[英]Android: How do I scale a bitmap to fit the screen size using canvas/draw bitmap?
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.
我还将绘制较小的图像,尽管不是全屏显示,我也需要根据屏幕的大小进行缩放。
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. frameToDraw
矩形的宽度和高度应为图片的宽度和高度。
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 (ie match_parent
), then use the scaleType
to scale/fit/crop the image how you want. 如果要编写具有
View
的应用程序,请使用全尺寸(即match_parent
)的ImageView
为布局添加膨胀,然后使用scaleType
缩放/调整/裁剪所需的图像。
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 ) frameBufferWidth
和frameBufferHeight
是您希望基于这些大小创建应用程序的大小(例如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 它根据屏幕尺寸绘制最终的位图
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.