简单的自定义圆形或者圆角的ImageView

756 阅读1分钟

介绍一个简单的自定义圆角或者圆形view

RoundImageView.java

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Path;
import android.os.Build;
import android.util.AttributeSet;

public class RoundImageView extends androidx.appcompat.widget.AppCompatImageView {
    private Path path = null;
    private ShowType showType = ShowType.DEFAULT;
    private int cornerPx;

    public RoundImageView(Context context) {
        super(context);
    }

    public RoundImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public RoundImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public void draw(Canvas canvas) {
    	//未设置类型则显示图片默认的样子
        if (showType == ShowType.DEFAULT) {
            super.draw(canvas);
        } else {
            if (path == null) {
                path = new Path();
            }
            if (showType == ShowType.CIRCLE) {//圆形图片
                path.addCircle(getMeasuredWidth() / 2, getMeasuredHeight() / 2, getMeasuredHeight() / 2, Path.Direction.CCW);
                canvas.save();
                canvas.clipPath(path);
                super.draw(canvas);
                canvas.restore();
            } else if (showType == ShowType.ROUNDRECT) {//圆角图片
                //其他的圆角矩形在课程页面使用有bug,此类则不会有
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//显示圆角仅支持到安卓6.0
                    canvas.save();
                    path.addRoundRect(0, 0, getMeasuredWidth(), getMeasuredHeight(), cornerPx, cornerPx, Path.Direction.CCW);
                    canvas.clipPath(path);
                    super.draw(canvas);
                    canvas.restore();
                }else{//其他的走默认逻辑把
                    super.draw(canvas);
                }
            }
        }
    }

    public enum ShowType {
        DEFAULT, CIRCLE, ROUNDRECT
    }

    public void setShowType(ShowType showType) {
        this.showType = showType;
    }

    public void setCornerPx(int cornerPx) {
        this.cornerPx = cornerPx;
    }
}

使用

只需要在布局中像使用ImageView那样使用此view,然后代码中设置显示类型就好啦.

布局中使用

<com.koolearn.toefl2019.view.RoundImageView
        android:id="@+id/kingGongImg"
        android:src="@drawable/kinggong_default_icon"
        android:scaleType="centerCrop"
        android:layout_width="48dp"
        android:layout_height="48dp"/>

代码中设置

//设置显示为圆形
kingGongImg.setShowType(RoundImageView.ShowType.CIRCLE);

//设置显示为圆角矩形
liveAvater.setShowType(RoundImageView.ShowType.ROUNDRECT);
liveAvater.setCornerPx(Utils.dp2px(5));