ImageView 裁剪顶部和底部并固定纵横比

ImageView cropped top and bottom and fixed aspect ratio

我需要一个具有以下要求的 ImageView:

所以我需要这样的东西 Custom View by JakeWharton combined with something like this CropImageView library。但是后一个库只支持 centerTopcenterBottom 而不是两者。

我想为这个问题创建一个自己的 CustomView。但我不知道怎么办。谁擅长实现自定义视图可以给我一些提示如何做到这一点?或者有人知道可以满足这两个要求的库吗?

  1. 我使用具有比例高度的自定义 ImageView。在 onMeasure 方法中,实际高度始终替换为与测量宽度成比例的高度。

    public class ImageViewWithProportionalHeight extends ImageView {
    
        private float mProportion;
    
        public ImageViewWithProportionalHeight(Context context, AttributeSet attrs) {
            super(context, attrs);
    
            TypedArray attributes = context.obtainStyledAttributes(attrs, R.styleable.ProportionalHeight, 0, 0);
            mProportion = attributes.getFloat(R.styleable.ProportionalHeight_heightProportionToWidth, 0);
            attributes.recycle();
        }
    
        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            int width = MeasureSpec.getSize(widthMeasureSpec);
            int height = (int) (width * mProportion);
    
            super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
        }
    
    }
    

    您当然可以直接在该文件中对比例进行硬编码。为了更加灵活,您可以使用可样式化的属性。然后你需要一个资源 XML 文件来定义你的自定义属性。

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
        <declare-styleable name="ProportionalHeight">
            <attr name="heightProportionToWidth" format="float" />
        </declare-styleable>
    </resources>
    

    现在您可以使用自定义属性在普通布局 XML 文件中使用您的视图

    <your.package.name.ImageViewWithProportionalHeight
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:heightProportionToWidth="0.5" />
    

  1. 您可以在 ImageView 上使用 scale type,例如 CENTER_CROP。这不一定只裁剪顶部和底部,但它会填充 ImageView 并将图像居中。如果这不是您的解决方案,您应该注意加载到视图中的图像的纵横比。可能是你得到了空白区域