我实现了一个可缩放和可滚动的GestrueDetector。我不想要自定义imageView或自定义视图,仅希望通过它实现它。
当我们使用此缩放功能时,它会导致图像滚动或晃动,您可以调用它!
我不能使用customView,因为我使用的是github libphotoeditor,它给了我一个imageView类型的sourceView
要在以下类别下使用:myView.setOnTouchListener(AppScaleGestureDetector(this))
class AppScaleGestureDetector(c: Context?) :
OnTouchListener, OnScaleGestureListener, GestureDetector.OnGestureListener, GestureDetector.OnDoubleTapListener {
private var view: View? = null
private val gesture = GestureDetector(c, this)
private val gestureScale: ScaleGestureDetector = ScaleGestureDetector(c, this)
private var scaleFactor = 1f
private var inScale = false
private var isZoomed: Boolean = false
override fun onTouch(view: View?, event: MotionEvent?): Boolean {
this.view = view
gesture.onTouchEvent(event)
gestureScale.onTouchEvent(event)
return true
}
override fun onScale(p0: ScaleGestureDetector?): Boolean {
if(p0 != null) {
scaleFactor *= p0.scaleFactor
scaleFactor = if (scaleFactor < 1f) 1f else scaleFactor
isZoomed = scaleFactor > 1f
scaleFactor = (scaleFactor * 100).toInt().toFloat() / 100
view?.scaleX = scaleFactor
view?.scaleY = scaleFactor
onScroll(null, null, 0f, 0f)
return true
}
return false
}
override fun onScaleBegin(detector: ScaleGestureDetector?): Boolean {
inScale = true
return true
}
override fun onScaleEnd(detector: ScaleGestureDetector?) {
inScale = false
onScroll(null, null, 0f, 0f)
}
override fun onShowPress(p0: MotionEvent?) {
}
override fun onSingleTapUp(p0: MotionEvent?): Boolean {
return true
}
override fun onDown(p0: MotionEvent?): Boolean {
return true
}
override fun onFling(p0: MotionEvent?, p1: MotionEvent?, p2: Float, p3: Float): Boolean {
return true
}
override fun onScroll(event1: MotionEvent?, event2: MotionEvent?, x: Float, y: Float): Boolean {
var newX = view!!.x
var newY = view!!.y
if (!inScale) {
newX -= x
newY -= y
}
val wm = view!!.context
.getSystemService(Context.WINDOW_SERVICE) as WindowManager
val d = wm.defaultDisplay
val p = Point()
d.getSize(p)
if (newX > (view!!.width * scaleFactor - p.x) / 2) {
newX = (view!!.width * scaleFactor - p.x) / 2
} else if (newX < -((view!!.width * scaleFactor - p.x) / 2)) {
newX = -((view!!.width * scaleFactor - p.x) / 2)
}
if (newY > (view!!.height * scaleFactor - p.y) / 2) {
newY = (view!!.height * scaleFactor - p.y) / 2
} else if (newY < -((view!!.height * scaleFactor - p.y) / 2)) {
newY = -((view!!.height * scaleFactor - p.y) / 2)
}
if(!inScale) {
view!!.x = newX
view!!.y = newY
}
return true
}
override fun onLongPress(p0: MotionEvent?) {
}
override fun onDoubleTap(p0: MotionEvent?): Boolean {
if (isZoomed) {
view?.scaleY = 1.0f
view?.scaleX = 1.0f
view?.x = 0f
view?.y = 0f
isZoomed = false
}else {
view?.scaleY = 5.0f
view?.scaleX = 5.0f
view?.x = 0f
view?.y = 0f
isZoomed = true
}
return true
}
override fun onDoubleTapEvent(p0: MotionEvent?): Boolean {
return true
}
override fun onSingleTapConfirmed(p0: MotionEvent?): Boolean {
return true
}
}