Skip to content

Commit 78746af

Browse files
update util functions
1 parent f8da3e4 commit 78746af

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
package com.smarttoolfactory.image.util
2+
3+
import androidx.compose.ui.geometry.Offset
4+
5+
6+
/**
7+
* Coerce an [Offset] x value in [horizontalRange] and y value in [verticalRange]
8+
*/
9+
fun Offset.coerceIn(
10+
horizontalRange: ClosedRange<Float>,
11+
verticalRange: ClosedRange<Float>
12+
) = Offset(this.x.coerceIn(horizontalRange), this.y.coerceIn(verticalRange))
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
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

Comments
 (0)