安卓ImageView的topCrop/bottomCrop缩放类型是什么?

3
我有一个正方形的ImageView,用于显示尺寸不同的图片。我想始终保持图片的原始长宽比,并且没有图像周围的空白(使图像占据整个ImageView)。为此,我在ImageView上使用了centerCrop scaleType。但是,如果图像的顶部和底部被裁剪掉(即:图像的高度大于宽度),我希望将图像拉向容器的底部。因此,图像的顶部和侧面与ImageView齐平,图像底部裁剪掉的像素数量是顶部的两倍。这是否可以在xml中实现?如果不能,在Java中有解决方案吗?
2个回答

4
你不能用普通的ImageView和xml中的属性来实现这个功能。你可以使用适当的scaleType Matrix来完成此操作,但是写起来相当麻烦。我建议你使用一个受人尊敬的库来轻松处理此问题。例如CropImageView

虽然 @praetorian 的回答可能有效(没有测试),但是因为我在多个地方使用它,而且不想在每个使用它的地方都有那段代码,所以这种方法对于我的应用程序来说更简单实现。 - Brandon Slaght

2
您可能无法在布局中完成此操作。但是使用类似以下代码的代码片段是可能的:
final ImageView image = (ImageView) findViewById(R.id.image);
// Proposing that the ImageView's drawable was set
final int width = image.getDrawable().getIntrinsicWidth();
final int height = image.getDrawable().getIntrinsicHeight();
if (width < height) {
    // This is just one of possible ways to get a measured View size
    image.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            int measuredSize = image.getMeasuredWidth();
            int offset = (int) ((float) measuredSize * (height - width) / width / 2);
            image.setPadding(0, offset, 0, -offset);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                image.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            } else {
                image.getViewTreeObserver().removeGlobalOnLayoutListener(this);
            }
        }
    });
}

请注意,如果您的ImageView有预定义的大小(很可能是这样),那么您需要将此大小放入dimen资源中,代码将变得更加简单:
ImageView image = (ImageView) findViewById(R.id.image2);
// For sure also proposing that the ImageView's drawable was set
int width = image.getDrawable().getIntrinsicWidth();
int height = image.getDrawable().getIntrinsicHeight();
if (width < height) {
    int imageSize = getResources().getDimensionPixelSize(R.dimen.image_size);
    int offset = (int) ((float) imageSize * (height - width) / width / 2);
    image.setPadding(0, offset, 0, -offset);
}

另请参阅:


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接