Maintaining Image quality when creating scaled bitmap in android

僤鯓⒐⒋嵵緔 提交于 2020-01-03 21:07:18

问题


I have an image of dimension 960x800 and I am trying to make it fill the screen.

The way I have been currently doing it is by loading the full 960x800 bitmap and using source and destination Rect objects. So far example, my destination rectangle is 480x320 (the dimensions of my screen) and the source rectangle will be 960x800.

background = BitmapFactory.decodeResource(getResources(), R.drawable.background, null);
destRect = new Rect(0,0, screenWidth, screenHeight);
sourceRect = new Rect(0,0, background.getWidth(), background.getHeight());
...
c.drawBitmap(background, sourceRect, destRect, backgroundPaint);

If I then use a Paint object and set dither true when trying the background to the canvas, the image looks absolutely perfect.

Paint backgroundPaint = new Paint();
backgroundPaint .setDither(true);

I have concluded that this may not be very efficient, causing unnecessary work to be done on each draw call. To combat this, I want to try and do the following:

background = BitmapFactory.decodeResource(getResources(), R.drawable.background, null);
background = Bitmap.createScaledBitmap(background, display.getWidth(), display.getHeight(), true);

Thereby creating an already sized bitmap, elminating the need for any Rect objects. However, when doing this I cannot retain the same image quality as I can with the above method. In fact, the image looks similar to that which can be seen if I do not use a Paint object with the aforementioned method. Using the paint object on the scaled bitmap has seemingly no effect.

To give an example of how my image looks, it is similar to this picture (althought not as severe)

Is there something I can do to get the same image quality?


回答1:


this is the condition if you want your image to be of width 140nyour height will get resized automatically

    Bitmap originalBitmap = BitmapFactory.decodeFile(getResources(), R.drawable.background, null);
    Bitmap bitmap=originalBitmap;
    if (bitmap !=null) {
        int h = bitmap.getHeight();
        int w = bitmap.getWidth();
        h = 140*h/w;
        w = 140;
        bitmap = Bitmap.createScaledBitmap(bitmap, w, h, true);
        setIconImage(bitmap);
    }


来源:https://stackoverflow.com/questions/8372313/maintaining-image-quality-when-creating-scaled-bitmap-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!