Usage

This documentation was generated with the assistance of AI. Please report any inaccuracies.

This page shows how to add GestureBitmapView (package com.irurueta.android.gesturebitmap) to a screen, set the bitmap, choose a display type, toggle gestures and listen to its events. Every property mentioned here is listed with its default value in the Configuration reference.

Adding the view to a layout

<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.irurueta.android.gesturebitmap.GestureBitmapView
        android:id="@+id/gesture_bitmap"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:src="@drawable/image"
        app:displayType="fit_if_bigger"
        app:maxScale="5.0"
        app:rotationEnabled="false"/>

</androidx.constraintlayout.widget.ConstraintLayout>

All custom attributes use the app: (res-auto) namespace. See XML attributes for the full list.

Creating the view in code

GestureBitmapView has a @JvmOverloads constructor (context, attrs = null, defStyleAttr = 0), so it can also be created programmatically:

val view = GestureBitmapView(context)
view.displayType = GestureBitmapView.DisplayType.CENTER_CROP
view.setDrawable(ContextCompat.getDrawable(context, R.drawable.image))
container.addView(view)

Setting the bitmap

val view = findViewById<GestureBitmapView>(R.id.gesture_bitmap)

// From a Bitmap: resets the transformation (scale, rotation and translation)
view.bitmap = bitmap

// Same, with explicit control over resetting the transformation
view.setBitmap(otherBitmap, resetMatrices = false)

// From a Drawable, converted to a bitmap (never scaled up by screen density)
view.setDrawable(drawable)
  • Assigning bitmap is equivalent to setBitmap(value, resetMatrices = true): the base transformation is recomputed for the current displayType and the gesture transformation is reset.

  • setBitmap(bitmap, resetMatrices = false) keeps the current base and gesture transformations, which is useful to replace the image with another one of the same size (for instance a processed version) without losing the current zoom and position.

  • setDrawable(drawable) (also used by the app:src attribute) converts the drawable with Drawable.toBitmap() and assigns it to bitmap. The drawable’s intrinsic size is used, except for bitmap drawables whose intrinsic size is larger than their actual bitmap because of screen density: those keep the size of their actual bitmap and are never scaled up.

Setting a new bitmap calls recycle() on the bitmap previously held by the view. Do not set a bitmap you still need elsewhere, and do not reuse a bitmap after it has been replaced. A recycled bitmap is ignored when set.
A bitmap you decode and assign yourself is drawn whole on every frame, so very large bitmaps make gestures less fluid (on a Pixel 7a, a 4032x3024 photo scaled up by density to about 10584x7938 took around 100 ms per frame, against 7 ms at its own size). For large photos do not decode them yourself: use the multi-resolution path described in Large images. The view enables mipmaps on the bitmap it is given (Bitmap.setHasMipMap(true)) to make drawing at reduced sizes cheaper.

Large images

A photo of several megapixels does not need to be held whole in memory to be shown on a screen. When the image is set through an ImageSource (or setImageResource, setImageUri, setImageFile, or app:src on a raster resource), the view decodes it by regions and keeps only what the current zoom needs:

  • Preview: a low resolution version of the whole image, decoded first, so that something is visible quickly and the image can always be drawn while sharper data is loading.

  • Cached levels: sharper versions of the whole image, kept while they fit in cachedLevelsMemoryBudget.

  • Patch: when zoomed in beyond the cached levels, only the visible region is decoded at full resolution and drawn over the coarser data. Panning or zooming decodes a new patch in background; meanwhile the coarser data keeps being drawn (a new patch appears without a fade-in).

Decoding runs on a worker thread, and the decoded bitmaps are released when the view is detached from the window and decoded again when it is attached. When the system reports memory pressure (onTrimMemory or onLowMemory), the patch and the cached levels sharper than the preview are dropped and decoded again when needed. The decoded bitmaps are hardware bitmaps when the view is hardware accelerated and hardwareBitmapsEnabled is true. Use imageLoadListener to be told when the preview and the sharper data are ready.

In a layout

<com.irurueta.android.gesturebitmap.GestureBitmapView
    android:id="@+id/gesture_bitmap"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:src="@drawable/image"
    app:regionDecodingEnabled="true"
    app:hardwareBitmapsEnabled="true"
    app:cachedLevelsMemoryBudget="33554432"/>

app:src on a raster resource (JPEG, PNG or WebP; not XML drawables or nine-patches) uses region decoding automatically, so existing layouts benefit without code changes. The three attributes are optional and their defaults are shown above (the budget default is computed from the view size, see below). Two things differ from the previous behaviour of app:src:

  • The EXIF orientation of the image is applied, so a photo taken in portrait is displayed upright.

  • The image size is the size in pixels of the file, instead of the size of a drawable scaled by density. This is only visible with DisplayType.NONE and DisplayType.FIT_IF_BIGGER, where the original size matters.

Set regionDecodingEnabled to false to get the previous behaviour.

From code

Set a resource, a content URI or a file. The view takes care of opening and closing the streams.

// R.drawable.image is a JPEG, PNG or WebP resource
view.setImageResource(R.drawable.image)
// a content:// or file:// URI, for instance returned by the system photo picker
val uri: Uri = Uri.fromFile(file)
view.setImageUri(uri)
view.setImageFile(file)

// keep the current zoom and position when replacing the image by another one
view.setImageFile(file, resetMatrices = false)

All of them accept resetMatrices (default true), as setBitmap does, and throw IOException if the image cannot be read or its format is not supported.

Image sources

ImageSource is the interface that provides the pixels: it exposes storedWidth, storedHeight and the EXIF orientation, and decodeRegion(region, sampleSize, config, reuse). ImageSources has factories for the common cases: fromResource, fromAsset, fromFile, fromUri and fromBytes.

// other factories: fromResource, fromAsset, fromFile and fromUri
view.setImageSource(ImageSources.fromBytes(bytes))
A source passed to setImageSource (or the imageSource property) is owned by the view: it is closed when it is replaced by another image or source, so do not close it nor use it afterwards. Setting the source that is already set does nothing.
Detaching the view releases the decoded bitmaps but keeps the source open, so that the image comes back when the view is attached again. When the view is not going to be used any more (for instance in onDestroy or onDestroyView), set imageSource = null to close the source and release its decoder right away instead of waiting for garbage collection. Sources are closed on a background thread, after any decode in progress, so custom ImageSource implementations must not assume close() runs on the UI thread.
Creating a source reads the image header. ImageSources.fromFile and ImageSources.fromUri (for URIs backed by a file) read the file as needed while decoding; the other factories keep the encoded image in memory. For large images or slow providers, create the source on a background thread and call setImageSource on the UI thread.

You can implement ImageSource to display an image that comes from anywhere (a network cache, a tiled file, a generator). decodeRegion is called on a worker thread and never concurrently with itself:

// Generates a 20000 x 20000 pixels image procedurally. It is never held whole in memory.
class CheckerboardImageSource : ImageSource {
    override val storedWidth = 20000
    override val storedHeight = 20000
    override val orientation = ExifInterface.ORIENTATION_NORMAL

    // called on a worker thread, never concurrently with itself
    override fun decodeRegion(
        region: Rect,
        sampleSize: Int,
        config: Bitmap.Config,
        reuse: Bitmap?
    ): Bitmap? {
        val width = (region.width() + sampleSize - 1) / sampleSize
        val height = (region.height() + sampleSize - 1) / sampleSize
        val result = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
        for (y in 0 until height) {
            for (x in 0 until width) {
                val column = (region.left + x * sampleSize) / 1000
                val row = (region.top + y * sampleSize) / 1000
                val color = if ((column + row) % 2 == 0) Color.DKGRAY else Color.LTGRAY
                result.setPixel(x, y, color)
            }
        }
        return result
    }

    override fun close() {
        // release anything held by the source
    }
}

view.setImageSource(CheckerboardImageSource())

EXIF orientation

The orientation reported by the source is applied by the view: the image is displayed upright, displayType computes the base transformation from the upright size, and every coordinate exposed by the view (mapViewToImage, invalidateImage regions, the canvas of the overlay drawer) is expressed in upright image pixels. Factories read the orientation from the file’s EXIF data (JPEG, and other formats that carry it). A custom source reports it in orientation with an ExifInterface.ORIENTATION_* value.

Memory budget

// 32 MiB for the decoded levels
view.cachedLevelsMemoryBudget = 32L * 1024L * 1024L

// only the preview is kept: lowest memory use, details are decoded as patches
view.cachedLevelsMemoryBudget = 0L

// back to the default: 4 times the pixels of the view, 4 bytes each
view.cachedLevelsMemoryBudget = GestureBitmapView.DEFAULT_CACHED_LEVELS_MEMORY_BUDGET

cachedLevelsMemoryBudget is expressed in bytes. By default (DEFAULT_CACHED_LEVELS_MEMORY_BUDGET) it is 4 times the number of pixels of the view, at 4 bytes per pixel. A budget of 0 keeps only the preview. Negative values throw IllegalArgumentException.

Switching decoding off

// images set through an ImageSource are decoded whole, at their full resolution
view.regionDecodingEnabled = false
view.setImageFile(file)

With regionDecodingEnabled = false an image set through an ImageSource is decoded whole at its full resolution and drawn as a regular bitmap. Use it for small images or to compare. Changing the flag reconfigures the current image.

// decode into software bitmaps (for instance to read their pixels)
view.hardwareBitmapsEnabled = false

Hardware bitmaps use less memory and are faster to draw, but their pixels cannot be read from the CPU.

Setting a bitmap yourself

// the bitmap is held whole in memory; the view recycles it when it is replaced
view.bitmap = bitmap

The bitmap property, setBitmap and setDrawable keep their behaviour (the bitmap is held whole and recycled when replaced). While an ImageSource is set, the bitmap getter returns null and imageSource returns the source.

Knowing when the image is loaded

view.imageLoadListener = object : GestureBitmapView.OnImageLoadListener {
    override fun onPreviewLoaded(view: GestureBitmapView) {
        // the whole image is visible, at low resolution
    }

    override fun onDetailLoaded(view: GestureBitmapView) {
        // a sharper level or a patch has been decoded
    }

    override fun onImageLoadFailed(view: GestureBitmapView, error: Throwable?) {
        Log.e(TAG, "Image could not be decoded", error)
    }
}

onPreviewLoaded is called when the preview is decoded, onDetailLoaded each time a sharper level or a patch is decoded, and onImageLoadFailed when decoding fails.

To change the contents of an image that is already displayed, see Updating image contents.

Choosing a display type

displayType decides how the bitmap is initially fitted into the view. The default is FIT_X_CENTER.

DisplayType XML value Initial display

NONE

none

Original scale, no rotation or translation.

FIT_IF_BIGGER

fit_if_bigger

Scaled down to fit (keeping aspect ratio) and centered only if bigger than the view.

FIT_X_TOP

fit_x_top

Scaled to fit horizontally, aligned to the top border.

FIT_X_BOTTOM

fit_x_bottom

Scaled to fit horizontally, aligned to the bottom border.

FIT_X_CENTER

fit_x_center

Scaled to fit horizontally, vertically centered (default).

FIT_Y_LEFT

fit_y_left

Scaled to fit vertically, aligned to the left border.

FIT_Y_RIGHT

fit_y_right

Scaled to fit vertically, aligned to the right border.

FIT_Y_CENTER

fit_y_center

Scaled to fit vertically, horizontally centered.

CENTER_CROP

center_crop

Scaled to fill the whole view, keeping aspect ratio, and centered.

The "fit" modes keep the aspect ratio, so there may be blank space along the other axis, or the bitmap may not fit completely along it.

Changing displayType at runtime keeps what is currently on screen unchanged: the base transformation is recomputed and the gesture transformation is adjusted so that the overall display transformation stays the same. The base transformation is also recomputed when the view is resized.

view.displayType = GestureBitmapView.DisplayType.FIT_Y_CENTER

Enabling and disabling gestures

view.scrollEnabled = true
view.twoFingerScrollEnabled = true
view.exclusiveTwoFingerScrollEnabled = false
view.scaleEnabled = true
view.doubleTapEnabled = true
view.rotationEnabled = false
view.rotationFlingEnabled = true // keep rotating after a rotation gesture ends while still rotating

See Gestures for how these flags interact.

Limits and bounce effect

view.minScale = 1.0f          // must be > 0
view.maxScale = 5.0f          // must be > 0
view.scaleFactorJump = 2.0f   // must be >= 1
view.minScaleMargin = 0.1f
view.maxScaleMargin = 1.0f
view.leftScrollMargin = 50.0f // pixels, must be >= 0
view.topScrollMargin = 50.0f
view.rightScrollMargin = 50.0f
view.bottomScrollMargin = 50.0f
view.scrollTensionEnabled = true // progressive slowdown while dragging past a limit
view.scrollTension = 2.0f // stiffer than the default linear resistance (1.0), must be >= 0
view.animationDurationMillis = 300L

Setters throw IllegalArgumentException for out-of-range values (as noted in the comments above).

Listeners

GestureBitmapView exposes one nullable property per event. Each listener is a regular Kotlin interface nested in GestureBitmapView, with a single method that receives the view that raised the event.

Property Interface and method Raised when

topBoundReachedListener

OnTopBoundReachedListener.onTopBoundReached(view)

A scroll reaches the top limit of the bitmap.

bottomBoundReachedListener

OnBottomBoundReachedListener.onBottomBoundReached(view)

A scroll reaches the bottom limit.

leftBoundReachedListener

OnLeftBoundReachedListener.onLeftBoundReached(view)

A scroll reaches the left limit.

rightBoundReachedListener

OnRightBoundReachedListener.onRightBoundReached(view)

A scroll reaches the right limit.

minScaleReachedListener

OnMinScaleReachedListener.onMinScaleReached(view)

A scale animation ends at or below minScale.

maxScaleReachedListener

OnMaxScaleReachedListener.onMaxScaleReached(view)

A scale animation ends at or above maxScale.

scaleAnimationCompletedListener

OnScaleAnimationCompletedListener.onScaleAnimationCompleted(view)

A scale animation (double tap, or returning within the scale limits) completes.

scrollAnimationCompletedListener

OnScrollAnimationCompletedListener.onScrollAnimationCompleted(view)

A scroll animation (fling, or returning within the scroll limits) completes.

rotateAndTranslateAnimationCompletedListener

OnRotateAndTranslateAnimationCompletedListener.onRotateAndTranslateAnimationCompleted(view)

The scale animation that also restores rotation and translation when a double tap returns to the minimum scale completes. It is not notified when a gesture ends below the minimum scale, since rotation is kept in that case.

doubleTapListener

OnDoubleTapListener.onDoubleTap(view)

A double tap is detected (raised even when doubleTapEnabled is false).

view.doubleTapListener = object : GestureBitmapView.OnDoubleTapListener {
    override fun onDoubleTap(view: GestureBitmapView) {
        Log.d(TAG, "Double tap")
    }
}

view.maxScaleReachedListener = object : GestureBitmapView.OnMaxScaleReachedListener {
    override fun onMaxScaleReached(view: GestureBitmapView) {
        Log.d(TAG, "Maximum scale reached: ${view.transformationParameters.scale}")
    }
}

view.leftBoundReachedListener = object : GestureBitmapView.OnLeftBoundReachedListener {
    override fun onLeftBoundReached(view: GestureBitmapView) {
        // e.g. switch to the previous image of a gallery
    }
}

The view also forwards standard View events: a confirmed single tap calls performClick(), so setOnClickListener works, and a long press calls performLongClick() when the view is long-clickable and no pinch is in progress, so setOnLongClickListener works too.

Reading and setting the transformation

// Transformation applied by gestures on top of the base (display type) transformation
val params: MetricTransformationParameters = view.transformationParameters
Log.d(TAG, "scale=${params.scale} angle=${params.rotationAngle} " +
    "tx=${params.horizontalTranslation} ty=${params.verticalTranslation}")

// Set it programmatically (no scale or scroll limits are enforced here)
view.transformationParameters = MetricTransformationParameters(
    scale = 2.0,
    rotationAngle = Math.PI / 4.0,
    horizontalTranslation = 0.0,
    verticalTranslation = 0.0
)

// Back to the initial display
view.resetTransformationParameters()

// Other read-only views of the transformation
val base: Matrix = view.baseTransformationMatrix
val display: Matrix = view.displayTransformationMatrix
val visibleArea: RectF? = view.displayRect // null when no bitmap is set

Each getter returns a new copy, so modifying the returned Matrix or MetricTransformationParameters does not affect the view; assign transformationParameters to apply a change. Setting transformationParameters or calling resetTransformationParameters() cancels any running animation and redraws the view.

Mapping touch coordinates to bitmap coordinates

displayTransformationMatrix maps bitmap pixels to view pixels, so its inverse maps a view point back to the bitmap:

val inverse = Matrix()
if (view.displayTransformationMatrix.invert(inverse)) {
    val point = floatArrayOf(touchX, touchY)
    inverse.mapPoints(point)
    // point[0], point[1] are now bitmap pixel coordinates
}

Antialiasing

Bitmaps are drawn with antialiasing by default. Disable it with view.isAntialiasingEnabled = false.

State saving

The view saves and restores its base, gesture and display matrices, gesture flags, displayType, scale limits and margins, scroll margins, scrollTensionEnabled and scrollTension across configuration changes, as long as it has an android:id. regionDecodingEnabled, hardwareBitmapsEnabled and cachedLevelsMemoryBudget are saved too. The bitmap or image source itself, animationDurationMillis, isAntialiasingEnabled, imageLoadListener, imageOverlayDrawer and the other listeners are not saved: set them again when the activity or fragment is recreated.