作用:将不同的绘制内容结合到一起
先绘制 一张图片文章来源:https://www.toymoban.com/news/detail-702661.html
package com.example.viewtest.view
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View
import com.example.viewtest.R
import com.example.viewtest.ext.dp
private val IMAGE_WIDTH = 200.dp
private val IMAGE_PADDING = 20.dp
class AvatarView(context: Context, attrs: AttributeSet) : View(context, attrs) {
private val paint = Paint(Paint.ANTI_ALIAS_FLAG)
override fun onDraw(canvas: Canvas) {
canvas.drawBitmap(getAvatar(IMAGE_WIDTH.toInt()), IMAGE_PADDING, IMAGE_PADDING, paint)
}
fun getAvatar(width: Int): Bitmap {
val options = BitmapFactory.Options()
// 第一次只读上下左右四个角的尺寸,这个速度是超级快的
options.inJustDecodeBounds = true
BitmapFactory.decodeResource(resources, R.drawable.ic_choice_select, options)
options.inJustDecodeBounds = false
// 本身的大小
options.inDensity = options.outWidth
// 实际想要的大小
options.inTargetDensity = width
// 无论原图有多大,都能读出一个很小,很快的图
return BitmapFactory.decodeResource(resources, R.drawable.ic_choice_select, options)
}
}
然后再绘制一个圆形,重叠在一起,圆形之外的部分透明显示文章来源地址https://www.toymoban.com/news/detail-702661.html
package com.example.viewtest.view
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.PorterDuff
import android.graphics.PorterDuffXfermode
import android.graphics.RectF
import android.util.AttributeSet
import android.view.View
import com.example.viewtest.R
import com.example.viewtest.ext.dp
private val IMAGE_WIDTH = 200.dp
private val IMAGE_PADDING = 20.dp
private val XFERMODE = PorterDuffXfermode(PorterDuff.Mode.SRC_IN)
class AvatarView(context: Context, attrs: AttributeSet) : View(context, attrs) {
private val paint = Paint(Paint.ANTI_ALIAS_FLAG)
private val bounds = RectF(IMAGE_PADDING, IMAGE_PADDING, IMAGE_PADDING + IMAGE_WIDTH,IMAGE_PADDING + IMAGE_WIDTH )
override fun onDraw(canvas: Canvas) {
val count = canvas.saveLayer(bounds, null)
canvas.drawOval(bounds, paint)
paint.xfermode = XFERMODE
canvas.drawBitmap(getAvatar(IMAGE_WIDTH.toInt()), IMAGE_PADDING, IMAGE_PADDING, paint)
paint.xfermode = null
canvas.restoreToCount(count)
}
private fun getAvatar(width: Int): Bitmap {
val options = BitmapFactory.Options()
// 第一次只读上下左右四个角的尺寸,这个速度是超级快的
options.inJustDecodeBounds = true
BitmapFactory.decodeResource(resources, R.drawable.qr_download, options)
options.inJustDecodeBounds = false
// 本身的大小
options.inDensity = options.outWidth
// 实际想要的大小
options.inTargetDensity = width
// 无论原图有多大,都能读出一个很小,很快的图
return BitmapFactory.decodeResource(resources, R.drawable.qr_download, options)
}
}
到了这里,关于Xfermode的完全使用解析的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!