前言:最近需要做一个带边框用户的圆角头像,然后搜索了下,发现大部分都是使用shape来做的,于是使用Canvas做了个头像处理
Demo:https://github.com/459905207/rounded-rectangle
效果图:
实现代码
//return:Bitmap
//参数:原图,圆角大小,边框大小
private Bitmap createCircleImage(Bitmap bitmap, int roundPx, int framePx) {
Bitmap newBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_4444);
//创建画板
Canvas canvas = new Canvas(newBitmap);
//画板drawARGB必须与Bitmap的Config一致
canvas.drawARGB(0, 0, 0, 0);
Paint paint = new Paint();
//抗锯齿
paint.setAntiAlias(true);
//左上右下位置
Rect rect = new Rect(framePx / 2, framePx / 2, bitmap.getWidth() - framePx / 2, bitmap.getHeight() - framePx / 2);
RectF rectF = new RectF(rect);
//RectF对象,X矩形圆角大小,Y矩形圆角大小,画笔
canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
//设置两张图片相交时的模式为Mode.SRC_IN
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
//创建画边框的画笔
Paint paintFrame = new Paint();
paintFrame.setAntiAlias(true);
//设置空心画笔
paintFrame.setStyle(Paint.Style.STROKE);
//设置边框颜色
paintFrame.setColor(Color.WHITE);
//设置边框宽度
paintFrame.setStrokeWidth(framePx);
//画圆角矩形边框
canvas.drawRoundRect(rectF, roundPx, roundPx, paintFrame);
return newBitmap;
}
public int dip2px(float dpValue) {
final float scale = getApplication().getResources()
.getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
}
核心:
主要用到了Canvas的drawRoundRect(RectF rect, float rx, float ry,Paint paint)方法,用来生成圆角矩形,根据float rx, float ry的大小决定X,Y轴矩形圆角的大小
还有Paint的setXfermode方法来生成圆角矩形头像
(参考文章:http://folksy.iteye.com/blog/1488629)
最后使用空心画笔画一个边框即可