Android SharedPreferences Tutorial and Example

Adding pinch to zoom with ImageView

Large photos often need more room than a normal ImageView provides. A user inspecting a receipt, artwork or map may want to enlarge a small detail without leaving the app. Pinch-to-zoom keeps the gesture familiar across Android devices.

This walkthrough uses Kotlin and one ImageView. It covers gesture detection, transform matrices, scale limits, bounds checking and state restoration after rotation. The pattern works for remote galleries, document previews and property listings when the bitmap is prepared separately from touch handling.

Prepare the image screen

Create an activity containing a full-screen ImageView. The layout reserves the complete content area and lets the activity calculate the first fit:

<ImageView
    android:id="@+id/photoView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:contentDescription="@string/photo_description"
    android:scaleType="matrix" />

Set scaleType to matrix because your code will control translation and scale. Assign a drawable or bitmap, then calculate the initial position after layout; the view has no measurable dimensions before that point.

private lateinit var photoView: ImageView
private val imageMatrix = Matrix()
private val matrixValues = FloatArray(9)
private var fittedScale = 1f

private fun fitImage() {
    val drawable = photoView.drawable ?: return
    val viewWidth = photoView.width.toFloat()
    val viewHeight = photoView.height.toFloat()
    val imageWidth = drawable.intrinsicWidth.toFloat()
    val imageHeight = drawable.intrinsicHeight.toFloat()

    fittedScale = minOf(viewWidth / imageWidth, viewHeight / imageHeight)
    imageMatrix.setScale(fittedScale, fittedScale)
    imageMatrix.postTranslate(
        (viewWidth - imageWidth * fittedScale) / 2f,
        (viewHeight - imageHeight * fittedScale) / 2f
    )
    photoView.imageMatrix = imageMatrix
}

In onCreate, assign photoView = findViewById(R.id.photoView) and call photoView.post { fitImage() }. The initial fit preserves the aspect ratio and centres the image. This becomes the reference for later zoom operations. If the view is recycled, reset the matrix before showing the next item so an earlier magnification cannot carry across.

In Australia, a commuter might open a harbour photo on a Sydney ferry, while a café owner in Melbourne could check a menu shot in the laneways. Portrait, landscape and low-light shots should all open with an adaptable aspect ratio.

Detect and apply pinch gestures

ScaleGestureDetector interprets multi-touch events and reports a scale factor with focal coordinates. Scaling around that focal point keeps the content under the user's fingers anchored instead of enlarging from the top-left corner.

private const val MAX_ZOOM = 5f
private val scaleValues = FloatArray(9)

private fun currentScale(): Float {
    imageMatrix.getValues(scaleValues)
    return scaleValues[Matrix.MSCALE_X]
}

private val scaleDetector = ScaleGestureDetector(
    this,
    object : ScaleGestureDetector.SimpleOnScaleGestureListener() {
        override fun onScaleBegin(detector: ScaleGestureDetector) = true

        override fun onScale(detector: ScaleGestureDetector): Boolean {
            val current = currentScale()
            val requested = current * detector.scaleFactor
            val target = requested.coerceIn(fittedScale, fittedScale * MAX_ZOOM)
            val factor = target / current

            imageMatrix.postScale(
                factor,
                factor,
                detector.focusX,
                detector.focusY
            )
            photoView.imageMatrix = imageMatrix
            keepImageInBounds()
            return true
        }
    }
)

The detector stays small. currentScale() reads horizontal scale, while coerceIn blocks rapid gestures from exceeding the allowed range. MAX_ZOOM is relative to the fitted image, so thumbnails and large photographs receive the same maximum multiple.

Register the detector with the view so it receives the complete stream of MotionEvent objects:

photoView.setOnTouchListener { _, event ->
    scaleDetector.onTouchEvent(event)
    when (event.actionMasked) {
        MotionEvent.ACTION_DOWN,
        MotionEvent.ACTION_POINTER_DOWN ->
            photoView.parent?.requestDisallowInterceptTouchEvent(true)

        MotionEvent.ACTION_UP,
        MotionEvent.ACTION_CANCEL ->
            photoView.parent?.requestDisallowInterceptTouchEvent(false)
    }
    true
}

Returning true keeps later pointer events flowing to the detector. Asking the parent not to intercept the gesture stops a surrounding scroll container from competing with the pinch. If pointer handling feels unfamiliar, the touch input fundamentals explain focal positions and action masks.

Keep scaling inside usable bounds

Scaling changes the matrix, but the image can also drift beyond the screen. After each gesture, calculate the transformed image rectangle and translate it back so a zoomed edge cannot disappear.

private fun keepImageInBounds() {
    val drawable = photoView.drawable ?: return
    val rect = RectF(
        0f,
        0f,
        drawable.intrinsicWidth.toFloat(),
        drawable.intrinsicHeight.toFloat()
    )
    photoView.imageMatrix.mapRect(rect)

    val width = photoView.width.toFloat()
    val height = photoView.height.toFloat()
    var dx = 0f
    var dy = 0f

    if (rect.width() <= width) {
        dx = (width - rect.width()) / 2f - rect.left
    } else if (rect.left > 0f) {
        dx = -rect.left
    } else if (rect.right < width) {
        dx = width - rect.right
    }

    if (rect.height() <= height) {
        dy = (height - rect.height()) / 2f - rect.top
    } else if (rect.top > 0f) {
        dy = -rect.top
    } else if (rect.bottom < height) {
        dy = height - rect.bottom
    }

    imageMatrix.postTranslate(dx, dy)
    photoView.imageMatrix = imageMatrix
}

This routine centres an image smaller than the viewport. Once enlarged, it permits movement only towards the visible edges and applies the same rule vertically.

The main approaches compare as follows:

Approach Best suited to Benefits Trade-offs
ScaleGestureDetector and Matrix A custom photo or document viewer Native primitives and full control You handle bounds and state
Third-party zoomable ImageView Rapid feature delivery Ready-made gestures Adds a dependency and less control
Manual MotionEvent calculations Unusual gesture requirements Maximum flexibility More code and edge-case testing

Platform primitives suit a bespoke viewer: they avoid a dependency, work with ordinary layouts and leave gesture thresholds under your control. A prebuilt library saves setup time, while manual calculations require much more testing.

Preserve state across real-world changes

Android can destroy and recreate an activity while the user is away, so save the matrix during configuration changes. Store its nine values and restore them after the replacement view has been measured.

override fun onSaveInstanceState(outState: Bundle) {
    super.onSaveInstanceState(outState)
    imageMatrix.getValues(matrixValues)
    outState.putFloatArray("photo_matrix", matrixValues)
    outState.putFloat("photo_fitted_scale", fittedScale)
}

When restoring, set those values back on imageMatrix, assign it to photoView, then run keepImageInBounds(). For list-based galleries, bind the image and restore or reset the matrix in the same adapter operation so a recycled row cannot inherit another photo's zoom level.

If thumbnail records arrive as JSON, keep parsing separate from gesture code. The Gson parsing guide demonstrates how to convert API fields into model objects before assigning a thumbnail to the ImageView.

Large source images deserve care. Decode an appropriately sized sample instead of loading a 20-megapixel bitmap into a phone handling several screens. Set a meaningful content description and provide an accessible zoom action so TalkBack users are not excluded.

Test the interaction on real devices

A reliable implementation must survive real fingers, rotation and changing network conditions. Run the viewer on several screen sizes and exercise it with the image already fitted and already enlarged.

Device checks

  • Pinch near each corner and confirm the focal area stays under the fingers.
  • Rotate the device and verify that the same zoom and position return.
  • Test with TalkBack and with a large-font accessibility setting.

Release checks

  • Profile scrolling in a gallery containing many remote thumbnails.
  • Verify that an interrupted download leaves the previous valid image visible.
  • Check memory use on a low-end device with several activities open.

Ask a teammate to have a look on a real Android phone, as an informal check catches pinch thresholds an emulator cannot. If the app offers a paid HD download through Google Play in Australia, consumers generally see prices in AUD with GST included, so keep commerce setup separate from the zoom viewer. The gesture then feels native whether the user browses a Sydney gallery or checks a property record at home.