简体   繁体   English

如何在Android中的View.Canvas上缩放位图?

[英]How to scale bitmaps on View.Canvas in Android?

I have a View-derived class where I draw a 790x500 (yes, this is odd but it has to stay this way) bitmap directly on the canvas in onDraw . 我有一个View派生类,我在onDraw的画布上直接绘制一个790x500(是的,这很奇怪,但它必须保持这种方式)位图。 This looks ok on my Nexus S, but when I run my app on a device with a smaller screen (eg Wildfire) I only see the upper left part of the bitmap. 这在我的Nexus S上看起来不错,但是当我在具有较小屏幕的设备上运行我的应用程序(例如Wildfire)时,我只看到位图的左上角部分。 What am I missing here? 我在这里错过了什么?

This is a game-like app where I draw a number of bitmaps on certain coordinates. 这是一个类似游戏的应用程序,我在某些坐标上绘制了许多位图。 I really don't want to have different pixel setups for LDPI, MDPI and HDPI (I have a good reason for this). 我真的不想为LDPI,MDPI和HDPI设置不同的像素设置(我有充分的理由)。

Q: How can I properly scale my bitmaps for any screen resolution? 问:如何针对任何屏幕分辨率正确缩放我的位图? (Centering the game screen for large screens may be an option, but is not a must.) Eg when I draw a 800x600 image on a 320x240 screen, the image is automatically stretched and when I output a pixel at 100x100, it becomes 40x40. (将屏幕的游戏屏幕居中可能是一个选项,但不是必须的。)例如,当我在320x240屏幕上绘制800x600图像时,图像会自动拉伸,当我以100x100输出像素时,它会变为40x40。

There are many forms of the drawbitmap() method. drawbitmap()方法有很多种形式。 Choose the one that allows you to specify the source and destination rectangle. 选择允许您指定源矩形和目标矩形的那个。 The source rectangle will be the size of your bitmap and the destination rectangle will be scaled to fit on the device display. 源矩形将是位图的大小,目标矩形将缩放以适合设备显示。 Android will scale your bitmap when it draws it. Android会在绘制位图时缩放您的位图。

Rect rs = new Rect();
Rect rd = new Rect();
rs.left = rs.top = 0;
rs.right = 789;
rs.bottom = 499;

<calculate destination rectangle from device size>

canvas.drawBitmap(myBitmap, rs, rd, null);

You can also scale and translate (shift) the entire canvas 您还可以缩放和转换(移动)整个画布

canvas.scale(float scaleX, float scaleY);
canvas.translate(float dx, float dy);

Canvas.scale()可以解决这个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM