答案 0 :(得分:2)
您需要使用矩阵缩放并自行设置矩阵。这并不难。
在布局视图后,您必须执行此操作,以便获得ImageView
的尺寸。您还需要设置Drawable
或Bitmap
的尺寸。
首先,您要弄清楚您需要多少缩放(乘)图像,以使高度与ImageView
的高度相同。为此,您只需将ImageView
高度除以图像高度。
现在您也知道图像的宽度。要获得图像的右边缘并使ImageView
对齐,您需要将图像向左移动(平移),然后将其移回ImageView
的宽度。因此,平移只是图像宽度与ImageView
宽度的差异。
我是这样做的:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ImageView imageView = (ImageView) findViewById(R.id.imageview);
imageView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
BitmapDrawable drawable = null;
if (Build.VERSION.SDK_INT >= 21) {
drawable = (BitmapDrawable) getResources().getDrawable(R.drawable.sunset, getTheme());
} else {
drawable = (BitmapDrawable) getResources().getDrawable(R.drawable.sunset);
}
Bitmap bitmap = drawable.getBitmap();
// get the scale factor that will have to be applied to
// the image to make it the same height as your ImageView
float factor = (float) imageView.getHeight() / (float) bitmap.getHeight();
// now the image will have to be shifted over all of its
// width minus the width of the ImageView. This will make
// the right edges line up.
int scaledImageWidth = (int) (bitmap.getWidth() * factor);
int translateX = imageView.getWidth() - scaledImageWidth;
// you can also use drawable.getIntrinsicWidth() and
// drawable.getIntrinsicHeight()
Matrix matrix = new Matrix();
matrix.setScale(factor, factor);
matrix.postTranslate(translateX, 0);
imageView.setScaleType(ImageView.ScaleType.MATRIX);
imageView.setImageMatrix(matrix);
imageView.setImageBitmap(bitmap);
}
});
}