在 a simple word game app我从 PNG-image stripe 加载 26 个字母平铺图像使用以下代码:
private static final CharacterIterator ABC =
new StringCharacterIterator("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
private static HashMap<Character, Bitmap> sImages =
new HashMap<Character, Bitmap>();
BitmapRegionDecoder decoder = null;
InputStream is = sContext.getResources()
.openRawResource(R.drawable.big_english);
try {
decoder = BitmapRegionDecoder.newInstance(is, false);
} catch (IOException ex) {
}
int h = decoder.getHeight();
Rect r = new Rect(0, 0, h, h);
for (char c = ABC.first();
c != CharacterIterator.DONE;
c = ABC.next(), r.offset(h, 0)) {
Bitmap bmp = decoder.decodeRegion(r, null);
sImages.put(c, bmp);
}
这在 Android 模拟器中运行良好:
但是在真正的 Moto G 设备上,字母太大(也许是 1.5 倍?当我打印 sContext.getResources().getDisplayMetrics().密度
时,由于某种原因,我得到了 2.0):
同时the yellow square tile backround正确显示。
所有( big_tile.png 和 big_english.png 和 game_board.png )都是 PNG 图像 - 那么为什么有区别?
为什么会发生这种情况以及如何解决这个问题?
我应该使用inDensity
或任何其他BitmapFactory.Options ?
或者是因为我的 getResources().openRawResource()
调用 - 但该使用什么来代替?
最佳答案
我也有同样的图像问题,Android 设备有很多屏幕分辨率。您需要将大量图像放入可绘制文件夹中,或者为每个屏幕分辨率提供一组图像宽度和高度规则
for example:
if screen_resolution = 4 inch
int img_height = 200
int img_width = 200
else if screen_resolution = 5 inch
int img_height = 300
int img_width = 300
。 。 等等 希望这可以对您有所帮助。
这里是我的一些代码(抱歉,我使用 imageview 而不是位图):
int 宽度,高度;
//calculate device screen
DisplayMetrics metrics=new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
float height=metrics.heightPixels/metrics.xdpi;
float width=metrics.widthPixels/metrics.ydpi;
float inchscreen = FloatMath.sqrt(height*height+width*width);
if (inchscreen > 4.1000)
{
//set image height for device above 4.1 inch screen
height = 400;
width = 400
}
else {
//set image height for device below 4.1 inch screen
height = 280;
width = 280
}
if (imgfile != null) {
int imageResource = getResources().getIdentifier(uri, null,
getPackageName());
Drawable image = getResources().getDrawable(imageResource);
imageview.setImageDrawable(image);
imageview.getLayoutParams().height = h_display;
imageview.getLayoutParams().width = h_display;
}
关于android - 使用 BitmapRegionDecoder 加载的图像在模拟器上没问题,但在设备上太大,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26893157/