Android使用PorterDuffXfermode的模式PorterDuff.Mode.SRC_OUT实现橡皮擦,Kotlin(1)
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Path
import android.graphics.PorterDuff
import android.graphics.PorterDuffXfermode
import android.util.AttributeSet
import android.view.MotionEvent
import androidx.appcompat.widget.AppCompatImageView
class MyView : AppCompatImageView {
private var WIDTH = 0
private var HEIGHT = 0
private var mPaint: Paint = Paint()
private var mBmpDst: Bitmap
private var mBmpSrc: Bitmap
private var mPath: Path
private var mPreX = 0f
private var mPreY = 0f
private var mPorterDuffXfermode: PorterDuffXfermode
constructor(ctx: Context, attributeSet: AttributeSet) : super(ctx, attributeSet) {
//WIDTH = resources.displayMetrics.widthPixels
//HEIGHT = resources.displayMetrics.heightPixels
//mPaint?.setColor(Color.RED)
mPaint.style = Paint.Style.STROKE
mPaint.strokeWidth = 30f
mBmpSrc = BitmapFactory.decodeResource(resources, R.mipmap.pic, null)
WIDTH = mBmpSrc.width
HEIGHT = mBmpSrc.height
//空Bitmap
mBmpDst = Bitmap.createBitmap(WIDTH, HEIGHT, Bitmap.Config.ARGB_8888)
mPath = Path()
/**
*
* SRC_OUT
*
* 当目标图像有图像时合成结果为空白像素;
* 当目标图像没有图像时,合成结果显示源图像;
* 如果把手指Path做为目标图像,在与源图像合成时,有手指轨迹的地方就变为空白像素,效果就是擦除。
*
*/
mPorterDuffXfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_OUT)
}
override fun onDraw(canvas: Canvas) {
//super.onDraw(canvas)
val layerId = canvas.saveLayer(0f, 0f, WIDTH.toFloat(), HEIGHT.toFloat(), null)
//绘制Path
val c = Canvas(mBmpDst)
c.drawPath(mPath, mPaint)
//绘制目标图像
canvas.drawBitmap(mBmpDst, 0f, 0f, mPaint)
//合成图像
mPaint.setXfermode(mPorterDuffXfermode)
canvas.drawBitmap(mBmpSrc, 0f, 0f, mPaint)
mPaint.setXfermode(null)
canvas.restoreToCount(layerId)
}
override fun onTouchEvent(event: MotionEvent): Boolean {
when (event.action) {
MotionEvent.ACTION_DOWN -> {
mPath.moveTo(event.x, event.y)
mPreX = event.x
mPreY = event.y
return true
}
MotionEvent.ACTION_MOVE -> {
val endX = (mPreX + event.x) / 2
val endY = (mPreY + event.y) / 2
mPath.quadTo(mPreX, mPreY, endX, endY)
mPreX = event.x
mPreY = event.y
}
MotionEvent.ACTION_UP -> {
}
}
postInvalidate()
return super.onTouchEvent(event)
}
}
手指在屏幕上滑动,图像像被橡皮擦擦掉一样。