-
Notifications
You must be signed in to change notification settings - Fork 136
/
ShapesSnippets.kt
601 lines (568 loc) · 19.6 KB
/
ShapesSnippets.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
/*
* Copyright 2023 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.compose.snippets.graphics
import android.graphics.PointF
import androidx.compose.animation.core.LinearEasing
import androidx.compose.animation.core.RepeatMode
import androidx.compose.animation.core.Spring
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.rememberInfiniteTransition
import androidx.compose.animation.core.spring
import androidx.compose.animation.core.tween
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.collectIsPressedAsState
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.drawWithCache
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Matrix
import androidx.compose.ui.graphics.Outline
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.graphics.asComposePath
import androidx.compose.ui.graphics.drawscope.scale
import androidx.compose.ui.graphics.drawscope.translate
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.Density
import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.unit.dp
import androidx.core.graphics.plus
import androidx.core.graphics.times
import androidx.graphics.shapes.CornerRounding
import androidx.graphics.shapes.Cubic
import androidx.graphics.shapes.Morph
import androidx.graphics.shapes.RoundedPolygon
import androidx.graphics.shapes.star
import androidx.graphics.shapes.toPath
import com.example.compose.snippets.R
import kotlin.math.PI
import kotlin.math.cos
import kotlin.math.max
import kotlin.math.sin
@Preview
@Composable
fun BasicShapeCanvas() {
// [START android_compose_graphics_basic_polygon]
Box(
modifier = Modifier
.drawWithCache {
val roundedPolygon = RoundedPolygon(
numVertices = 6,
radius = size.minDimension / 2,
centerX = size.width / 2,
centerY = size.height / 2
)
val roundedPolygonPath = roundedPolygon.toPath().asComposePath()
onDrawBehind {
drawPath(roundedPolygonPath, color = Color.Blue)
}
}
.fillMaxSize()
)
// [END android_compose_graphics_basic_polygon]
}
@Preview
@Composable
private fun RoundedShapeExample() {
// [START android_compose_graphics_polygon_rounding]
Box(
modifier = Modifier
.drawWithCache {
val roundedPolygon = RoundedPolygon(
numVertices = 3,
radius = size.minDimension / 2,
centerX = size.width / 2,
centerY = size.height / 2,
rounding = CornerRounding(
size.minDimension / 10f,
smoothing = 1f
)
)
val roundedPolygonPath = roundedPolygon.toPath().asComposePath()
onDrawBehind {
drawPath(roundedPolygonPath, color = Color.Black)
}
}
.fillMaxSize()
)
// [END android_compose_graphics_polygon_rounding]
}
@Preview
@Composable
private fun RoundedShapeSmoothnessExample() {
// [START android_compose_graphics_polygon_rounding_smooth]
Box(
modifier = Modifier
.drawWithCache {
val roundedPolygon = RoundedPolygon(
numVertices = 3,
radius = size.minDimension / 2,
centerX = size.width / 2,
centerY = size.height / 2,
rounding = CornerRounding(
size.minDimension / 10f,
smoothing = 0.1f
)
)
val roundedPolygonPath = roundedPolygon.toPath().asComposePath()
onDrawBehind {
drawPath(roundedPolygonPath, color = Color.Black)
}
}
.size(100.dp)
)
// [END android_compose_graphics_polygon_rounding_smooth]
}
@Preview
@Composable
private fun MorphExample() {
// [START android_compose_graphics_polygon_morph]
Box(
modifier = Modifier
.drawWithCache {
val triangle = RoundedPolygon(
numVertices = 3,
radius = size.minDimension / 2f,
centerX = size.width / 2f,
centerY = size.height / 2f,
rounding = CornerRounding(
size.minDimension / 10f,
smoothing = 0.1f
)
)
val square = RoundedPolygon(
numVertices = 4,
radius = size.minDimension / 2f,
centerX = size.width / 2f,
centerY = size.height / 2f
)
val morph = Morph(start = triangle, end = square)
val morphPath = morph
.toPath(progress = 0.5f).asComposePath()
onDrawBehind {
drawPath(morphPath, color = Color.Black)
}
}
.fillMaxSize()
)
// [END android_compose_graphics_polygon_morph]
}
@Preview
@Composable
private fun MorphExampleAnimation() {
// [START android_compose_graphics_polygon_morph_animation]
val infiniteAnimation = rememberInfiniteTransition(label = "infinite animation")
val morphProgress = infiniteAnimation.animateFloat(
initialValue = 0f,
targetValue = 1f,
animationSpec = infiniteRepeatable(
tween(500),
repeatMode = RepeatMode.Reverse
),
label = "morph"
)
Box(
modifier = Modifier
.drawWithCache {
val triangle = RoundedPolygon(
numVertices = 3,
radius = size.minDimension / 2f,
centerX = size.width / 2f,
centerY = size.height / 2f,
rounding = CornerRounding(
size.minDimension / 10f,
smoothing = 0.1f
)
)
val square = RoundedPolygon(
numVertices = 4,
radius = size.minDimension / 2f,
centerX = size.width / 2f,
centerY = size.height / 2f
)
val morph = Morph(start = triangle, end = square)
val morphPath = morph
.toPath(progress = morphProgress.value)
.asComposePath()
onDrawBehind {
drawPath(morphPath, color = Color.Black)
}
}
.fillMaxSize()
)
// [END android_compose_graphics_polygon_morph_animation]
}
// [START android_compose_morph_to_path]
/**
* Transforms the morph at a given progress into a [Path].
* It can optionally be scaled, using the origin (0,0) as pivot point.
*/
fun Morph.toComposePath(progress: Float, scale: Float = 1f, path: Path = Path()): Path {
var first = true
path.rewind()
forEachCubic(progress) { bezier ->
if (first) {
path.moveTo(bezier.anchor0X * scale, bezier.anchor0Y * scale)
first = false
}
path.cubicTo(
bezier.control0X * scale, bezier.control0Y * scale,
bezier.control1X * scale, bezier.control1Y * scale,
bezier.anchor1X * scale, bezier.anchor1Y * scale
)
}
path.close()
return path
}
// [END android_compose_morph_to_path]
/**
* Function used to create a Path from a list of Cubics.
*/
// [START android_compose_list_cubics_to_path]
fun List<Cubic>.toPath(path: Path = Path(), scale: Float = 1f): Path {
path.rewind()
firstOrNull()?.let { first ->
path.moveTo(first.anchor0X * scale, first.anchor0Y * scale)
}
for (bezier in this) {
path.cubicTo(
bezier.control0X * scale, bezier.control0Y * scale,
bezier.control1X * scale, bezier.control1Y * scale,
bezier.anchor1X * scale, bezier.anchor1Y * scale
)
}
path.close()
return path
}
// [END android_compose_list_cubics_to_path]
// [START android_compose_morph_clip_shape]
class MorphPolygonShape(
private val morph: Morph,
private val percentage: Float
) : Shape {
private val matrix = Matrix()
override fun createOutline(
size: Size,
layoutDirection: LayoutDirection,
density: Density
): Outline {
// Below assumes that you haven't changed the default radius of 1f, nor the centerX and centerY of 0f
// 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.
matrix.scale(size.width / 2f, size.height / 2f)
matrix.translate(1f, 1f)
val path = morph.toPath(progress = percentage).asComposePath()
path.transform(matrix)
return Outline.Generic(path)
}
}
// [END android_compose_morph_clip_shape]
@Preview
@Composable
private fun MorphOnClick() {
// [START android_compose_graphics_morph_on_click]
val shapeA = remember {
RoundedPolygon(
6,
rounding = CornerRounding(0.2f)
)
}
val shapeB = remember {
RoundedPolygon.star(
6,
rounding = CornerRounding(0.1f)
)
}
val morph = remember {
Morph(shapeA, shapeB)
}
val interactionSource = remember {
MutableInteractionSource()
}
val isPressed by interactionSource.collectIsPressedAsState()
val animatedProgress = animateFloatAsState(
targetValue = if (isPressed) 1f else 0f,
label = "progress",
animationSpec = spring(dampingRatio = 0.4f, stiffness = Spring.StiffnessMedium)
)
Box(
modifier = Modifier
.size(200.dp)
.padding(8.dp)
.clip(MorphPolygonShape(morph, animatedProgress.value))
.background(Color(0xFF80DEEA))
.size(200.dp)
.clickable(interactionSource = interactionSource, indication = null) {
}
) {
Text("Hello", modifier = Modifier.align(Alignment.Center))
}
// [END android_compose_graphics_morph_on_click]
}
// [START android_compose_shapes_polygon_compose_shape]
fun RoundedPolygon.getBounds() = calculateBounds().let { Rect(it[0], it[1], it[2], it[3]) }
class RoundedPolygonShape(
private val polygon: RoundedPolygon,
private var matrix: Matrix = Matrix()
) : Shape {
private var path = Path()
override fun createOutline(
size: Size,
layoutDirection: LayoutDirection,
density: Density
): Outline {
path.rewind()
path = polygon.toPath().asComposePath()
matrix.reset()
val bounds = polygon.getBounds()
val maxDimension = max(bounds.width, bounds.height)
matrix.scale(size.width / maxDimension, size.height / maxDimension)
matrix.translate(-bounds.left, -bounds.top)
path.transform(matrix)
return Outline.Generic(path)
}
}
// [END android_compose_shapes_polygon_compose_shape]
@Preview
@Composable
fun ApplyPolygonAsClipBasic() {
// [START android_compose_shapes_apply_as_clip]
val hexagon = remember {
RoundedPolygon(
6,
rounding = CornerRounding(0.2f)
)
}
val clip = remember(hexagon) {
RoundedPolygonShape(polygon = hexagon)
}
Box(
modifier = Modifier
.clip(clip)
.background(MaterialTheme.colorScheme.secondary)
.size(200.dp)
) {
Text(
"Hello Compose",
color = MaterialTheme.colorScheme.onSecondary,
modifier = Modifier.align(Alignment.Center)
)
}
// [END android_compose_shapes_apply_as_clip]
}
@Preview
@Composable
fun ApplyPolygonAsClipImage() {
// [START android_compose_shapes_apply_as_clip_advanced]
val hexagon = remember {
RoundedPolygon(
6,
rounding = CornerRounding(0.2f)
)
}
val clip = remember(hexagon) {
RoundedPolygonShape(polygon = hexagon)
}
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center
) {
Image(
painter = painterResource(id = R.drawable.dog),
contentDescription = "Dog",
contentScale = ContentScale.Crop,
modifier = Modifier
.graphicsLayer {
this.shadowElevation = 6.dp.toPx()
this.shape = clip
this.clip = true
this.ambientShadowColor = Color.Black
this.spotShadowColor = Color.Black
}
.size(200.dp)
)
}
// [END android_compose_shapes_apply_as_clip_advanced]
}
// [START android_compose_shapes_custom_rotating_morph_shape]
class CustomRotatingMorphShape(
private val morph: Morph,
private val percentage: Float,
private val rotation: Float
) : Shape {
private val matrix = Matrix()
override fun createOutline(
size: Size,
layoutDirection: LayoutDirection,
density: Density
): Outline {
// Below assumes that you haven't changed the default radius of 1f, nor the centerX and centerY of 0f
// 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.
matrix.scale(size.width / 2f, size.height / 2f)
matrix.translate(1f, 1f)
matrix.rotateZ(rotation)
val path = morph.toPath(progress = percentage).asComposePath()
path.transform(matrix)
return Outline.Generic(path)
}
}
@Preview
@Composable
private fun RotatingScallopedProfilePic() {
val shapeA = remember {
RoundedPolygon(
12,
rounding = CornerRounding(0.2f)
)
}
val shapeB = remember {
RoundedPolygon.star(
12,
rounding = CornerRounding(0.2f)
)
}
val morph = remember {
Morph(shapeA, shapeB)
}
val infiniteTransition = rememberInfiniteTransition("infinite outline movement")
val animatedProgress = infiniteTransition.animateFloat(
initialValue = 0f,
targetValue = 1f,
animationSpec = infiniteRepeatable(
tween(2000, easing = LinearEasing),
repeatMode = RepeatMode.Reverse
),
label = "animatedMorphProgress"
)
val animatedRotation = infiniteTransition.animateFloat(
initialValue = 0f,
targetValue = 360f,
animationSpec = infiniteRepeatable(
tween(6000, easing = LinearEasing),
repeatMode = RepeatMode.Reverse
),
label = "animatedMorphProgress"
)
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center
) {
Image(
painter = painterResource(id = R.drawable.dog),
contentDescription = "Dog",
contentScale = ContentScale.Crop,
modifier = Modifier
.clip(
CustomRotatingMorphShape(
morph,
animatedProgress.value,
animatedRotation.value
)
)
.size(200.dp)
)
}
}
// [END android_compose_shapes_custom_rotating_morph_shape]
@Preview
@Composable
private fun CartesianPoints() {
// [START android_compose_shapes_custom_vertices]
val vertices = remember {
val radius = 1f
val radiusSides = 0.8f
val innerRadius = .1f
floatArrayOf(
radialToCartesian(radiusSides, 0f.toRadians()).x,
radialToCartesian(radiusSides, 0f.toRadians()).y,
radialToCartesian(radius, 90f.toRadians()).x,
radialToCartesian(radius, 90f.toRadians()).y,
radialToCartesian(radiusSides, 180f.toRadians()).x,
radialToCartesian(radiusSides, 180f.toRadians()).y,
radialToCartesian(radius, 250f.toRadians()).x,
radialToCartesian(radius, 250f.toRadians()).y,
radialToCartesian(innerRadius, 270f.toRadians()).x,
radialToCartesian(innerRadius, 270f.toRadians()).y,
radialToCartesian(radius, 290f.toRadians()).x,
radialToCartesian(radius, 290f.toRadians()).y,
)
}
// [END android_compose_shapes_custom_vertices]
// [START android_compose_shapes_custom_vertices_draw]
val rounding = remember {
val roundingNormal = 0.6f
val roundingNone = 0f
listOf(
CornerRounding(roundingNormal),
CornerRounding(roundingNone),
CornerRounding(roundingNormal),
CornerRounding(roundingNormal),
CornerRounding(roundingNone),
CornerRounding(roundingNormal),
)
}
val polygon = remember(vertices, rounding) {
RoundedPolygon(
vertices = vertices,
perVertexRounding = rounding
)
}
Box(
modifier = Modifier
.drawWithCache {
val roundedPolygonPath = polygon.toPath().asComposePath()
onDrawBehind {
scale(size.width * 0.5f, size.width * 0.5f) {
translate(size.width * 0.5f, size.height * 0.5f) {
drawPath(roundedPolygonPath, color = Color(0xFFF15087))
}
}
}
}
.size(400.dp)
)
// [END android_compose_shapes_custom_vertices_draw]
}
// [START android_compose_shapes_radial_to_cartesian]
internal fun Float.toRadians() = this * PI.toFloat() / 180f
internal val PointZero = PointF(0f, 0f)
internal fun radialToCartesian(
radius: Float,
angleRadians: Float,
center: PointF = PointZero
) = directionVectorPointF(angleRadians) * radius + center
internal fun directionVectorPointF(angleRadians: Float) =
PointF(cos(angleRadians), sin(angleRadians))
// [END android_compose_shapes_radial_to_cartesian]