@@ -44,6 +44,7 @@ import androidx.compose.ui.Alignment
44
44
import androidx.compose.ui.Modifier
45
45
import androidx.compose.ui.draw.clip
46
46
import androidx.compose.ui.draw.drawWithCache
47
+ import androidx.compose.ui.geometry.Rect
47
48
import androidx.compose.ui.geometry.Size
48
49
import androidx.compose.ui.graphics.Color
49
50
import androidx.compose.ui.graphics.Matrix
@@ -66,9 +67,11 @@ import androidx.graphics.shapes.Cubic
66
67
import androidx.graphics.shapes.Morph
67
68
import androidx.graphics.shapes.RoundedPolygon
68
69
import androidx.graphics.shapes.star
70
+ import androidx.graphics.shapes.toPath
69
71
import com.example.compose.snippets.R
70
72
import kotlin.math.PI
71
73
import kotlin.math.cos
74
+ import kotlin.math.max
72
75
import kotlin.math.sin
73
76
74
77
@Preview
@@ -348,22 +351,49 @@ private fun MorphOnClick() {
348
351
}
349
352
350
353
// [START android_compose_shapes_polygon_compose_shape]
354
+ @JvmOverloads
355
+ fun RoundedPolygon.toPath (path : Path = Path ()): Path {
356
+ pathFromCubics(path, cubics)
357
+ return path
358
+ }
359
+ private fun pathFromCubics (
360
+ path : Path ,
361
+ cubics : List <Cubic >
362
+ ) {
363
+ var first = true
364
+ path.rewind()
365
+ for (element in cubics) {
366
+ if (first) {
367
+ path.moveTo(element.anchor0X, element.anchor0Y)
368
+ first = false
369
+ }
370
+ path.cubicTo(
371
+ element.control0X, element.control0Y, element.control1X, element.control1Y,
372
+ element.anchor1X, element.anchor1Y
373
+ )
374
+ }
375
+ path.close()
376
+ }
377
+ fun RoundedPolygon.getBounds () = calculateBounds().let { Rect (it[0 ], it[1 ], it[2 ], it[3 ]) }
351
378
class RoundedPolygonShape (
352
- private val polygon : RoundedPolygon
379
+ private val polygon : RoundedPolygon ,
380
+ private var matrix : Matrix = Matrix ()
353
381
) : Shape {
354
- private val matrix = Matrix ()
382
+ private val path = Path ()
355
383
override fun createOutline (
356
384
size : Size ,
357
385
layoutDirection : LayoutDirection ,
358
386
density : Density
359
387
): Outline {
360
- val path = polygon.cubics.toPath()
361
- // below assumes that you haven't changed the default radius of 1f, nor the centerX and centerY of 0f
362
- // By default this stretches the path to the size of the container, if you don't want stretching, use the same size.width for both x and y.
363
- matrix.scale(size.width / 2f , size.height / 2f )
364
- matrix.translate(1f , 1f )
365
- path.transform(matrix)
388
+ path.rewind()
389
+ polygon.toPath(path)
390
+ matrix.reset()
391
+ val bounds = polygon.getBounds()
392
+ val maxDimension = max(bounds.width, bounds.height)
393
+ matrix.scale(size.width / maxDimension, size.height / maxDimension)
394
+ matrix.translate(- bounds.left, - bounds.top)
366
395
396
+ path.transform(matrix)
367
397
return Outline .Generic (path)
368
398
}
369
399
}
0 commit comments