Creating a scaled bitmap with createScaledBitmap in Android

后端 未结 3 1975
野性不改
野性不改 2020-12-05 07:47

I want to create a scaled bitmap, but I seemingly get a dis-proportional image. It looks like a square while I want to be rectangular.

My code:

Bitma         


        
3条回答
  •  庸人自扰
    2020-12-05 08:27

    If you already have the original bitmap in memory, you don't need to do the whole process of inJustDecodeBounds, inSampleSize, etc. You just need to figure out what ratio to use and scale accordingly.

    final int maxSize = 960;
    int outWidth;
    int outHeight;
    int inWidth = myBitmap.getWidth();
    int inHeight = myBitmap.getHeight();
    if(inWidth > inHeight){
        outWidth = maxSize;
        outHeight = (inHeight * maxSize) / inWidth; 
    } else {
        outHeight = maxSize;
        outWidth = (inWidth * maxSize) / inHeight; 
    }
    
    Bitmap resizedBitmap = Bitmap.createScaledBitmap(myBitmap, outWidth, outHeight, false);
    

    If the only use for this image is a scaled version, you're better off using Tobiel's answer, to minimize memory usage.

提交回复
热议问题