绘制圆形头像需要用到Xfermode参数,Xfermode又叫transform mode,老美喜欢把transform叫做X. 具体有哪些transform mode, 可以参考博客:
https://www.cnblogs.com/spring87/p/5779201.html
demo程序如下:
public class AvatarView extends View {
private static final float WIDTH = Utils.dp2px(300);
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
Xfermode xfermode = new PorterDuffXfermode(PorterDuff.Mode.SRC_IN);
Bitmap bitmap;
RectF saveArea = new RectF();
public AvatarView(Context context, AttributeSet attrs) {
super(context, attrs);
}
{
bitmap = getAvatar((int)WIDTH);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
saveArea.set(0,0,WIDTH,WIDTH);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawOval(0,0,WIDTH,WIDTH,paint);
int saved = canvas.saveLayer(saveArea, paint);
canvas.drawOval(Utils.dp2px(3),Utils.dp2px(3),WIDTH-Utils.dp2px(3),WIDTH-Utils.dp2px(3),paint);
paint.setXfermode(xfermode);
canvas.drawBitmap(bitmap,0,0,paint);
paint.setXfermode(null);
canvas.restoreToCount(saved);
}
Bitmap getAvatar(int width) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(getResources(), R.mipmap.avatar, options);
options.inJustDecodeBounds = false;
options.inDensity = options.outWidth;
options.inTargetDensity = width;
return BitmapFactory.decodeResource(getResources(),R.mipmap.avatar, options);
}
}