Usage

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

This page shows how to add CurlTextureView (package com.irurueta.android.gl.curl) to a screen, provide its pages and handle the activity lifecycle. Every property is listed with its default value in the Configuration reference.

Adding the view to a layout

CurlTextureView is a regular view, so it can be declared in XML next to any other view. Its background is transparent, so views declared before it remain visible around and behind the pages:

<?xml version="1.0" encoding="utf-8"?>
<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">

    <!-- Regular view drawn behind the pages: visible through the transparent background -->
    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="20dp"
        android:text="@string/title"
        android:textSize="40sp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <com.irurueta.android.gl.curl.CurlTextureView
        android:id="@+id/curl_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

Creating the view in code

CurlTextureView has a @JvmOverloads constructor (context, attrs = null, defStyleAttr = 0):

val curlView = CurlTextureView(context)
curlView.layoutParams = ViewGroup.LayoutParams(
    ViewGroup.LayoutParams.MATCH_PARENT,
    ViewGroup.LayoutParams.MATCH_PARENT
)
container.addView(curlView)
curlView.pageProvider = pageProvider

Providing pages

Nothing is drawn until a PageProvider is set. The provider tells the view how many pages there are and fills a CurlPage with the bitmap of each page when the view needs it:

private val pageProvider = object : CurlTextureView.PageProvider {

    // Total number of pages of the "book"
    override val pageCount: Int
        get() = bitmaps.size

    // Called every time a page needs its texture, possibly from the OpenGL thread.
    // width and height are the size in pixels the page is drawn with.
    override fun updatePage(
        page: CurlPage,
        width: Int,
        height: Int,
        index: Int,
        backIndex: Int?
    ) {
        val front = renderPage(width, height, index)
        if (backIndex == null) {
            // Same bitmap on both sides of the page
            page.setTexture(front, CurlPage.SIDE_BOTH)
        } else {
            // backIndex is the content to reveal on the back side (for instance, the target page
            // while jumping with setSmoothCurrentIndex)
            page.setTexture(front, CurlPage.SIDE_FRONT)
            page.setTexture(renderPage(width, height, backIndex), CurlPage.SIDE_BACK)
        }
    }
}

width and height are the size in pixels of a page on screen (the view size minus its margins, or half of it in two page mode). Returning bitmaps of that size keeps the aspect ratio of the page, although bitmaps of any size are accepted. A helper that scales a source image to fit the page could look like this:

/**
 * Draws the source bitmap of a page scaled to fit and centered on a white page of the requested size, so
 * that the aspect ratio of the source image is kept.
 */
private fun renderPage(width: Int, height: Int, index: Int): Bitmap? {
    val source = bitmaps[index] ?: return null

    val scale = min(width.toFloat() / source.width, height.toFloat() / source.height)
    val imageWidth = (scale * source.width).toInt()
    val imageHeight = (scale * source.height).toInt()
    val left = (width - imageWidth) / 2
    val top = (height - imageHeight) / 2

    val page = createBitmap(width, height)
    page.eraseColor(Color.WHITE)
    Canvas(page).drawBitmap(source, null, Rect(left, top, left + imageWidth, top + imageHeight), null)
    return page
}

Setting pageProvider resets the current page to 0 and requests the pages again. See Pages and textures for back sides, blend colors and memory considerations.

Handling the lifecycle

As with any GLTextureView (or GLSurfaceView), forward the activity or fragment lifecycle to the view, so that its OpenGL rendering thread is paused and resumed:

override fun onResume() {
    super.onResume()
    curlView.onResume()
}

override fun onPause() {
    super.onPause()
    curlView.onPause()
}

A complete activity

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.irurueta.android.gl.curl.CurlPage
import com.irurueta.android.gl.curl.CurlTextureView

class BookActivity : AppCompatActivity() {

    private lateinit var curlView: CurlTextureView

    // Source images, decoded once and kept in memory
    private val bitmaps = mutableListOf<Bitmap>()

    private val pageProvider = object : CurlTextureView.PageProvider {
        override val pageCount: Int
            get() = bitmaps.size

        override fun updatePage(page: CurlPage, width: Int, height: Int, index: Int, backIndex: Int?) {
            page.setTexture(renderPage(width, height, index), CurlPage.SIDE_BOTH)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_book)

        listOf(R.drawable.page1, R.drawable.page2, R.drawable.page3).forEach {
            bitmaps.add(BitmapFactory.decodeResource(resources, it))
        }

        curlView = findViewById(R.id.curl_view)
        curlView.pageProvider = pageProvider
    }

    override fun onResume() {
        super.onResume()
        curlView.onResume()
    }

    override fun onPause() {
        super.onPause()
        curlView.onPause()
    }

    override fun onDestroy() {
        super.onDestroy()
        bitmaps.forEach { it.recycle() }
        bitmaps.clear()
    }

    private fun renderPage(width: Int, height: Int, index: Int): Bitmap {
        // Scale the source bitmap to the page size (see "Pages and textures")
        return Bitmap.createScaledBitmap(bitmaps[index], width, height, true)
    }
}

Reacting to size changes

Margins depend on the view size, which is only known once the view has been laid out. Set a SizeChangedObserver to adjust them, and set the page provider from there, so that the first pages are requested with their final size. This is what the sample app does to leave room for a title above the pages:

curlView.sizeChangedObserver = object : CurlTextureView.SizeChangedObserver {
    override fun onSizeChanged(width: Int, height: Int) {
        // Leave room for the title above the pages and a 20dp margin elsewhere
        val margin = dp2px(20.0f)
        val topMargin = 2 * margin + titleView.measuredHeight

        curlView.setProportionalMargins(
            margin.toFloat() / width,    // left
            topMargin.toFloat() / height, // top
            margin.toFloat() / width,    // right
            margin.toFloat() / width     // bottom
        )

        // Pages are requested with the final size once the provider is set
        curlView.pageProvider = pageProvider
    }
}

Choosing a view

Both views expose the same properties, methods and listeners. The only difference is the class they extend:

  • CurlTextureView extends GLTextureView, a TextureView. It is drawn as part of the view hierarchy, so it supports a transparent background, alpha, view animations and transformations, and it can be placed between other views:

    // CurlTextureView is part of the view hierarchy, so regular view properties and animations apply
    curlView.alpha = 0.9f
    curlView.animate()
        .rotationY(15.0f)
        .scaleX(0.9f)
        .scaleY(0.9f)
        .setDuration(400L)
        .start()
  • CurlGLSurfaceView extends GLSurfaceView. Its surface is composited separately from the window, which is slightly faster, but it cannot be animated, transformed or blended with other views like a regular view.

The listener and provider interfaces are nested in each class (CurlGLSurfaceView.PageProvider, CurlGLSurfaceView.PageClickListener…​), and their callbacks receive the corresponding view type:

// Same API, different base class. The page provider interface is nested in each view class.
val surfaceView = findViewById<CurlGLSurfaceView>(R.id.curl_surface_view)
surfaceView.pageProvider = object : CurlGLSurfaceView.PageProvider {
    override val pageCount: Int
        get() = bitmaps.size

    override fun updatePage(page: CurlPage, width: Int, height: Int, index: Int, backIndex: Int?) {
        page.setTexture(renderPage(width, height, index), CurlPage.SIDE_BOTH)
    }
}

Using the view from Jetpack Compose

CurlTextureView is a classic view, so it can be embedded in a composable with AndroidView. Composables drawn before it remain visible through its transparent background:

@Composable
fun Book(pageProvider: CurlTextureView.PageProvider, modifier: Modifier = Modifier) {
    val lifecycleOwner = LocalLifecycleOwner.current
    var curlView by remember { mutableStateOf<CurlTextureView?>(null) }

    AndroidView(
        modifier = modifier,
        factory = { context ->
            CurlTextureView(context).also {
                it.pageProvider = pageProvider
                curlView = it
            }
        }
    )

    // Forward resume/pause to the OpenGL thread of the view
    DisposableEffect(lifecycleOwner, curlView) {
        val view = curlView
        val observer = LifecycleEventObserver { _, event ->
            when (event) {
                Lifecycle.Event.ON_RESUME -> view?.onResume()
                Lifecycle.Event.ON_PAUSE -> view?.onPause()
                else -> Unit
            }
        }
        lifecycleOwner.lifecycle.addObserver(observer)
        onDispose { lifecycleOwner.lifecycle.removeObserver(observer) }
    }
}

Touch handling and rendering model

The view handles touch events itself: dragging from the right page curls it towards the left (next page), and dragging from the left page curls it back (previous page). When the finger is raised, the flip is completed or reverted with a short animation. A tap is reported to the PageClickListener.

The view renders only on demand (RENDER_MODE_WHEN_DIRTY): setters such as pageProvider, setCurrentIndex or setBackgroundColor request a new frame, and frames are rendered continuously only while a page is moving.