Android ImageView topCrop/bottomCrop scaletype?

旧巷老猫 提交于 2019-12-04 13:12:27

You won't be able to do that with a regular ImageView and it's properties in xml. You can accomplish that with a proper scaleType Matrix, but tbh writing it is a pain in the ass. I'd suggest you use a respected library that can handle this easily. For example CropImageView.

You probably can't do this in layout. But it's possible with a piece of code like this:

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);
            }
        }
    });
}

Note that if your ImageView has predefined size (likely it has) then you need to put this size to dimen resources and the code will be even simpler:

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);
}

See also:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!