Android ImageView高度固定,宽度按比例自适应显示

1

        如图所示,需要高度固定死,宽度需要根据比例来自适应显示,于是找了资料,通过自定义view实现,重写onMeasure方法:

public class ResizableImageView extends androidx.appcompat.widget.AppCompatImageView {

    public ResizableImageView(Context context) {

        super(context);

}

    public ResizableImageView(Context context, AttributeSet attrs) {

        super(context, attrs);

}

    @Override

    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

        Drawable d = getDrawable();

        if (d != null) {

            // ceil not round - avoid thin vertical gaps along the left/right edges

            int width = View.MeasureSpec.getSize(widthMeasureSpec);

            //高度根据使得图片的宽度充满屏幕计算而得

            int height = (int) Math.ceil((float) width * (float) d.getIntrinsicHeight() / (float) d.getIntrinsicWidth());

            setMeasuredDimension(width, height);

        } else {

            super.onMeasure(widthMeasureSpec, heightMeasureSpec);

}

}

}

你可能感兴趣的:(Android ImageView高度固定,宽度按比例自适应显示)