1:最近项目中在做一个圆形头像,之前用的只是简单的圆形,现在整理的需求是圆环,于是折腾了下,查找了资料,总结如下:
原理:先在canvas上面画一个圆形,参照圆形的起点坐标、半径,再画一个边长为圆的直径的bitmap(这个bitmap就是你想画的圆形头像),此时圆和bitmap重叠在一起,圆在下面,bitmap在上面,bitmap覆盖着圆。
public Bitmap toRoundBitmap(Bitmap bitmap) {
//圆形图片宽高
int width = bitmap.getWidth();
int height = bitmap.getHeight();
//正方形的边长
int r = 0;
//取最短边做边长
if(width > height) {
r = height;
} else {
r = width;
}
//构建一个bitmap
Bitmap backgroundBmp = Bitmap.createBitmap(width,
height, Config.ARGB_8888);
//new一个Canvas,在backgroundBmp上画图
Canvas canvas = new Canvas(backgroundBmp);
Paint paint = new Paint();
//设置边缘光滑,去掉锯齿
paint.setAntiAlias(true);
//宽高相等,即正方形
RectF rect = new RectF(0, 0, r, r);
//通过制定的rect画一个圆角矩形,当圆角X轴方向的半径等于Y轴方向的半径时,
//且都等于r/2时,画出来的圆角矩形就是圆形
canvas.drawRoundRect(rect, r/2, r/2, paint);
//设置当两个图形相交时的模式,SRC_IN为取SRC图形相交的部分,多余的将被去掉
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
//canvas将bitmap画在backgroundBmp上
canvas.drawBitmap(bitmap, null, rect, paint);
//返回已经绘画好的backgroundBmp
return backgroundBmp;
}
2:强烈推荐这篇文章:https://github.com/hdodenhof/CircleImageView 点击打开链接,直接可以在AS上引用
Gradle配置文件中直接引用:
compile 'de.hdodenhof:circleimageview:2.0.0'
- 在需要使用的地方直接布局:
<de.hdodenhof.circleimageview.CircleImageView xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/myinfo_user_headimg" android:layout_width="61dp" android:layout_height="61dp" android:layout_centerInParent="true" android:src="@mipmap/myinfo_un_login_icon" app:civ_border_width="2dp"