自定义圆形头像
前言
我不停奔跑只为追赶当年被寄予厚望的自己
一、利用drawBitmap先画出原来的头像
封装一个获取bitmap方法
private fun getAvatarBitmap(width: Int): Bitmap {
val options = BitmapFactory.Options()
options.inJustDecodeBounds = true
BitmapFactory.decodeResource(resources, R.mipmap.zzt, options)
options.inJustDecodeBounds = false
options.inDensity = options.outWidth
options.inTargetDensity = width
return BitmapFactory.decodeResource(resources, R.mipmap.zzt, options)
}
通过重写onDraw方法就可以画出对应的头像图片
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
canvas.drawBitmap(getAvatarBitmap(IMAGE_WIDTH.toInt()), IMAGE_PADDING, IMAGE_PADDING, paint)
}
二、画出圆形
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
canvas.drawOval(
IMAGE_PADDING,
IMAGE_PADDING,
IMAGE_PADDING + IMAGE_WIDTH,
IMAGE_PADDING + IMAGE_WIDTH, paint
)
canvas.drawBitmap(getAvatarBitmap(IMAGE_WIDTH.toInt()), IMAGE_PADDING, IMAGE_PADDING, paint)
}
三、利用Xfermode可以实现图层叠加
private var XFERMODE = PorterDuffXfermode(PorterDuff.Mode.SRC_IN)
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
val count = canvas.saveLayer(bounds, null)
canvas.drawOval(
IMAGE_PADDING,
IMAGE_PADDING,
IMAGE_PADDING + IMAGE_WIDTH,
IMAGE_PADDING + IMAGE_WIDTH, paint
)
paint.xfermode = XFERMODE
canvas.drawBitmap(getAvatarBitmap(IMAGE_WIDTH.toInt()), IMAGE_PADDING, IMAGE_PADDING, paint)
paint.xfermode = null
canvas.restoreToCount(count)
}
四、增加自定义控件的属性
attrs.xml里面增加属性
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="AvatarView">
<attr name="imgSrc" format="reference" />
</declare-styleable>
</resources>
初始化的时候获取下属性
constructor(context: Context) : this(context, null)
constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, -1)
@SuppressLint("Recycle")
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
context,
attrs,
defStyleAttr
) {
val typeArray = context.obtainStyledAttributes(attrs, R.styleable.AvatarView)
resource =
typeArray.getResourceId(R.styleable.AvatarView_imgSrc, -1);
}
xml里面就可以直接填对应的值
<?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">
<com.jbh.demo.widget.AvatarView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:imgSrc="@mipmap/zzt" />
</LinearLayout>
五、Xfermode属性
参考官方文档