美文网首页Android深入
Android 自定义ImageView 填充比例的图片

Android 自定义ImageView 填充比例的图片

作者: zhengLH | 来源:发表于2018-10-13 13:29 被阅读105次

【情景1】启动页广告位:需要按照图片比例铺满整个ImageView 控件,这时候图片的填充效果类似centerCrop;

【情景2】全局弹出框:需要根据ImageView固定宽高比,去重新计算图片的宽高。

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;

public class AlignBottomImageView extends   android.support.v7.widget.AppCompatImageView {

public AlignBottomImageView(Context context) {
    super(context);
    // TODO Auto-generated constructor stub
}

public AlignBottomImageView(Context context, AttributeSet attrs) {
    super(context, attrs);
    // TODO Auto-generated constructor stub
}

public AlignBottomImageView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    // TODO Auto-generated constructor stub
}

@Override
public void setImageDrawable(Drawable drawable) {
    super.setImageDrawable(drawable);
    setDrawableBound(drawable);
}

public void setDrawableBound(Drawable drawable) {
    if (drawable != null) {
        int width = getWidth();
        int height = getHeight();
        int drawableWidth = drawable.getIntrinsicWidth();
        int drawableHeight = drawable.getIntrinsicHeight();
        if (width != 0
                && height != 0
                && drawableWidth != 0
                && drawableHeight != 0) {

            // 思路:按照图片的比例
            if (drawableWidth * height > width * drawableHeight) {  // 图片的宽高比 比较大
                // 情景1
                /*int offset = (drawableWidth * height / drawableHeight - width) / 2;
                drawable.setBounds(-offset, 0, width + offset, height);*/

               // 情景2
                int dw = drawableHeight *  width / height ;
                int offset = (width -dw)/2;
                drawable.setBounds( offset, 0, width- offset, height);

            } else {  // 反之
                int offset = drawableHeight * width / drawableWidth - height;
                drawable.setBounds(0, -offset, width, height);
                invalidate();
            }
        }
    }
}

@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
    super.onLayout(changed, left, top, right, bottom);
    setDrawableBound(getDrawable());
}

@Override
protected void onDraw(Canvas canvas) {
 //     super.onDraw(canvas);
    Drawable drawable = getDrawable();
    if (drawable != null) {
        drawable.draw(canvas);
    }
  }
 }

相关文章

网友评论

    本文标题:Android 自定义ImageView 填充比例的图片

    本文链接:https://www.haomeiwen.com/subject/ezcoaftx.html