Question

Is there any method that gets the phones resolution (or dp) and scales bitmaps accordingly? I have all my images in xhdpi folder and at the moment they do not scale the way they should.

I want an efficiant and memory-friendly method that can do the scaling automatically. If not, what is the next best thing? completely new area for me. So any tutorial-link is also appriciated.

this is what I use to load bitmaps atm:

public Bitmap loadBitmap(int resourceID) {
    Options options = new BitmapFactory.Options();
    options.inScaled = true;
    options.inPreferredConfig = Bitmap.Config.RGB_565;
    Bitmap tempBmp = null;
    try {
        tempBmp = BitmapFactory.decodeResource(getResources(), resourceID,
                options);
    } catch (OutOfMemoryError e) {

    } catch (Error e) {

    }
    return tempBmp;
}
Was it helpful?

Solution

If you wanna scale bitmap for each phone resolution, you should know phone screen size, scale ratio.

This code will return width (w) & height (h) of screen.

DisplayMetrics dMetrics = new DisplayMetrics();
activity.getWindowManager().getDefaultDisplay().getMetrics(dMetrics);
float density = dMetrics.density;
int w = Math.round(dMetrics.widthPixels / density);
int h = Math.round(dMetrics.heightPixels / density);

activity is instance of Activity which would you like to get screen size.

You have to remember that: When your device is in landscape orientation, w > h. When it in portrait orientation w < h.

So from width & height you can detect your device is in what orientation.

Example:

From w & h of device and ratio (which you want to scale) you can calculate new bitmap size to scale it.

public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) {
    int width = bm.getWidth();
    int height = bm.getHeight();
    float scaleWidth = ((float) newWidth) / width;
    float scaleHeight = ((float) newHeight) / height;
    // CREATE A MATRIX FOR THE MANIPULATION
    Matrix matrix = new Matrix();
    // RESIZE THE BIT MAP
    matrix.postScale(scaleWidth, scaleHeight);

    // "RECREATE" THE NEW BITMAP
    Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);
    return resizedBitmap;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top