原图
效果
一、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