有时候我们自定义一个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
如对本文有疑问, 点击进行留言回复!!
荐 面试官:kafka日志段如何读写都不知道,好意思说精通Kafka吗?
荐 如何写出一份“有理有据使人信服”的Android项目设计文档
荐 灵魂一问,Android中有代替HashMap的方法吗?
intent.setFlag的参数 FLAG_ACTIVITY_CLEAR_TASK 说明
网友评论