unlimited101 unlimited101 - 28 days ago 18
Android Question

ImageView cropped top and bottom and fixed aspect ratio

I need an ImageView with the following requirements:


  • Its height has to be 50% of its width

  • The image has to be cropped at the top and the bottom



So i would need something like this Custom View by JakeWharton combined with something like this CropImageView library. But the latter library only support either
centerTop
or
centerBottom
and not both.

I would like to create an own CustomView for this issue. But I don't know how. Can who is good at implementing custom views give me some hints how to do that? Or does someone know a library with which I can satisfy both requirements?

Answer
  1. I use a custom ImageView with proportional height. In the onMeasure method the actual height is always replaced with a height proportional to the measured width.

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

    You could of course hardcode the proportion directly in that file. To be more flexible you can use styleable attributes. Then you need a resource XML file to define your custom attributes.

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

    Now you can use your view in a normal layout XML file using your custom attribute

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

  1. You may use a scale type on your ImageView like CENTER_CROP. This does not necessarily only crop the top and bottom, but it fills the ImageView and centers the image in it. If this is not a solution for you, you should be careful with the aspect ratio of the images your loading into the view. It may be that you get empty areas