Android开发之自定义ImageView圆角图片的方法

老套路看图:

实现方法非常简单,使用ClipPath切割就可以了:

完整代码如下:dpUtils工具类就不发了,自己写下吧

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Path;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.widget.ImageView;

import com.gfan.xiayiye5.utils.DpUtils;

/**
 * @author xiayiye5
 * 2020年11月14日15:21:42
 * 自定义圆角图片
 */
@SuppressLint("AppCompatCustomView")
public class RadiusImageView extends ImageView {

    /**
     * 圆角大小
     */
    private int radiusSize = DpUtils.dip2px(getContext(), 10);

    public RadiusImageView(Context context) {
        super(context, null);
    }

    public RadiusImageView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs, 0);
    }

    public RadiusImageView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
    }

    /**
     * 设置圆角大小,设置后需要再次刷新下当前view,使用invalidate()或者postInvalidate()刷新都可以的
     *
     * @param size dp值
     */
    public void setRadiusSize(int size) {
        radiusSize = DpUtils.dip2px(getContext(), size);
        invalidate();
//        postInvalidate();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        if (getWidth() > radiusSize && getHeight() > radiusSize) {
            @SuppressLint("DrawAllocation")
            Path path = new Path();
            path.moveTo(radiusSize, 0);
            path.lineTo(getWidth() - radiusSize, 0);
            path.quadTo(getWidth(), 0, getWidth(), radiusSize);
            path.lineTo(getWidth(), getHeight() - radiusSize);
            path.quadTo(getWidth(), getHeight(), getWidth() - radiusSize, getHeight());
            path.lineTo(radiusSize, getHeight());
            path.quadTo(0, getHeight(), 0, getHeight() - radiusSize);
            path.lineTo(0, radiusSize);
            path.quadTo(0, 0, radiusSize, 0);
            canvas.clipPath(path);
        }
        super.onDraw(canvas);
    }
}

如何使用呢?

在布局中直接使用该控件就可以了:

<!-- 下面的com.gfan.xiayiye5.view.RadiusImageView换成自己路径就好了 -->

<com.gfan.xiayiye5.view.RadiusImageView
        android:id="@+id/ivLastLoginId"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_below="@+id/tvLastLoginId" />

再次非常感谢原博主:博主链接

猜你喜欢

转载自blog.csdn.net/xiayiye5/article/details/109691727