我需要一个具有以下要求的ImageView:
所以我需要像这样Custom View by JakeWharton这样的东西CropImageView library。但后一个库只支持centerTop
或centerBottom
而不支持两者。
我想为此问题创建自己的CustomView。但我不知道怎么做。擅长实现自定义视图的人能给我一些提示吗?或者有人知道我可以满足这两个要求的图书馆吗?
答案 0 :(得分: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" />