In a simple word game app I load 26 letter tile images from a PNG-image stripe with the following code:
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);
}
This works well in Android emulator:
But on a real Moto G device the letters are too big (Maybe by 1.5 factor? When I print sContext.getResources().getDisplayMetrics().density
I for some reason get 2.0):
At the same time the yellow square tile backround is shown correctly.
All (big_tile.png and big_english.png and game_board.png) are PNG-images - so why the difference?
Why does it happen and how to fix this please?
Should I maybe use inDensity
or any other BitmapFactory.Options?
Or is it because of my getResources().openRawResource()
call - but what to use instead?
I also have the same problem with image, android devices came with many screen resolution. you will need either put alot of image into your drawable folder or give a set of rule of the image width and height to each screen resolution
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
. . and so on hope this can help you some how.
here some of my code(I use imageview not bitmap sorry):
int width, height;
//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;
}