让自定义view宽高成比例显示

时间:2022-12-19 23:46:02

有时候我们自定义一个View,比如ImageView,我们需要让它宽高按照一定的比例显示,例如在ImageView在GridView中显示,GridView设置了3列,由于ImageVIew的宽度会根据屏幕的大小进行缩放的,如果不设置高度与宽度成一定比例的话,那么可能会由于屏幕大小的变化而让ImageView的宽高比例失调。

那么怎么做到让高度根据宽度的改变而成比例改变呢?

 

重写ImageView的onMesure()方法:

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (ratioHeight > 0 && ratioWidth > 0) {
int originalWidth = MeasureSpec.getSize(widthMeasureSpec); int calculatedHeight = originalWidth * ratioHeight / ratioWidth; super.onMeasure(
MeasureSpec.makeMeasureSpec(originalWidth, MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(calculatedHeight, MeasureSpec.EXACTLY));
} else {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
originalWidth * ratioHeight / ratioWidth;便是宽高比例。

我们可以自定义属性
ratioHeight与ratioWidth 然后我们可以在布局当中写上(假如设定宽高比例为1:2的话)
ratioWidth:1
ratioHeight:2