Resizing ImageView to fit to aspect ratio

后端 未结 3 1028
夕颜
夕颜 2020-11-30 06:20

I need to resize an ImageView such that it fits to the screen, maintains the same aspect ratio. The following conditions hold:

  • Images are a fixed width (size o
3条回答
  •  难免孤独
    2020-11-30 06:41

    I created it with the help of this Bob Lee's answer in this post: Android: How to stretch an image to the screen width while maintaining aspect ratio?

    package com.yourpackage.widgets;
    
    import android.content.Context;
    import android.util.AttributeSet;
    import android.widget.ImageView;
    
    public class AspectRatioImageView extends ImageView {
    
        public AspectRatioImageView(Context context) {
            super(context);
        }
    
        public AspectRatioImageView(Context context, AttributeSet attrs) {
            super(context, attrs);
        }
    
        public AspectRatioImageView(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
        }
    
        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            int width = MeasureSpec.getSize(widthMeasureSpec);
            int height = width * getDrawable().getIntrinsicHeight() / getDrawable().getIntrinsicWidth();
            setMeasuredDimension(width, height);
        }
    }
    

    Now to use it in the XML:

    
    

    Have fun!

提交回复
热议问题