2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Android】画像をピンチイン・アウト

Last updated at Posted at 2022-02-18

Kotlinで書かれているコードが見つからなかったのでメモ。

CustomImageView.kt
class CustomImageView : View {
	constructor(context: Context) : super(context)
	constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
	constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)

	private var bitmap: Bitmap? = null
	private val bitmapMatrix = Matrix()
	private val paint = Paint()

	// ピンチイン/アウト時、画像を拡大/縮小
	private val scaleGestureDetector by lazy {
		ScaleGestureDetector(context, object : SimpleOnScaleGestureListener() {
			private var scale = 1f
			override fun onScaleBegin(detector: ScaleGestureDetector?): Boolean {
				scale = 1f
				return super.onScaleBegin(detector)
			}

			override fun onScale(detector: ScaleGestureDetector): Boolean {
				val deltaScale = detector.scaleFactor / scale
				bitmapMatrix.postScale(deltaScale, deltaScale, detector.focusX, detector.focusY)
				scale = detector.scaleFactor
				invalidate()
				return super.onScale(detector)
			}
		})
	}

	//スクロール時、画像を移動
	private val gestureDetector by lazy {
		GestureDetector(context, object : SimpleOnGestureListener() {
			override fun onScroll(e1: MotionEvent, e2: MotionEvent, distanceX: Float, distanceY: Float): Boolean {
				if (e1.getPointerId(0) == e2.getPointerId(0)) {
					bitmapMatrix.postTranslate(-distanceX, -distanceY)
					invalidate()
				}
				return super.onScroll(e1, e2, distanceX, distanceY)
			}
		})
	}

	@SuppressLint("ClickableViewAccessibility")
	override fun onTouchEvent(event: MotionEvent): Boolean {
		return gestureDetector.onTouchEvent(event) || scaleGestureDetector.onTouchEvent(event) || super.onTouchEvent(event)
	}

	override fun onDraw(canvas: Canvas) {
		bitmap?.let { bitmap ->
			canvas.save()
			canvas.drawBitmap(bitmap, bitmapMatrix, paint)
			canvas.restore()
		}
	}

	/**
	 * ビットマップをセット
	 *
	 * @param bitmap ビットマップ
	 */
	fun setBitmap(bitmap: Bitmap?) {
		if (bitmap != null) {
			this.bitmap = bitmap
			val mScaleFactor = min(width.toFloat() / bitmap.width, height.toFloat() / bitmap.height)
			bitmapMatrix.setScale(mScaleFactor, mScaleFactor, 0f, 0f)
		}
	}
}

参照記事:https://qiita.com/Cyber_Hacnosuke/items/b2a8724218d2f4a4c3c2

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?