Android双指缩放ScaleGestureDetector检测放大因子大图移动到双指中心点ImageView区域中心,Kotlin(2)
在 Android ScaleGestureDetector检测双指缩放Bitmap基于Matrix动画移动到双指捏合中心点ImageView区域中心,Kotlin-CSDN博客 的基础上,改进一下,实现两根手指在屏幕上捏合缩放时候,图片随之缩放。当手指在屏幕上抬离时候,画布上呈现的是缩放后的图。
Kotlin
class MyImageView : AppCompatImageView {
private var mCenterX = 0f
private var mCenterY = 0f
private val mCirclePaint = Paint()
private var mSrcBmp: Bitmap? = null
private var mScaleBmp: Bitmap? = null
//放大系数。
private var mScaleFactor = 1f
private var mScaleGestureDetector: ScaleGestureDetector? = null
private var mCanDrawScaleBmp = false
constructor(ctx: Context, attrs: AttributeSet) : super(ctx, attrs) {
mSrcBmp = (drawable as BitmapDrawable).bitmap //mSrcBmp是原始图大小,没有缩放和拉伸的。
mCirclePaint.style = Paint.Style.STROKE
mCirclePaint.strokeWidth = 10f
mCirclePaint.isAntiAlias = true
mCirclePaint.color = Color.RED
mScaleGestureDetector = ScaleGestureDetector(ctx, object : ScaleGestureDetector.SimpleOnScaleGestureListener() {
override fun onScale(detector: ScaleGestureDetector): Boolean {
//更新两个手指缩放的中心点。
mCenterX = detector.focusX
mCenterY = detector.focusY
//if (detector.currentSpan > 50 && detector.timeDelta > 20) {
mScaleFactor = detector.scaleFactor
Log.d("fly", "onScaleEnd scaleFactor=${detector.scaleFactor}")
//}
updateView()
return false
}
})
}
private fun updateView() {
this.invalidate()
}
override fun onTouchEvent(event: MotionEvent): Boolean {
mScaleGestureDetector?.onTouchEvent(event)
when (event.actionMasked) {
MotionEvent.ACTION_MOVE -> {
mCanDrawScaleBmp = true
}
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
//如果抬手时候重新置false,没有绘制,显示原始底图。
//mCanDrawScaleBmp = false
}
}
return true
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
if (mCanDrawScaleBmp) {
myDraw(canvas)
}
}
private fun myDraw(canvas: Canvas) {
mScaleBmp = Bitmap.createScaledBitmap(
mSrcBmp!!,
(this.width * mScaleFactor + 1).toInt(), //注意这里的精度损失,会造成坐标偏移.
(this.height * mScaleFactor + 1).toInt(),//注意这里的精度损失,会造成坐标偏移.
true
)
val cx = this.width / 2f
val cy = this.height / 2f
val matrix = Matrix()
matrix.setScale(mScaleFactor, mScaleFactor)
matrix.setTranslate(cx - mCenterX * mScaleFactor, cy - mCenterY * mScaleFactor)
canvas.drawBitmap(mScaleBmp!!, matrix, null)
//中心圆圈
canvas.drawCircle(cx, cy, 50f, mCirclePaint)
}
}
需要改进的地方是滑动缩放过程不是图片缩放不是非常丝滑流畅,需要改善。