[英]How to scale bitmaps based on device screen size in Android
I want to create images with sizes relevant to the size of the screen they are on. 我想创建与屏幕大小相关的图像。 Basically I have a scaled bitmap
50w * 50h
. 基本上我有一个缩放的位图
50w * 50h
。 I want it to be 50w * 50h
on a small device, slightly larger on a larger device, etc... Is there anyway to make a scaled bitmap relevant to the screen size it's on. 我希望在小型设备上将其设置为
50w * 50h
,在较大的设备上将其设置为稍大一点,以此类推。 I have that of making a dimen.xml
file with different dp
values for different screen width's. 我有一个
dimen.xml
文件,它针对不同的屏幕宽度使用不同的dp
值。 But it seems so demanding. 但这似乎要求很高。 Is there any easier way to do it?
有没有更简单的方法可以做到这一点? I have done some research but found nothing, can anyone help?
我已经做了一些研究,但没有发现任何结果,有人可以帮忙吗?
public class BitmapScaler {
// scale and keep aspect ratio
public static Bitmap scaleToFitWidth(Bitmap b, int width) {
float factor = width / (float) b.getWidth();
return Bitmap.createScaledBitmap(b, width, (int) (b.getHeight() * factor), true);
}
// scale and keep aspect ratio
public static Bitmap scaleToFitHeight(Bitmap b, int height) {
float factor = height / (float) b.getHeight();
return Bitmap.createScaledBitmap(b, (int) (b.getWidth() * factor), height, true);
}
// scale and keep aspect ratio
public static Bitmap scaleToFill(Bitmap b, int width, int height) {
float factorH = height / (float) b.getWidth();
float factorW = width / (float) b.getWidth();
float factorToUse = (factorH > factorW) ? factorW : factorH;
return Bitmap.createScaledBitmap(b, (int) (b.getWidth() * factorToUse),
(int) (b.getHeight() * factorToUse), true);
}
// scale and don't keep aspect ratio
public static Bitmap strechToFill(Bitmap b, int width, int height) {
float factorH = height / (float) b.getHeight();
float factorW = width / (float) b.getWidth();
return Bitmap.createScaledBitmap(b, (int) (b.getWidth() * factorW),
(int) (b.getHeight() * factorH), true);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.