当前位置: 移动技术网 > 移动技术>移动开发>Android > 让自定义view宽高成比例显示

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

2018年09月14日  | 移动技术网移动技术  | 我要评论

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


如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网