Android:如何使用画布/绘制位图缩放位图以适合屏幕大小? [英] Android: How do I scale a bitmap to fit the screen size using canvas/draw bitmap?

查看:205
本文介绍了Android:如何使用画布/绘制位图缩放位图以适合屏幕大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在拍摄图像,并使用画布将其绘制到屏幕上.我想根据屏幕尺寸缩放它.

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).

frameToDraw矩形的宽度和高度应为图片的宽度和高度.

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

这篇关于Android:如何使用画布/绘制位图缩放位图以适合屏幕大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆