1+ package com.smarttoolfactory.image.util
2+
3+ import androidx.compose.ui.geometry.Offset
4+ import androidx.compose.ui.geometry.Rect
5+ import androidx.compose.ui.geometry.Size
6+
7+ /* *
8+ * Get rectangle of current transformation of [pan], [zoom] and current bounds of the Composable's
9+ * selected area as [rectSelection] in a Bitmap with [bitmapWidth] and [bitmapHeight] which
10+ * is displayed in a Composable with [containerWidth] and [containerHeight].
11+ *
12+ * This is getting area to display or crop based on the rectangle returned
13+ *
14+ * @param bitmapWidth width of the physical file
15+ * @param bitmapHeight height of the physical file
16+ * @param containerWidth width of the Composable that displays image
17+ * @param containerHeight height of the Composable that displays image
18+ * @param pan current translation of image via gestures or set values
19+ * @param rectSelection bounds of the selected area in Composable. This can be used for selecting
20+ * area via a cropping app
21+ */
22+ fun getCropRect (
23+ bitmapWidth : Int ,
24+ bitmapHeight : Int ,
25+ containerWidth : Float ,
26+ containerHeight : Float ,
27+ pan : Offset ,
28+ zoom : Float ,
29+ rectSelection : Rect
30+ ): Rect {
31+ val widthRatio = bitmapWidth / containerWidth
32+ val heightRatio = bitmapHeight / containerHeight
33+
34+ val width = (widthRatio * rectSelection.width / zoom).coerceIn(0f , bitmapWidth.toFloat())
35+ val height = (heightRatio * rectSelection.height / zoom).coerceIn(0f , bitmapHeight.toFloat())
36+
37+ val offsetXInBitmap = (widthRatio * (pan.x + rectSelection.left / zoom))
38+ .coerceIn(0f , bitmapWidth - width)
39+ val offsetYInBitmap = heightRatio * (pan.y + rectSelection.top / zoom)
40+ .coerceIn(0f , bitmapHeight - height)
41+
42+ return Rect (
43+ offset = Offset (offsetXInBitmap, offsetYInBitmap),
44+ size = Size (width, height)
45+ )
46+ }
0 commit comments