(在澄清原问题后,答案进行了大幅修改)
经过澄清:
这个问题不能仅通过xml实现。无法同时缩放图像和ImageView
,使得图像的一个维度始终为250dp,并且ImageView
的尺寸与图像相同。
此代码将 ImageView
的 Drawable
缩放到一个正方形中,大小为250dp x 250dp,其中一个维度恰好为250dp,并保持宽高比。然后,ImageView
被调整大小以匹配缩放后的图像的尺寸。该代码用于活动中。我通过按钮点击处理程序进行了测试。
祝使用愉快。:)
private void scaleImage(ImageView view) throws NoSuchElementException {
Bitmap bitmap = null;
try {
Drawable drawing = view.getDrawable();
bitmap = ((BitmapDrawable) drawing).getBitmap();
} catch (NullPointerException e) {
throw new NoSuchElementException("No drawable on given view");
} catch (ClassCastException e) {
bitmap = Ion.with(view).getBitmap();
}
int width = 0;
try {
width = bitmap.getWidth();
} catch (NullPointerException e) {
throw new NoSuchElementException("Can't find bitmap on given view/drawable");
}
int height = bitmap.getHeight();
int bounding = dpToPx(250);
Log.i("Test", "original width = " + Integer.toString(width));
Log.i("Test", "original height = " + Integer.toString(height));
Log.i("Test", "bounding = " + Integer.toString(bounding));
float xScale = ((float) bounding) / width;
float yScale = ((float) bounding) / height;
float scale = (xScale <= yScale) ? xScale : yScale;
Log.i("Test", "xScale = " + Float.toString(xScale));
Log.i("Test", "yScale = " + Float.toString(yScale));
Log.i("Test", "scale = " + Float.toString(scale));
Matrix matrix = new Matrix();
matrix.postScale(scale, scale);
Bitmap scaledBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
width = scaledBitmap.getWidth();
height = scaledBitmap.getHeight();
BitmapDrawable result = new BitmapDrawable(scaledBitmap);
Log.i("Test", "scaled width = " + Integer.toString(width));
Log.i("Test", "scaled height = " + Integer.toString(height));
view.setImageDrawable(result);
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) view.getLayoutParams();
params.width = width;
params.height = height;
view.setLayoutParams(params);
Log.i("Test", "done");
}
private int dpToPx(int dp) {
float density = getApplicationContext().getResources().getDisplayMetrics().density;
return Math.round((float)dp * density);
}
ImageView
的xml代码:
<ImageView a:id="@+id/image_box"
a:background="#ff0000"
a:src="@drawable/star"
a:layout_width="wrap_content"
a:layout_height="wrap_content"
a:layout_marginTop="20dp"
a:layout_gravity="center_horizontal"/>
感谢这篇讨论提供的缩放代码:
http://www.anddev.org/resize_and_rotate_image_-_example-t621.html
更新于2012年11月7日:
根据评论建议添加了空指针检查。
ImageView
的大小更改为图像大小吗?例如,100dp x 150dp的图像将缩放ImageView
到相同的尺寸?还是您想知道如何将图像缩放到ImageView
边界。例如,1000dp x 875dp的图像将缩放为250dp x 250dp。您需要保持纵横比吗? - Jarno Argillander