ImageView裁剪了顶部和底部以及固定的宽高比

时间:2016-04-06 16:00:50

标签: android android-custom-view crop aspect-ratio

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

  • 它的高度必须是其宽度的50%
  • 图像必须在顶部和底部裁剪

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

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

1 个答案:

答案 0 :(得分:1)

  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并将图像居中。如果这不是您的解决方案,您应该小心加载到视图中的图像的宽高比。可能是你得到空白区域