Android双指缩放ScaleGestureDetector检测放大因子大图移动到双指中心点ImageView区域中心,Kotlin(2)
在 Android ScaleGestureDetector检测双指缩放Bitmap基于Matrix动画移动到双指捏合中心点ImageView区域中心,Kotlin-CSDN博客 的基础上,改进一下,实现两根手指在屏幕上捏合缩放时候,图片随之缩放。当手指在屏幕上抬离时候,画布上呈现的是缩放后的图。
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)
}
}
需要改进的地方是滑动缩放过程不是图片缩放不是非常丝滑流畅,需要改善。
Android ScaleGestureDetector检测双指缩放Bitmap基于Matrix动画移动到双指捏合中心点ImageView区域中心,Kotlin-CSDN博客文章浏览阅读75次,点赞3次,收藏5次。需要注意的,因为在xml布局里面特别设置了ImageView的高度为wrap_content,手指在屏幕触点的位置是放大镜里面放大图片后准确圆心位置,但是,如果ImageView设置成match_parent,则因为ImageView里面的Bitmap被缩放(此处Bitmap其实小于ImageView,被拉伸了),拉伸后的Bitmap水平方向坐标与ImageView一直重合,但竖直方向,Bitmap坐标与ImageView不一致,会造成一种现象,手指触点放大镜放大后,水平方向是正确的,但竖直方向有偏移量。https://blog.csdn.net/zhangphil/article/details/135705931