?
初始化状态,ImageView里面只是显示一张fitcenter被缩放的原图,当手指在图片上双击后(记录双击点位置:mCurX,mCurY)画一个红色小圆圈标记双击位置,放大图片,然后把放大后的图的(原mCurX,mCurY)位置移动到区域中心点位置,用大的红色圆圈标记。
?
双击:
?
?
放大图片,并把原来图中的双击点移动到区域中心,用大红圆圈标记:
?
class MyImageView : AppCompatImageView {
private var mCurX = 0f
private var mCurY = 0f
private val mCirclePaint = Paint()
private var mSrcBmp: Bitmap? = null
private var mScaleBmp: Bitmap? = null
private var testIV: ImageView? = null
//放大系数。
private val mScaleFactor = 4f
private var mGestureDetector: GestureDetector? = null
private var mIsDoubleTap = false
private var mCanDraw = 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
mGestureDetector = GestureDetector(ctx, object : GestureDetector.SimpleOnGestureListener() {
override fun onDoubleTap(e: MotionEvent): Boolean {
mIsDoubleTap = true
return false
}
})
}
fun setTestImageView(iv: ImageView?) {
testIV = iv
}
override fun onTouchEvent(event: MotionEvent): Boolean {
mCurX = event.x
mCurY = event.y
mGestureDetector?.onTouchEvent(event)
mCanDraw = true
invalidate()
return true
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
if (mCanDraw) {
canvas.drawCircle(mCurX, mCurY, 10f, mCirclePaint)
}
if (mIsDoubleTap) {
myDraw(canvas)
}
}
private fun myDraw(canvas: Canvas) {
Thread.sleep(1000)
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 - mCurX * mScaleFactor, cy - mCurY * mScaleFactor)
canvas.drawBitmap(mScaleBmp!!, matrix, null)
//中心圆圈
canvas.drawCircle(cx, cy, 40f, mCirclePaint)
}
}
?
?
xml里面定义MyImageView,特别的属性设置:
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:scaleType="fitCenter"
?
?
?
?
?
?