Change ImageView size and return a BitmapDrawable - Android Graphics

Android examples for Graphics:Bitmap Size

Description

Change ImageView size and return a BitmapDrawable

Demo Code


//package com.java2s;

import android.content.Context;

import android.graphics.Bitmap;

import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;

import android.widget.ImageView;

public class Main {
    public static BitmapDrawable sizeChanger(Context context,
            ImageView imageView, int sizeOnDps, int orientation) {
        Drawable drawing = imageView.getDrawable();
        if (drawing == null) {
            return null;
        }/* w  w w .  j  ava  2s .  c  om*/
        Bitmap bitmap = ((BitmapDrawable) drawing).getBitmap();

        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        int bounding = dpToPx(250, context);

        float xScale = ((float) bounding) / width;
        float yScale = ((float) bounding) / height;
        float scale = (xScale <= yScale) ? xScale : yScale;

        Matrix matrix = new Matrix();
        matrix.postScale(scale, scale);
        matrix.postRotate(orientation, imageView.getDrawable().getBounds()
                .width() / 2,
                imageView.getDrawable().getBounds().height() / 2);

        Bitmap scaledBitmap = Bitmap.createBitmap(bitmap, 0, 0, width,
                height, matrix, true);
        width = scaledBitmap.getWidth();
        height = scaledBitmap.getHeight();
        return new BitmapDrawable(scaledBitmap);
    }

    public static int dpToPx(int dp, Context context) {
        float density = context.getResources().getDisplayMetrics().density;
        return Math.round((float) dp * density);
    }
}

Related Tutorials