Modern Apps git

← Modern-Apps.git

pdf: allow quadrilateral transformation instead of just cropping

Commit
0dab706ef0a78ddafb870a311e0800f258e8b7c6
Author
Vayun Mathur <[email protected]>
When
2026-06-05 03:19 UTC (6 months ago)
Parents
eef328a

Diff

pdf/src/main/java/com/vayunmathur/pdf/model/CapturedImage.kt
diff --git a/pdf/src/main/java/com/vayunmathur/pdf/model/CapturedImage.kt b/pdf/src/main/java/com/vayunmathur/pdf/model/CapturedImage.ktindex 0fb4feb09e..9e14312adc 100644--- a/pdf/src/main/java/com/vayunmathur/pdf/model/CapturedImage.kt+++ b/pdf/src/main/java/com/vayunmathur/pdf/model/CapturedImage.kt@@ -1,9 +1,54 @@ package com.vayunmathur.pdf.model  import android.net.Uri+import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Rect +/**+ * Represents a quadrilateral with 4 independent corner points.+ * Points are in normalized coordinates (0f..1f) relative to the image dimensions.+ * Order: top-left, top-right, bottom-right, bottom-left (clockwise)+ */+data class Quadrilateral(+    val topLeft: Offset,+    val topRight: Offset,+    val bottomRight: Offset,+    val bottomLeft: Offset+) {+    companion object {+        /** Creates a quadrilateral from a Rect (for backward compatibility) */+        fun fromRect(rect: Rect): Quadrilateral {+            return Quadrilateral(+                topLeft = Offset(rect.left, rect.top),+                topRight = Offset(rect.right, rect.top),+                bottomRight = Offset(rect.right, rect.bottom),+                bottomLeft = Offset(rect.left, rect.bottom)+            )+        }+        +        /** Creates a default quadrilateral covering the full image */+        fun default(): Quadrilateral {+            return Quadrilateral(+                topLeft = Offset(0f, 0f),+                topRight = Offset(1f, 0f),+                bottomRight = Offset(1f, 1f),+                bottomLeft = Offset(0f, 1f)+            )+        }+    }+    +    /** Converts to Rect by computing the bounding box (for backward compatibility) */+    fun toBoundingRect(): Rect {+        val left = minOf(topLeft.x, topRight.x, bottomRight.x, bottomLeft.x)+        val top = minOf(topLeft.y, topRight.y, bottomRight.y, bottomLeft.y)+        val right = maxOf(topLeft.x, topRight.x, bottomRight.x, bottomLeft.x)+        val bottom = maxOf(topLeft.y, topRight.y, bottomRight.y, bottomLeft.y)+        return Rect(left, top, right, bottom)+    }+}+ data class CapturedImage(     val uri: Uri,-    val cropRect: Rect? = null+    val cropRect: Rect? = null,+    val quadrilateral: Quadrilateral? = null )
pdf/src/main/java/com/vayunmathur/pdf/ui/CapturePdfScreen.kt
diff --git a/pdf/src/main/java/com/vayunmathur/pdf/ui/CapturePdfScreen.kt b/pdf/src/main/java/com/vayunmathur/pdf/ui/CapturePdfScreen.ktindex 012bcbcb40..d707a7f381 100644--- a/pdf/src/main/java/com/vayunmathur/pdf/ui/CapturePdfScreen.kt+++ b/pdf/src/main/java/com/vayunmathur/pdf/ui/CapturePdfScreen.kt@@ -136,9 +136,9 @@ fun CapturePdfScreen(         val currentImage = images[currentSelected]         CropScreen(             uri = currentImage.uri,-            initialCrop = currentImage.cropRect,-            onCropDone = { newRect ->-                viewModel.updateCrop(currentSelected, newRect)+            initialQuadrilateral = currentImage.quadrilateral,+            onCropDone = { newQuadrilateral ->+                viewModel.updateQuadrilateral(currentSelected, newQuadrilateral)                 isCropping = false             },             onBack = { isCropping = false }
pdf/src/main/java/com/vayunmathur/pdf/ui/CropScreen.kt
diff --git a/pdf/src/main/java/com/vayunmathur/pdf/ui/CropScreen.kt b/pdf/src/main/java/com/vayunmathur/pdf/ui/CropScreen.ktindex 9863058bd9..982e23e549 100644--- a/pdf/src/main/java/com/vayunmathur/pdf/ui/CropScreen.kt+++ b/pdf/src/main/java/com/vayunmathur/pdf/ui/CropScreen.kt@@ -9,6 +9,7 @@ import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.offset+import androidx.compose.foundation.layout.aspectRatio import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.material3.ExperimentalMaterial3Api@@ -45,6 +46,7 @@ import coil.compose.AsyncImage import com.vayunmathur.library.ui.IconNavigation import com.vayunmathur.library.ui.IconSave import com.vayunmathur.pdf.R+import com.vayunmathur.pdf.model.Quadrilateral import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import kotlin.math.roundToInt@@ -53,21 +55,35 @@ import kotlin.math.roundToInt @Composable fun CropScreen(     uri: Uri,-    initialCrop: Rect?,-    onCropDone: (Rect) -> Unit,+    initialQuadrilateral: Quadrilateral?,+    onCropDone: (Quadrilateral) -> Unit,     onBack: () -> Unit ) {     val context = LocalContext.current-    var crop by remember { mutableStateOf(initialCrop ?: Rect(0f, 0f, 1f, 1f)) }+    var quadrilateral by remember {+        mutableStateOf(initialQuadrilateral ?: Quadrilateral.default())+    }     var originalSize by remember { mutableStateOf<IntSize?>(null) }      LaunchedEffect(uri) {         withContext(Dispatchers.IO) {-            val options = BitmapFactory.Options().apply { inJustDecodeBounds = true }-            context.contentResolver.openInputStream(uri)?.use { -                BitmapFactory.decodeStream(it, null, options)+            try {+                // Use ImageDecoder which respects EXIF orientation+                val source = android.graphics.ImageDecoder.createSource(context.contentResolver, uri)+                val bitmap = android.graphics.ImageDecoder.decodeBitmap(source) { decoder, _, _ ->+                    decoder.allocator = android.graphics.ImageDecoder.ALLOCATOR_SOFTWARE+                    decoder.isMutableRequired = false+                }+                originalSize = IntSize(bitmap.width, bitmap.height)+                bitmap.recycle()+            } catch (e: Exception) {+                // Fallback to BitmapFactory if ImageDecoder fails+                val options = BitmapFactory.Options().apply { inJustDecodeBounds = true }+                context.contentResolver.openInputStream(uri)?.use {+                    BitmapFactory.decodeStream(it, null, options)+                }+                originalSize = IntSize(options.outWidth, options.outHeight)             }-            originalSize = IntSize(options.outWidth, options.outHeight)         }     } @@ -82,7 +98,7 @@ fun CropScreen(         },         floatingActionButton = {             ExtendedFloatingActionButton(-                onClick = { onCropDone(crop) },+                onClick = { onCropDone(quadrilateral) },                 text = { Text(stringResource(R.string.continue_label)) },                 icon = { IconSave() }             )@@ -99,24 +115,43 @@ fun CropScreen(         ) {             val maxWidth = constraints.maxWidth.toFloat()             val maxHeight = constraints.maxHeight.toFloat()-            +             originalSize?.let { size ->                 val photoRatio = size.width.toFloat() / size.height.toFloat()                 val containerRatio = maxWidth / maxHeight+                // Calculate size to fit within container while maintaining aspect ratio+                // Use maximum available space                 val (viewportWidth, viewportHeight) = if (photoRatio > containerRatio) {+                    // Photo is wider than container - fit to width                     maxWidth to (maxWidth / photoRatio)                 } else {+                    // Photo is taller than container - fit to height                     (maxHeight * photoRatio) to maxHeight                 } -                Box(Modifier.size(with(LocalDensity.current) { viewportWidth.toDp() }, with(LocalDensity.current) { viewportHeight.toDp() })) {-                    AsyncImage(-                        model = uri,-                        contentDescription = null,-                        modifier = Modifier.fillMaxSize(),-                        contentScale = ContentScale.FillBounds-                    )-                    CropOverlay(cropRect = crop, onCropRectChange = { crop = it })+                Box(+                    Modifier.fillMaxSize(),+                    contentAlignment = Alignment.Center+                ) {+                    // Single box with exact size containing both image and overlay+                    // This ensures they are perfectly aligned+                    Box(+                        Modifier.size(+                            with(LocalDensity.current) { viewportWidth.toDp() },+                            with(LocalDensity.current) { viewportHeight.toDp() }+                        )+                    ) {+                        AsyncImage(+                            model = uri,+                            contentDescription = null,+                            modifier = Modifier.fillMaxSize(),+                            contentScale = ContentScale.FillBounds+                        )+                        CropOverlay(+                            quadrilateral = quadrilateral,+                            onQuadrilateralChange = { quadrilateral = it }+                        )+                    }                 }             } ?: AsyncImage(                 model = uri,@@ -129,57 +164,63 @@ fun CropScreen( }  @Composable-fun CropOverlay(cropRect: Rect, onCropRectChange: (Rect) -> Unit) {+fun CropOverlay(quadrilateral: Quadrilateral, onQuadrilateralChange: (Quadrilateral) -> Unit) {     BoxWithConstraints(modifier = Modifier.fillMaxSize()) {         val width = constraints.maxWidth.toFloat()         val height = constraints.maxHeight.toFloat()++        // Convert normalized coordinates to screen coordinates+        val topLeft = Offset(quadrilateral.topLeft.x * width, quadrilateral.topLeft.y * height)+        val topRight = Offset(quadrilateral.topRight.x * width, quadrilateral.topRight.y * height)+        val bottomRight = Offset(quadrilateral.bottomRight.x * width, quadrilateral.bottomRight.y * height)+        val bottomLeft = Offset(quadrilateral.bottomLeft.x * width, quadrilateral.bottomLeft.y * height)+         Canvas(modifier = Modifier.fillMaxSize()) {-            val rect = Rect(cropRect.left * width, cropRect.top * height, cropRect.right * width, cropRect.bottom * height)+            // Draw dark overlay with quadrilateral cutout             val path = Path().apply {+                // Outer rectangle (full screen)                 addRect(Rect(0f, 0f, width, height))-                addRect(rect)+                // Inner quadrilateral (the crop area) - using EvenOdd to create a hole+                moveTo(topLeft.x, topLeft.y)+                lineTo(topRight.x, topRight.y)+                lineTo(bottomRight.x, bottomRight.y)+                lineTo(bottomLeft.x, bottomLeft.y)+                close()                 fillType = PathFillType.EvenOdd             }             drawPath(path, Color.Black.copy(alpha = 0.5f))-            drawRect(color = Color.White, topLeft = Offset(rect.left, rect.top), size = androidx.compose.ui.geometry.Size(rect.width, rect.height), style = Stroke(width = 2.dp.toPx()))-        }-        -        // Draggable area for moving the whole crop-        Box(modifier = Modifier-            .offset { IntOffset((cropRect.left * width).roundToInt(), (cropRect.top * height).roundToInt()) }-            .size(width = with(LocalDensity.current) { (cropRect.width * width).toDp() }, height = with(LocalDensity.current) { (cropRect.height * height).toDp() })-            .pointerInput(cropRect) {-                detectDragGestures { change, dragAmount ->-                    change.consume()-                    val dx = dragAmount.x / width-                    val dy = dragAmount.y / height-                    val newLeft = (cropRect.left + dx).coerceIn(0f, 1f - cropRect.width)-                    val newTop = (cropRect.top + dy).coerceIn(0f, 1f - cropRect.height)-                    onCropRectChange(Rect(left = newLeft, top = newTop, right = newLeft + cropRect.width, bottom = newTop + cropRect.height))-                }++            // Draw quadrilateral border+            val borderPath = Path().apply {+                moveTo(topLeft.x, topLeft.y)+                lineTo(topRight.x, topRight.y)+                lineTo(bottomRight.x, bottomRight.y)+                lineTo(bottomLeft.x, bottomLeft.y)+                close()             }-        )+            drawPath(borderPath, Color.White, style = Stroke(width = 2.dp.toPx()))+        } -        // Corner handles-        CropHandle(offset = Offset(cropRect.left * width, cropRect.top * height)) { delta ->-            val newLeft = (cropRect.left + delta.x / width).coerceIn(0f, cropRect.right - 0.05f)-            val newTop = (cropRect.top + delta.y / height).coerceIn(0f, cropRect.bottom - 0.05f)-            onCropRectChange(cropRect.copy(left = newLeft, top = newTop))+        // Corner handles - each can be dragged independently+        CropHandle(offset = topLeft) { delta ->+            val newX = (quadrilateral.topLeft.x + delta.x / width).coerceIn(0f, 1f)+            val newY = (quadrilateral.topLeft.y + delta.y / height).coerceIn(0f, 1f)+            onQuadrilateralChange(quadrilateral.copy(topLeft = Offset(newX, newY)))         }-        CropHandle(offset = Offset(cropRect.right * width, cropRect.top * height)) { delta ->-            val newRight = (cropRect.right + delta.x / width).coerceIn(cropRect.left + 0.05f, 1f)-            val newTop = (cropRect.top + delta.y / height).coerceIn(0f, cropRect.bottom - 0.05f)-            onCropRectChange(cropRect.copy(right = newRight, top = newTop))+        CropHandle(offset = topRight) { delta ->+            val newX = (quadrilateral.topRight.x + delta.x / width).coerceIn(0f, 1f)+            val newY = (quadrilateral.topRight.y + delta.y / height).coerceIn(0f, 1f)+            onQuadrilateralChange(quadrilateral.copy(topRight = Offset(newX, newY)))         }-        CropHandle(offset = Offset(cropRect.left * width, cropRect.bottom * height)) { delta ->-            val newLeft = (cropRect.left + delta.x / width).coerceIn(0f, cropRect.right - 0.05f)-            val newBottom = (cropRect.bottom + delta.y / height).coerceIn(cropRect.top + 0.05f, 1f)-            onCropRectChange(cropRect.copy(left = newLeft, bottom = newBottom))+        CropHandle(offset = bottomRight) { delta ->+            val newX = (quadrilateral.bottomRight.x + delta.x / width).coerceIn(0f, 1f)+            val newY = (quadrilateral.bottomRight.y + delta.y / height).coerceIn(0f, 1f)+            onQuadrilateralChange(quadrilateral.copy(bottomRight = Offset(newX, newY)))         }-        CropHandle(offset = Offset(cropRect.right * width, cropRect.bottom * height)) { delta ->-            val newRight = (cropRect.right + delta.x / width).coerceIn(cropRect.left + 0.05f, 1f)-            val newBottom = (cropRect.bottom + delta.y / height).coerceIn(cropRect.top + 0.05f, 1f)-            onCropRectChange(cropRect.copy(right = newRight, bottom = newBottom))+        CropHandle(offset = bottomLeft) { delta ->+            val newX = (quadrilateral.bottomLeft.x + delta.x / width).coerceIn(0f, 1f)+            val newY = (quadrilateral.bottomLeft.y + delta.y / height).coerceIn(0f, 1f)+            onQuadrilateralChange(quadrilateral.copy(bottomLeft = Offset(newX, newY)))         }     } }
pdf/src/main/java/com/vayunmathur/pdf/ui/components/SubcroppedImage.kt
diff --git a/pdf/src/main/java/com/vayunmathur/pdf/ui/components/SubcroppedImage.kt b/pdf/src/main/java/com/vayunmathur/pdf/ui/components/SubcroppedImage.ktindex 678af7e960..ffb9a8559d 100644--- a/pdf/src/main/java/com/vayunmathur/pdf/ui/components/SubcroppedImage.kt+++ b/pdf/src/main/java/com/vayunmathur/pdf/ui/components/SubcroppedImage.kt@@ -1,9 +1,14 @@ package com.vayunmathur.pdf.ui.components +import android.graphics.Bitmap+import android.graphics.ImageDecoder+import android.graphics.Matrix+import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.aspectRatio import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember@@ -13,19 +18,101 @@ import androidx.compose.ui.draw.clipToBounds import androidx.compose.ui.geometry.Rect import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.TransformOrigin+import androidx.compose.ui.graphics.asImageBitmap import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.layout.ContentScale+import androidx.compose.ui.platform.LocalContext import coil.compose.AsyncImage import coil.compose.AsyncImagePainter import com.vayunmathur.pdf.model.CapturedImage+import com.vayunmathur.pdf.model.Quadrilateral+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext+import kotlin.math.roundToInt  @Composable fun SubcroppedImage(     image: CapturedImage,     modifier: Modifier = Modifier+) {+    val quad = image.quadrilateral+    if (quad != null) {+        PerspectiveCroppedImage(image, quad, modifier)+    } else {+        BoundingBoxCroppedImage(image, modifier)+    }+}++@Composable+private fun PerspectiveCroppedImage(+    image: CapturedImage,+    quad: Quadrilateral,+    modifier: Modifier+) {+    val context = LocalContext.current+    var croppedBitmap by remember(image.uri, quad) { mutableStateOf<Bitmap?>(null) }++    LaunchedEffect(image.uri, quad) {+        withContext(Dispatchers.Default) {+            try {+                val source = ImageDecoder.createSource(context.contentResolver, image.uri)+                val bitmap = ImageDecoder.decodeBitmap(source) { decoder, _, _ ->+                    decoder.allocator = ImageDecoder.ALLOCATOR_SOFTWARE+                    decoder.isMutableRequired = false+                }++                val bounds = quad.toBoundingRect()+                val targetWidth = (bounds.width * bitmap.width).roundToInt().coerceAtLeast(1)+                val targetHeight = (bounds.height * bitmap.height).roundToInt().coerceAtLeast(1)++                val srcPoints = floatArrayOf(+                    quad.topLeft.x * bitmap.width, quad.topLeft.y * bitmap.height,+                    quad.topRight.x * bitmap.width, quad.topRight.y * bitmap.height,+                    quad.bottomRight.x * bitmap.width, quad.bottomRight.y * bitmap.height,+                    quad.bottomLeft.x * bitmap.width, quad.bottomLeft.y * bitmap.height+                )+                val dstPoints = floatArrayOf(+                    0f, 0f,+                    targetWidth.toFloat(), 0f,+                    targetWidth.toFloat(), targetHeight.toFloat(),+                    0f, targetHeight.toFloat()+                )+                val matrix = Matrix()+                val result = if (matrix.setPolyToPoly(srcPoints, 0, dstPoints, 0, 4)) {+                    val out = Bitmap.createBitmap(targetWidth, targetHeight, Bitmap.Config.ARGB_8888)+                    android.graphics.Canvas(out).drawBitmap(bitmap, matrix, null)+                    out+                } else {+                    // Fallback: bounding box crop+                    val left = (bounds.left * bitmap.width).roundToInt().coerceIn(0, bitmap.width - 1)+                    val top = (bounds.top * bitmap.height).roundToInt().coerceIn(0, bitmap.height - 1)+                    val w = targetWidth.coerceAtMost(bitmap.width - left)+                    val h = targetHeight.coerceAtMost(bitmap.height - top)+                    Bitmap.createBitmap(bitmap, left, top, w, h)+                }+                bitmap.recycle()+                croppedBitmap = result+            } catch (_: Exception) {}+        }+    }++    croppedBitmap?.let { bmp ->+        Image(+            bitmap = bmp.asImageBitmap(),+            contentDescription = null,+            modifier = modifier.aspectRatio(bmp.width.toFloat() / bmp.height.toFloat()),+            contentScale = ContentScale.Fit+        )+    }+}++@Composable+private fun BoundingBoxCroppedImage(+    image: CapturedImage,+    modifier: Modifier ) {     var painterSize by remember(image.uri) { mutableStateOf<Size?>(null) }-    +     val crop = image.cropRect ?: Rect(0f, 0f, 1f, 1f)     val finalModifier = if (painterSize != null && painterSize!!.width > 0f && painterSize!!.height > 0f) {         val aspect = (painterSize!!.width * crop.width) / (painterSize!!.height * crop.height)
pdf/src/main/java/com/vayunmathur/pdf/util/PdfExporter.kt
diff --git a/pdf/src/main/java/com/vayunmathur/pdf/util/PdfExporter.kt b/pdf/src/main/java/com/vayunmathur/pdf/util/PdfExporter.ktindex 5b04abaf9f..a65d13990d 100644--- a/pdf/src/main/java/com/vayunmathur/pdf/util/PdfExporter.kt+++ b/pdf/src/main/java/com/vayunmathur/pdf/util/PdfExporter.kt@@ -19,13 +19,22 @@ suspend fun savePdfToUri(context: Context, images: List<CapturedImage>, targetUr             val uri = capturedImage.uri             try {                 val crop = capturedImage.cropRect+                val quadrilateral = capturedImage.quadrilateral                 val source = ImageDecoder.createSource(context.contentResolver, uri)                 val bitmap = ImageDecoder.decodeBitmap(source) { decoder, _, _ ->                     decoder.allocator = ImageDecoder.ALLOCATOR_SOFTWARE                 }                 -                val cropWidth = if (crop != null) bitmap.width * crop.width else bitmap.width.toFloat()-                val cropHeight = if (crop != null) bitmap.height * crop.height else bitmap.height.toFloat()+                // Determine crop dimensions+                val (cropWidth, cropHeight) = when {+                    quadrilateral != null -> {+                        // For quadrilateral, use bounding box dimensions+                        val bounds = quadrilateral.toBoundingRect()+                        bitmap.width * bounds.width to bitmap.height * bounds.height+                    }+                    crop != null -> bitmap.width * crop.width to bitmap.height * crop.height+                    else -> bitmap.width.toFloat() to bitmap.height.toFloat()+                }                  // Scale the image so its longest side matches the longest side of A4 (842 points).                 val a4LongSide = 842f@@ -41,19 +50,59 @@ suspend fun savePdfToUri(context: Context, images: List<CapturedImage>, targetUr                 val pageInfo = PdfDocument.PageInfo.Builder(targetWidth, targetHeight, index + 1).create()                 val page = pdfDocument.startPage(pageInfo) -                if (crop != null) {-                    val srcRect = android.graphics.Rect(-                        (crop.left * bitmap.width).roundToInt(),-                        (crop.top * bitmap.height).roundToInt(),-                        (crop.right * bitmap.width).roundToInt(),-                        (crop.bottom * bitmap.height).roundToInt()-                    )-                    val dstRect = android.graphics.Rect(0, 0, targetWidth, targetHeight)-                    page.canvas.drawBitmap(bitmap, srcRect, dstRect, null)-                } else {-                    val matrix = Matrix()-                    matrix.postScale(scale, scale)-                    page.canvas.drawBitmap(bitmap, matrix, null)+                when {+                    quadrilateral != null -> {+                        // Apply perspective transform using Matrix.setPolyToPoly+                        // This maps the 4 corners of the quadrilateral to the 4 corners of the output rectangle+                        val srcPoints = floatArrayOf(+                            quadrilateral.topLeft.x * bitmap.width,+                            quadrilateral.topLeft.y * bitmap.height,+                            quadrilateral.topRight.x * bitmap.width,+                            quadrilateral.topRight.y * bitmap.height,+                            quadrilateral.bottomRight.x * bitmap.width,+                            quadrilateral.bottomRight.y * bitmap.height,+                            quadrilateral.bottomLeft.x * bitmap.width,+                            quadrilateral.bottomLeft.y * bitmap.height+                        )+                        val dstPoints = floatArrayOf(+                            0f, 0f,+                            targetWidth.toFloat(), 0f,+                            targetWidth.toFloat(), targetHeight.toFloat(),+                            0f, targetHeight.toFloat()+                        )+                        val matrix = Matrix()+                        val success = matrix.setPolyToPoly(srcPoints, 0, dstPoints, 0, 4)+                        if (!success) {+                            Log.w("PdfExporter", "setPolyToPoly failed, falling back to bounding rect crop")+                            // Fallback to bounding rect if perspective transform fails+                            val bounds = quadrilateral.toBoundingRect()+                            val srcRect = android.graphics.Rect(+                                (bounds.left * bitmap.width).roundToInt(),+                                (bounds.top * bitmap.height).roundToInt(),+                                (bounds.right * bitmap.width).roundToInt(),+                                (bounds.bottom * bitmap.height).roundToInt()+                            )+                            val dstRect = android.graphics.Rect(0, 0, targetWidth, targetHeight)+                            page.canvas.drawBitmap(bitmap, srcRect, dstRect, null)+                        } else {+                            page.canvas.drawBitmap(bitmap, matrix, null)+                        }+                    }+                    crop != null -> {+                        val srcRect = android.graphics.Rect(+                            (crop.left * bitmap.width).roundToInt(),+                            (crop.top * bitmap.height).roundToInt(),+                            (crop.right * bitmap.width).roundToInt(),+                            (crop.bottom * bitmap.height).roundToInt()+                        )+                        val dstRect = android.graphics.Rect(0, 0, targetWidth, targetHeight)+                        page.canvas.drawBitmap(bitmap, srcRect, dstRect, null)+                    }+                    else -> {+                        val matrix = Matrix()+                        matrix.postScale(scale, scale)+                        page.canvas.drawBitmap(bitmap, matrix, null)+                    }                 }                  pdfDocument.finishPage(page)
pdf/src/main/java/com/vayunmathur/pdf/util/PdfViewModel.kt
diff --git a/pdf/src/main/java/com/vayunmathur/pdf/util/PdfViewModel.kt b/pdf/src/main/java/com/vayunmathur/pdf/util/PdfViewModel.ktindex 846e7e3ab4..e29aec6c39 100644--- a/pdf/src/main/java/com/vayunmathur/pdf/util/PdfViewModel.kt+++ b/pdf/src/main/java/com/vayunmathur/pdf/util/PdfViewModel.kt@@ -11,6 +11,7 @@ import androidx.pdf.PdfPasswordException import androidx.pdf.SandboxedPdfLoader import com.vayunmathur.pdf.R import com.vayunmathur.pdf.model.CapturedImage+import com.vayunmathur.pdf.model.Quadrilateral import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableSharedFlow@@ -68,7 +69,16 @@ class PdfViewModel(application: Application) : AndroidViewModel(application) {         val current = _capturedImages.value         if (index !in current.indices) return         _capturedImages.value = current.toMutableList().also {-            it[index] = it[index].copy(cropRect = crop)+            it[index] = it[index].copy(cropRect = crop, quadrilateral = Quadrilateral.fromRect(crop))+        }+    }+    +    /** Updates the committed quadrilateral for the image at [index]. */+    fun updateQuadrilateral(index: Int, quadrilateral: Quadrilateral) {+        val current = _capturedImages.value+        if (index !in current.indices) return+        _capturedImages.value = current.toMutableList().also {+            it[index] = it[index].copy(quadrilateral = quadrilateral, cropRect = quadrilateral.toBoundingRect())         }     }