Java tutorial
//package com.java2s; import android.content.Context; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; public class Main { /** Default canvas used to interact with bitmaps */ private static Canvas canvas = new Canvas(); /** * Resize a {@link Drawable} to the given size.<br /> * Metrics and density are given by the {@link Resources} bount to this instance. * @param ctx Context. * @param id The desired resource identifier, as generated by the aapt tool. This integer encodes the package, type, and resource entry. The value 0 is an invalid identifier. * @param widthId Reference to the dimension containing the desired width. * @param heightId Reference to the dimension containing the desired height. * @return A scaled {@link Drawable}. */ public static Drawable resizeDrawable(Context ctx, int id, int widthId, int heightId) { return resizeDrawable(ctx, ctx.getResources().getDrawable(id), widthId, heightId); } /** * Resize a {@link Drawable} to the given size.<br /> * Metrics and density are given by the {@link Resources} bount to this instance. * @param ctx Context. * @param drawable {@link Drawable} to resize. * @param widthId Reference to the dimension containing the desired width. * @param heightId Reference to the dimension containing the desired height. * @return A scaled {@link Drawable}. */ public static Drawable resizeDrawable(Context ctx, Drawable drawable, int widthId, int heightId) { Resources res = ctx.getResources(); //float density = res.getDisplayMetrics().density; //Get a bitmap from the drawable Bitmap bmp = drawableToBitmap(drawable); //Create a scaled bitmap // bmp = Bitmap.createScaledBitmap( // bmp, // (int)(width * density), // (int)(height * density), // true); bmp = Bitmap.createScaledBitmap(bmp, res.getDimensionPixelSize(widthId), res.getDimensionPixelSize(heightId), true); //Convert bitmap to drawable return new BitmapDrawable(res, bmp); } /** * Return the {@link Bitmap} representing the {@link Drawable}. * @param drawable Object to convert to {@link Bitmap}. * @return {@link Bitmap} representing the {@link Drawable}. */ private static Bitmap drawableToBitmap(Drawable drawable) { Bitmap retVal; if (drawable instanceof BitmapDrawable) { //Easy retVal = ((BitmapDrawable) drawable).getBitmap(); } else { drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight()); retVal = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888); synchronized (canvas) { canvas.setBitmap(retVal); drawable.draw(canvas); } } return retVal; } }