Android How to - Scale a bitmap relative to a view








Question

We would like to know how to scale a bitmap relative to a view.

Answer

/* w ww.ja  va  2  s . c  o m*/
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.Point;
import android.view.View;

 class BitmapAXT {

    private final Bitmap bitmap;

    public BitmapAXT(Bitmap bitmap) {
        this.bitmap = bitmap;
    }
    public Bitmap scaleRelative2View(View view, float inScaleX, float inScaleY) {
        // create a matrix for the manipulation
        Matrix matrix = new Matrix();

        float outScaleX, outScaleY;
        if (inScaleY != 0f) {
            // take the given y scale
            outScaleY = (view.getHeight() * inScaleY) / bitmap.getHeight();
        } else {
            // take outScaleX
            outScaleY = (view.getWidth() * inScaleX) / bitmap.getWidth();
        }

        if (inScaleX != 0f) {
            // take the given x scale
            outScaleX = (view.getWidth() * inScaleX) / bitmap.getWidth();
        } else {
            // take the given y scale
            outScaleX = (view.getHeight() * inScaleY) / bitmap.getHeight();
        }

        matrix.postScale(outScaleX, outScaleY);

        return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
    }
}