I need an ImageView with the following requirements:
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?
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" />