自定义圆形头像

本文介绍了两种自定义圆形头像的方法。首先通过clipPath在XML中创建attrs.xml文件,然后在布局文件引用并自定义View,实现将画布剪裁为圆形。接着讨论了这种方法的缺点,即可能产生锯齿。另一种方法是使用BitmapShader,它能更流畅地制作圆形头像。
摘要由CSDN通过智能技术生成

原图

效果

 

一、clipPath自定义圆形头像

在res/values下新建attrs.xml文件

<declare-styleable name="CustomAvatarView">
    <attr name="stroke_color" format="color|reference"/>
    <attr name="stroke_width" format="dimension"/>
    <attr name="src" format="reference"/>
</declare-styleable>

布局文件引用

<com.huangmiao.kotlintest.view.CustomAvatarView
    android:id="@+id/customAvatarView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:stroke_color = "@color/colorSilver"
    app:stroke_width="5dp"
    app:src="@drawable/test"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

自定义View

圆形头像的实现并不复制,只需将画布剪裁成圆形,核心代码是canvas.clipPath(path),根据圆形路径剪裁画布

这里做了几个优化,比如图片过大,会将图片剪裁至控件最短边距大小

限制控件大小,比如控件大小不能超过屏幕宽高,防止超出绘制区域

public class CustomAvatarView extends View {
    public CustomAvatarView(Context context) {
        this(context,null);
    }

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

    public CustomAvatarView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.CustomAvatarView);
        init(typedArray);
    }

    //画笔
    private Paint strokePaint;
    public Paint getStrokePaint(){
        return strokePaint;
    }

    //画笔宽度
    private float strokeWidth = 5;
    public void setStrokeWidth(float strokeWidth){
        this.strokeWidth = strokeWidth;
        strokePaint.setStrokeWidth(strokeWidth);
        invalidate();
    }

    //画笔颜色
    private int strokeColor = ContextCompat.getColor(getContext().getApplicationContext(), R.color.colorSilver);
    public void setStrokeColor(@ColorRes int color){
        this.st
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值