?
在?Android双击图片放大移动图中双击点到ImageView区域中心,Kotlin-CSDN博客 基础上,这次使用ScaleGestureDetector检测两根手指的缩放动作,记录两根手指的中心点位置,根据ScaleGestureDetector检测到的缩放因子(系数),放大原图,并移动放大前两根手指中心点在原图的位置移动到放大后区域。
?
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 testIV: ImageView? = null
//放大系数。
private var mScaleFactor = 1f
private var mScaleGestureDetector: ScaleGestureDetector? = null
private var mCanDrawScaleBmp = false
private var mCanDrawCircle = 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 onScaleEnd(detector: ScaleGestureDetector) {
super.onScaleEnd(detector)
if (detector.currentSpan > 50 && detector.timeDelta > 10) {
mScaleFactor = detector.scaleFactor
}
}
override fun onScale(detector: ScaleGestureDetector): Boolean {
//更新两个手指缩放的中心点。
mCenterX = detector.focusX
mCenterY = detector.focusY
return super.onScale(detector)
}
})
}
fun setTestImageView(iv: ImageView?) {
testIV = iv
}
private fun updateView() {
this.invalidate()
}
override fun onTouchEvent(event: MotionEvent): Boolean {
when (event.actionMasked) {
MotionEvent.ACTION_MOVE -> {
mScaleGestureDetector?.onTouchEvent(event)
mCanDrawCircle = true
}
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
mCanDrawScaleBmp = true //两个手指松开了,可以绘制放大的图。
mCanDrawCircle = false
}
}
updateView()
return true
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
if (mCanDrawCircle) {
canvas.drawCircle(mCenterX, mCenterY, 10f, mCirclePaint)
}
if (mCanDrawScaleBmp) {
myDraw(canvas)
}
}
private fun myDraw(canvas: Canvas) {
Thread.sleep(1500)
if (mScaleBmp == null) {
//创建一次,避免重复创建,提高速度。
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, 40f, mCirclePaint)
}
}
?
?
两根手指在原图上缩放,红色小圆圈实时处于两根手指的中心点:
?
?
?
?
当两根手指离开屏幕后,然后放大原图,并把原先手指中心点“点中”的原图位置,移动到屏幕中心:
?
?
?