1+ package com.smarttoolfactory.cropper.crop
2+
3+ import android.graphics.Bitmap
4+ import androidx.compose.ui.geometry.Offset
5+ import androidx.compose.ui.geometry.Rect
6+ import androidx.compose.ui.graphics.*
7+ import androidx.compose.ui.unit.Density
8+ import androidx.compose.ui.unit.LayoutDirection
9+
10+ /* *
11+ * Crops imageBitmap based on path that is passed in [crop] function
12+ */
13+ class CropAgent {
14+
15+ private val imagePaint = Paint ().apply {
16+ blendMode = BlendMode .SrcIn
17+ }
18+
19+ private val paint = Paint ()
20+
21+ fun crop (
22+ imageBitmap : ImageBitmap ,
23+ cropRect : Rect ,
24+ shape : Shape ,
25+ layoutDirection : LayoutDirection ,
26+ density : Density ,
27+ onCropSuccess : (ImageBitmap ) -> Unit
28+ ) {
29+
30+ val croppedBitmap = Bitmap .createBitmap(
31+ imageBitmap.asAndroidBitmap(),
32+ cropRect.left.toInt(),
33+ cropRect.top.toInt(),
34+ cropRect.width.toInt(),
35+ cropRect.height.toInt()
36+ ).asImageBitmap()
37+
38+ val path = Path ().apply {
39+ val outline = shape.createOutline(cropRect.size, layoutDirection, density)
40+ addOutline(outline)
41+ }
42+
43+ Canvas (image = croppedBitmap).run {
44+ saveLayer(nativeCanvas.clipBounds.toComposeRect(), imagePaint)
45+ drawPath(path, paint)
46+ drawImage(image = croppedBitmap, topLeftOffset = Offset .Zero , imagePaint)
47+ onCropSuccess(croppedBitmap)
48+ restore()
49+ }
50+ }
51+
52+ fun crop (
53+ imageBitmap : ImageBitmap ,
54+ cropRect : Rect ,
55+ shape : Shape ,
56+ layoutDirection : LayoutDirection ,
57+ density : Density ,
58+ ): ImageBitmap {
59+
60+ val croppedBitmap = Bitmap .createBitmap(
61+ imageBitmap.asAndroidBitmap(),
62+ cropRect.left.toInt(),
63+ cropRect.top.toInt(),
64+ cropRect.width.toInt(),
65+ cropRect.height.toInt()
66+ ).asImageBitmap()
67+
68+ val path = Path ().apply {
69+ val outline = shape.createOutline(cropRect.size, layoutDirection, density)
70+ addOutline(outline)
71+ }
72+
73+ Canvas (image = croppedBitmap).run {
74+ saveLayer(nativeCanvas.clipBounds.toComposeRect(), imagePaint)
75+ drawPath(path, paint)
76+ drawImage(image = croppedBitmap, topLeftOffset = Offset .Zero , imagePaint)
77+ restore()
78+ }
79+
80+ return croppedBitmap
81+ }
82+
83+ }
0 commit comments