1// Copyright (c) 2012 The Chromium Authors. All rights reserved. 2// Use of this source code is governed by a BSD-style license that can be 3// found in the LICENSE file. 4 5package org.chromium.ui.gfx; 6 7import android.content.res.Resources; 8import android.graphics.Bitmap; 9import android.graphics.BitmapFactory; 10import org.chromium.base.CalledByNative; 11import org.chromium.base.JNINamespace; 12 13@JNINamespace("ui") 14public class BitmapHelper { 15 @CalledByNative 16 public static Bitmap createBitmap(int width, int height) { 17 return Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); 18 } 19 20 /** 21 * Decode and sample down a bitmap resource to the requested width and height. 22 * 23 * @param name The resource name of the bitmap to decode. 24 * @param reqWidth The requested width of the resulting bitmap. 25 * @param reqHeight The requested height of the resulting bitmap. 26 * @return A bitmap sampled down from the original with the same aspect ratio and dimensions. 27 * that are equal to or greater than the requested width and height. 28 */ 29 @CalledByNative 30 private static Bitmap decodeDrawableResource(String name, 31 int reqWidth, 32 int reqHeight) { 33 Resources res = Resources.getSystem(); 34 int resId = res.getIdentifier(name, null, null); 35 36 final BitmapFactory.Options options = new BitmapFactory.Options(); 37 options.inJustDecodeBounds = true; 38 BitmapFactory.decodeResource(res, resId, options); 39 40 options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); 41 42 options.inJustDecodeBounds = false; 43 return BitmapFactory.decodeResource(res, resId, options); 44 } 45 46 // http://developer.android.com/training/displaying-bitmaps/load-bitmap.html 47 private static int calculateInSampleSize(BitmapFactory.Options options, 48 int reqWidth, 49 int reqHeight) { 50 // Raw height and width of image 51 final int height = options.outHeight; 52 final int width = options.outWidth; 53 int inSampleSize = 1; 54 55 if (height > reqHeight || width > reqWidth) { 56 57 // Calculate ratios of height and width to requested height and width 58 final int heightRatio = Math.round((float) height / (float) reqHeight); 59 final int widthRatio = Math.round((float) width / (float) reqWidth); 60 61 // Choose the smallest ratio as inSampleSize value, this will guarantee 62 // a final image with both dimensions larger than or equal to the 63 // requested height and width. 64 inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio; 65 } 66 67 return inSampleSize; 68 } 69} 70