Issue when scaling image using matrix in ImageView
I have the following snippet of code in the onCreate method of a class that extends Activity:
ImageView view = (Image开发者_运维百科View) findViewById(R.id.ImageView01);
BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
bmpFactoryOptions.inJustDecodeBounds = true;
Bitmap bmp = BitmapFactory.decodeResource(getResources(),
R.drawable.sample_landscape, bmpFactoryOptions);
Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();
Log.v("IMAGEVIEWERMATRIX", "Display Width: " + display.getWidth());
Log.v("IMAGEVIEWERMATRIX", "Display Height: " + display.getHeight());
Log.v("IMAGEVIEWERMATRIX", "BMP Width: " + bmpFactoryOptions.outWidth);
Log.v("IMAGEVIEWERMATRIX", "BMP Height: " + bmpFactoryOptions.outHeight);
if (bmpFactoryOptions.outWidth > width || bmpFactoryOptions.outHeight > height) {
float heightRatio = (float) height / (float) bmpFactoryOptions.outHeight;
float widthRatio = (float) width / (float) bmpFactoryOptions.outWidth;
// WHY
heightRatio = heightRatio / 1.5f;
widthRatio = widthRatio / 1.5f;
Log.v("IMAGEVIEWERMATRIX", "heightRatio:" + heightRatio);
Log.v("IMAGEVIEWERMATRIX", "widthRatio: " + widthRatio);
float scale = widthRatio;
if (heightRatio < widthRatio) {
scale = heightRatio;
}
matrix.setScale(scale, scale);
Log.v("IMAGEVIEWERMATRIX", "Scale: " + scale);
} else {
Log.v("IMAGEVIEWERMATRIX", "NOTNOTNOT");
matrix.setTranslate(1f, 1f);
}
Bitmap realBmp = BitmapFactory.decodeResource(getResources(),
R.drawable.sample_landscape);
view.setImageBitmap(realBmp);
view.setImageMatrix(matrix);
When I run it, the image appears on screen scaled to fit correctly. My issue is that I have to adjust the scale by 1.5 in order for this to be correct.
heightRatio = heightRatio / 1.5f;
widthRatio = widthRatio / 1.5f;
My intuition is that this has to do with the display density of the device but for the life of me, I can't wrap my head around why I would need to do this.
Here is the layout XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView android:id="@+id/ImageView01" android:scaleType="matrix" android:layout_width="wrap_content" android:layout_height="wrap_content"></ImageView>
</LinearLayout>
Ok, answering my own question here. The issue that I was seeing has to do with where I put the image asset. I had it in the res/drawable-mdpi folder only and the device I was testing on was high density. Therefore, Android was scaling the image up for me automagically. To rectify the situation and deal with the pixels directly, I placed the image in the res/drawable-nodpi folder.
This behavior is described on this page: http://developer.android.com/guide/practices/screens_support.html under "How Android supports multiple screens".
精彩评论