Compose 中的形狀

您可以使用 Compose 建立由多邊形組成的形狀。例如,您可以製作下列形狀:

繪圖區域中央的藍色六邊形
圖 1. 使用 graphics-shapes 程式庫可製作的不同形狀範例

如要在 Compose 中建立自訂圓角多邊形,請將 graphics-shapes 依附元件新增至 app/build.gradle:

implementation "androidx.graphics:graphics-shapes:1.0.1"

這個程式庫可讓您建立由多邊形組成的形狀。多邊形只有直邊和尖角,但這些形狀可以選擇圓角。可輕鬆在兩種不同形狀之間變形。任意形狀之間的變形難度較高,通常是設計階段的問題。不過,這個程式庫可讓您在這些具有類似多邊形結構的形狀之間變形,輕鬆完成這項操作。

建立多邊形

下列程式碼片段會在繪圖區域中央,建立一個有 6 個點的基本多邊形:

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()
)

繪圖區域中央的藍色六邊形
圖 2. 繪圖區中央有一個藍色六邊形。

在這個範例中,程式庫會建立 RoundedPolygon,其中包含代表所要求形狀的幾何圖形。如要在 Compose 應用程式中繪製該形狀,您必須從中取得 Path 物件,將形狀轉換為 Compose 知道如何繪製的形式。

將多邊形的角修圓

如要將多邊形的角設為圓角,請使用 CornerRounding 參數。這會採用兩個參數:radius 和 smoothing。每個圓角由 1 到 3 條立方曲線組成,中心為圓弧形狀,兩側 (「側翼」) 曲線則從形狀邊緣過渡到中心曲線。

Radius

radius 是用於圓角頂點的圓形半徑。

舉例來說,以下圓角三角形的製作方式如下:

圓角三角形
圖 3. 圓角三角形。
圓角半徑 r 決定圓角的圓形圓角大小
圖 4. 圓角半徑 r 會決定圓角的圓形圓角大小。

平滑化

平滑度是決定從圓角部分到邊緣所需時間的因素。平滑係數為 0 (未平滑,CornerRounding 的預設值) 會產生純圓角。非零平滑係數 (最大值為 1.0) 會使角落由三個獨立曲線圓角。

平滑係數為 0 (未平滑) 時,會產生一條立方曲線,沿著角落周圍的圓形,並採用指定的圓角半徑,如前例所示
圖 5. 平滑係數為 0 (未平滑) 時,會產生單一立方曲線,沿著角落周圍的圓形,並採用指定的圓角半徑,如前例所示。
非零平滑係數會產生三條立方曲線,使頂點變圓:內圓曲線 (如前所述),以及兩條側翼曲線,在內曲線和多邊形邊緣之間轉換。
圖 6. 非零平滑係數會產生三條立方曲線,使頂點變圓:內圓曲線 (如前所述) 加上兩條側翼曲線,在內曲線和多邊形邊緣之間轉換。

舉例來說,以下程式碼片段說明將平滑度設為 0 和 1 的細微差異:

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)
)

兩個黑色三角形,顯示平滑參數的差異。
圖 7. 兩個黑色三角形,顯示平滑參數的差異。

大小和位置

根據預設,系統會以中心點 (0, 0) 為圓心,建立半徑為 1 的形狀。這個半徑代表中心點與多邊形外部頂點之間的距離,而多邊形是形狀的基礎。請注意,圓角會比圓角頂點更接近中心,因此圓角會導致形狀變小。如要調整多邊形大小,請調整 radius 值。如要調整位置,請變更多邊形的 centerX 或 centerY。或者,您也可以使用標準 DrawScope 轉換函式 (例如 DrawScope#translate()) 轉換物件,藉此變更物件的大小、位置和旋轉角度。

變形

Morph 物件是一種新形狀,代表兩個多邊形之間的動畫。如要在兩個形狀之間變形,請建立兩個 RoundedPolygons 和一個採用這兩個形狀的 Morph 物件。如要計算起始和結束形狀之間的形狀,請提供介於 0 和 1 之間的 progress 值,決定起始 (0) 和結束 (1) 形狀之間的形狀:

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()
)

在上述範例中,進度剛好介於兩個形狀 (圓角三角形和正方形) 之間,產生以下結果:

介於圓角三角形和正方形之間
圖 8. 50% 介於圓角三角形和正方形之間。

在大多數情況下,變形是動畫的一部分,而不只是靜態算繪。如要在這兩者之間建立動畫,可以使用 Compose 中的標準 Animation API,隨著時間變更進度值。舉例來說,您可以無限次播放這兩種形狀之間的變形動畫,如下所示:

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()
)

在正方形和圓角三角形之間無限變形
圖 9. 在正方形和圓角三角形之間無限變形。

使用多邊形裁剪

在 Compose 中,通常會使用 clip 修飾符來變更可組合項的算繪方式,並利用在裁剪區域周圍繪製的陰影:

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)
    }
}

接著,您可以將多邊形當做剪輯,如以下程式碼片段所示:

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)
    )
}

這會導致以下結果:

六邊形,中間有「hello compose」文字。
圖 10. 六邊形,中間有「Hello Compose」文字。

這與先前轉譯的內容可能沒有太大差異,但可讓您運用 Compose 中的其他功能。舉例來說,這項技術可用於裁剪圖片,並在裁剪區域周圍套用陰影:

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)

    )
}

六邊形中的狗,邊緣套用陰影
圖 11. 自訂形狀已套用為剪輯。

點選時變形按鈕

您可以使用 graphics-shape 程式庫建立按鈕,在按下時變換兩種形狀。首先,建立擴充 Shape 的 MorphPolygonShape,並縮放及轉譯,使其符合適當大小。請注意,傳入進度後,形狀就能以動畫形式呈現:

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)
    }
}

如要使用這個變形形狀,請建立兩個多邊形:shapeA 和 shapeB。建立並記住 Morph。接著,將變形套用至按鈕做為剪輯外框,並使用按下時的 interactionSource 做為動畫的驅動力:

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))
}

輕觸方塊時,就會產生下列動畫:

在兩個圖形之間點按,即可套用變形效果
圖 12. 在兩個形狀之間點按,即可套用變形效果。

無限次播放形狀變形動畫

如要讓變形圖案無限動畫,請使用 rememberInfiniteTransition。以下範例顯示個人資料相片會隨著時間不斷變更形狀 (和旋轉)。這個方法會對上述 MorphPolygonShape 進行小幅調整:

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)
        )
    }
}

這段程式碼會產生以下有趣結果:

心形
圖 13. 個人資料相片,由旋轉的扇貝形狀裁剪。

自訂多邊形

如果正多邊形建立的形狀不符合您的用途,您可以使用頂點清單建立更自訂的形狀。舉例來說,您可能想建立像這樣的心形:

心形
圖 14. 心形。

您可以使用 RoundedPolygon 超載,指定這個形狀的個別頂點,該超載會採用 x、y 座標的浮點陣列。

如要拆解愛心多邊形,請注意,使用極座標系統指定點,會比使用笛卡兒 (x,y) 座標系統更容易,其中 0° 從右側開始,並以順時針方向進行,270° 位於 12 點鐘位置:

心形
圖 15。有座標的心形。

現在,您可以透過指定角度 (𝜭) 和每個點與中心的半徑,以更簡單的方式定義形狀:

心形
圖 16。有座標的心形,未四捨五入。

現在可以建立頂點,並傳遞至 RoundedPolygon 函式:

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,
    )
}

您必須使用以下 radialToCartesian 函式,將頂點轉譯為笛卡兒座標:

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))

上述程式碼會提供愛心形狀的原始頂點,但您需要將特定角落圓角化,才能取得所選的愛心形狀。90° 和 270° 的角落沒有圓角,但其他角落有。如要為個別角落自訂圓角,請使用 perVertexRounding 參數:

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)
)

這會產生粉色愛心:

心形
圖 17. 心形結果。

如果上述形狀不符合您的用途,請考慮使用 Path 類別繪製自訂形狀,或從磁碟載入 ImageVector 檔案。graphics-shapes 程式庫不適用於任意形狀,而是專門用於簡化圓角多邊形的建立,以及多邊形之間的變形動畫。

其他資源

如需更多資訊和範例,請參閱下列資源: