Android中ImageView半边圆角处理记录2

125啦读书导航,我的单页导航

前言

之前介绍过对ImageView进行圆角处理,具体文章《Android中ImageView半边圆角处理记录 -125啦读书导航 - 阅读是一种生活方式 (125la.com)》,后面发现网上还有一种更简单的一种方式。

  1. 有点:代码少,简单
  2. 缺点:边界不够圆滑(存在锯齿)

正文

具体效果如下(左侧是RoundImageView2,右侧是之前RoundImageView),看圆角处,RoundImageView2就存在锯齿。

Android中ImageView半边圆角处理记录2

代码片段

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

    private final Path mPath;
    private float mWidth, mHeight;

    public RoundImageView2(Context context) {
        this(context, null);
    }

    public RoundImageView2(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public RoundImageView2(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mPath = new Path();
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        mWidth = getWidth();
        mHeight = getHeight();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        int radius = 20; //圆角半径
        if (mWidth > radius && mHeight > radius) {
            mPath.moveTo(radius, 0);
            mPath.lineTo(mWidth - radius, 0);
            mPath.quadTo(mWidth, 0, mWidth, radius);
            mPath.lineTo(mWidth, mHeight - radius);
            mPath.quadTo(mWidth, mHeight, mWidth - radius, mHeight);
            mPath.lineTo(radius, mHeight);
            mPath.quadTo(0, mHeight, 0, mHeight - radius);
            mPath.lineTo(0, radius);
            mPath.quadTo(0, 0, radius, 0);
            canvas.clipPath(mPath);
        }
        super.onDraw(canvas);
    }

}

参考文章

  1. Android中ImageView半边圆角处理记录 -125啦读书导航 - 阅读是一种生活方式 (125la.com)

125啦读书导航,我的单页导航
版权声明:改变自己 发表于 2023年2月21日 上午8:08。
转载请注明:Android中ImageView半边圆角处理记录2 | 125啦读书导航

相关文章

125啦读书导航,我的单页导航

暂无评论

暂无评论...