resize Drawable For Screen - Android android.graphics.drawable

Android examples for android.graphics.drawable:Drawable

Description

resize Drawable For Screen

Demo Code


import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;

public class Main {
  public static Drawable resizeDrawableForScreen(Context ctx, int image) {
    int deviceWidth = ctx.getResources().getDisplayMetrics().widthPixels;

    BitmapDrawable bitMap = (BitmapDrawable) ctx.getResources().getDrawable(image);
    double imgWidth = bitMap.getBitmap().getWidth();
    double imgHeight = bitMap.getBitmap().getHeight();

    double ratio = deviceWidth / imgWidth;
    int newImageHeight = (int) (imgHeight * ratio);

    Bitmap bMap = BitmapFactory.decodeResource(ctx.getResources(), image);
    Drawable drawable = new BitmapDrawable(ctx.getResources(), resizedBitmap(bMap, newImageHeight, (int) deviceWidth));

    return drawable;
  }//w w  w  . j a v a 2  s  .  c  om

  private static Bitmap resizedBitmap(Bitmap bMap, int newHeight, int newWidth) {
    float scaleWidth = ((float) newWidth) / bMap.getWidth();
    float scaleHeight = ((float) newHeight) / bMap.getHeight();

    Matrix matrix = new Matrix();
    matrix.postScale(scaleWidth, scaleHeight);

    Bitmap resizedBitmap = Bitmap.createBitmap(bMap, 0, 0, bMap.getWidth(), bMap.getHeight(), matrix, false);
    return resizedBitmap;
  }
}

Related Tutorials