Fixed aspect ratio View

后端 未结 9 1799
后悔当初
后悔当初 2020-12-04 10:50

How would I go implementing a fixed aspect ratio View? I\'d like to have items with 1:1 aspect ratio in a GridView. I think it\'s better to subclas

9条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-04 11:38

    Simply override onSizeChanged and calculate ratio there.

    Formula for aspect ratio is:

    newHeight =  original_height / original_width x new_width
    

    this would give you something like that:

     @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
    
        //3:5 ratio
        float RATIO = 5/3;
        setLayoutParams(new LayoutParams((int)RATIO * w, w));
    
    }
    

    hope this helps!

提交回复
热议问题