How to dynamically change ImageView Height

后端 未结 2 1943
慢半拍i
慢半拍i 2021-01-13 01:28

I have a simple linear layout used for ListView\'s cell, and it has an imageview. The image will be downloaded from internet, so the size can be different sizes.

How

2条回答
  •  时光取名叫无心
    2021-01-13 02:12

    You will need to subclass ImageView

    Override the onMeasure, I haven't tested this but all the variables you need are there and the idea is correct. You just perform the apply the aspect ratio of the image to the imageviews height, and if it's greater than the width, set it to the width.

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
    {
        Drawable drawable = getDrawable();
        if (drawable != null)
        {
            //get imageview width
            int width =  MeasureSpec.getSize(widthMeasureSpec);
    
    
            int diw = drawable.getIntrinsicWidth();
            int dih = drawable.getIntrinsicHeight();
            float ratio = (float)diw/dih; //get image aspect ratio
    
            int height = width * ratio;
    
            //don't let height exceed width
            if (height > width){
                height = width;
            }
    
    
            setMeasuredDimension(width, height);    
        }
        else
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    
    }
    

提交回复
热议问题