Android: How do I scale a bitmap to fit the screen size using canvas/draw bitmap?

雨燕双飞 提交于 2019-12-02 03:24:21

问题


I am taking an image and drawing it to the screen using canvas. I want to scale it based on the screen size.

This is what I tried, but it cuts off a large chunk of the image:

DisplayMetrics metrics = context.getResources().getDisplayMetrics();
int width = metrics.widthPixels;
int height = metrics.heightPixels;

Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(),R.drawable.myimage);
bitmap = Bitmap.createScaledBitmap(bitmap, width, height, false);

Rect frameToDraw = new Rect(0, 0, width, height);
RectF whereToDraw = new RectF(0, 0, width, height);

canvas.drawBitmap(bitmap,frameToDraw,whereToDraw, paint);

I know I am doing a few things wrong, but I'm not exactly sure what. This code causes the image to exceed the size of the screen. I want it to be scaled to the size of the screen. I'll be drawing smaller images in too that I also will need to scale according to the size of the screen, though not to the full screen.


回答1:


Rect frameToDraw = new Rect(0, 0, width, height);
RectF whereToDraw = new RectF(0, 0, width, height);

Take a look at the above code. Your are not scaling the picture. You are simply taking a part of the picture (in this case the whole picture) and pasting it somewhere (in this case the size of the original picture).

The width and heigth of the frameToDraw rectangle should be the width and height of your picture.




回答2:


    DisplayMetrics metrics = context.getResources().getDisplayMetrics();
    int width = metrics.widthPixels;
    int height = metrics.heightPixels;

If you get your width and height like this, you aren't going to take the size of any toolbar/status bar/navigation bar into account.

If you are coding an app that has a View, inflate a layout with an ImageView that is full size (i.e. match_parent), then use the scaleType to scale/fit/crop the image how you want.




回答3:


dont need creat scale bitmap, instead:

Bitmap frameBuffer = Bitmap.createBitmap(frameBufferWidth,frameBufferHeight, Config.RGB_565);

frameBufferWidth and frameBufferHeight are the sizes that you want to make your app base on those(for example 480*800)

then simply add this code:

Rect dstRect = new Rect();
canvas.getClipBounds(dstRect); // get canvas size base screen size
canvas.drawBitmap(framebuffer, null, dstRect, null);

it draw your final bitmap according to screen size



来源:https://stackoverflow.com/questions/38573926/android-how-do-i-scale-a-bitmap-to-fit-the-screen-size-using-canvas-draw-bitmap

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