DEV Community

myougaTheAxo
myougaTheAxo

Posted on

Pinch Zoom & Pan: Image Zoom and Double-tap Gestures

Pinch Zoom & Pan: Image Zoom and Double-tap Gestures

Gesture support for zooming and panning transforms static images into interactive, explorable content.

Pinch to Zoom

var scale by remember { mutableStateOf(1f) }
var offset by remember { mutableStateOf(Offset.Zero) }

Image(
    painter = painterResource(R.drawable.photo),
    contentDescription = "Zoomable photo",
    modifier = Modifier
        .fillMaxSize()
        .pointerInput(Unit) {
            detectTransformGestures { _, pan, gestureZoom, _ ->
                scale *= gestureZoom
                offset += pan
            }
        }
        .graphicsLayer {
            scaleX = scale
            scaleY = scale
            translationX = offset.x
            translationY = offset.y
        }
)
Enter fullscreen mode Exit fullscreen mode

Double-tap to Zoom

var isZoomed by remember { mutableStateOf(false) }

Image(
    painter = painterResource(R.drawable.photo),
    contentDescription = "Double-tap to zoom",
    modifier = Modifier
        .fillMaxSize()
        .pointerInput(Unit) {
            detectTapGestures(
                onDoubleTap = { isZoomed = !isZoomed }
            )
        }
        .graphicsLayer {
            scaleX = if (isZoomed) 2f else 1f
            scaleY = if (isZoomed) 2f else 1f
        }
)
Enter fullscreen mode Exit fullscreen mode

Pan with Bounds

scale = scale.coerceIn(1f, 3f)
offset = Offset(
    x = offset.x.coerceIn(-size.width * scale / 2, size.width * scale / 2),
    y = offset.y.coerceIn(-size.height * scale / 2, size.height * scale / 2)
)
Enter fullscreen mode Exit fullscreen mode

Gesture support makes image viewing and interaction feel natural and responsive on touch devices.


8 Android app templates available on Gumroad

Top comments (0)