一、简介
目前最新版本是 3.0.1。
GitHub:https://github.com/hdodenhof/CircleImageView
快速圆形的 ImageView,非常适合个人资料图像。 这基于 Vince Mi 的 RoundedImageView ,它本身基于 Romain Guy 推荐的技术。
原理
- 继承自 ImageView,即自定义了 ImageView。
- 使用 BitmapShader 来实现圆形绘制,但出于内存优化以及效率的考虑。
a.不会对图片进行复制,即不会有图片的副本。
b.不使用 clipPath,因为其既不支持硬件加速也不支持抗锯齿。
c.不使用setXfermode通过裁剪图片的方式实现,因为那将要绘制 2 次。
限制
- 不支持除 CENTER_CROP 之外的 ScaleType,也就是说只支持图片中心裁剪的缩放方式。
- 不支持 adjustViewBounds(是否保持原图的长宽比),当然不支持了,因为其不支持其他的 ScaleType。
- 不支持 Picasso or Glide 的动画。不过,话说这 2 个库本身就可以自己实现支持圆形,圆角或者任意形状的图片。
- 不支持 TransitionDrawable(渐变),可能会导致图片混乱。
二、使用
1. 在 app/build.gradle 中添加:
dependencies {
...
implementation 'de.hdodenhof:circleimageview:3.0.1'
}
2. 布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
<de.hdodenhof.circleimageview.CircleImageView
android:id="@+id/profile_image"
android:layout_width="96dp"
android:layout_height="96dp"
android:layout_centerInParent="true"
android:src="@drawable/profile"
app:civ_border_color="#FF000000"
app:civ_border_width="2dp" />
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:background="#000"
android:layout_height="0dp"
android:layout_weight="1">
<de.hdodenhof.circleimageview.CircleImageView
android:id="@+id/profile_image2"
android:layout_width="96dp"
android:layout_height="96dp"
android:layout_centerInParent="true"
android:src="@drawable/profile"
app:civ_border_color="#ffffff"
app:civ_border_width="2dp" />
</RelativeLayout>
</LinearLayout>
3. 效果图
三、小结
简单小结下 CircleImageView 的原理:
(1) 通过 BitmapShader 构造一个可以绘制出图片的画刷
(2) 通过 View 的大小,Padding,边框等计算出图片需要进行变换的变换矩阵
(3) 通过 canvas.drawCircle() 方法绘制出最终需要的圆形图片