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

有时候我们自定义一个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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值