虽然2023年4月Graphics-Shapes库就已经被发布^[1], 但是相关的资料仍寥寥无几, 近日浏览 Fun with shapes in Compose ^[2]这篇文章的时候, 才发觉已经可以用shape来实现很多的功能了.
Shape是什么?
简单来说, 借助Compose, 您可以创建由多边形组成的形状^[3]. 这么说可能不太直观, 那么我们可以下Shape都可以创建出什么样的内容:
虽然不能直接处理任意两个形状之间的变换问题,(当然, 这个问题是设计时的问题.) 但是对于多边形结构之间的变化来说, 却能帮助我们简化大量的操作.
Shape能做到什么?
正如前文中所说, Shape可以帮助我们完成多边形之间的变化.
我们先看一下, 首先展示的的6种预设的情况.
然后是作为clip裁剪显示图片的效果, 这里添加了缩放和选择的效果, 如果有需要的话可以根据实际情况添加需要的效果.
下面就是对开始和结束多边形的设置了. 需要注意的是, 部分预设的情况是可以自定义形状的.^[4]
下面我们依次显示不同预设效果都可以如何进行条件.
需要注意的是, 在实际使用的过程中, 如果直接在DrawScope 中使用的话, radius , width , height 需要设置为实际View的大小, 而如果将其构建出来提供给类似clip中使用的话, radius , width , height则需要设置为比例的情况.^[5]
RoundedPolygonType.Common
kotlin
fun RoundedPolygon(
@IntRange(from = 3) numVertices: Int,
radius: Float = 1f,
centerX: Float = 0f,
centerY: Float = 0f,
rounding: CornerRounding = CornerRounding.Unrounded,
perVertexRounding: List<CornerRounding>? = null
) = RoundedPolygon(
...
)
RoundedPolygonType.CIRCLE
kotlin
fun RoundedPolygon.Companion.circle(
@IntRange(from = 3) numVertices: Int = 8,
radius: Float = 1f,
centerX: Float = 0f,
centerY: Float = 0f
): RoundedPolygon {
...
}
RoundedPolygonType.PILL
kotlin
fun RoundedPolygon.Companion.pill(
width: Float = 2f,
height: Float = 1f,
smoothing: Float = 0f,
centerX: Float = 0f,
centerY: Float = 0f,
): RoundedPolygon {
...
}
RoundedPolygonType.PILL_STAR
kotlin
fun RoundedPolygon.Companion.pillStar(
width: Float = 2f,
height: Float = 1f,
numVerticesPerRadius: Int = 8,
@FloatRange(
from = 0.0, fromInclusive = false, to = 1.0, toInclusive = false
) innerRadiusRatio: Float = .5f,
rounding: CornerRounding = CornerRounding.Unrounded,
innerRounding: CornerRounding? = null,
perVertexRounding: List<CornerRounding>? = null,
@FloatRange(from = 0.0, to = 1.0) vertexSpacing: Float = 0.5f,
centerX: Float = 0f,
centerY: Float = 0f
): RoundedPolygon {
...
}
RoundedPolygonType.RECTANGLE
kotlin
fun RoundedPolygon.Companion.rectangle(
width: Float = 2f,
height: Float = 2f,
rounding: CornerRounding = CornerRounding.Unrounded,
perVertexRounding: List<CornerRounding>? = null,
centerX: Float = 0f,
centerY: Float = 0f
): RoundedPolygon {
...
}
RoundedPolygonType.STAR
kotlin
fun RoundedPolygon.Companion.star(
numVerticesPerRadius: Int,
radius: Float = 1f,
innerRadius: Float = .5f,
rounding: CornerRounding = CornerRounding.Unrounded,
innerRounding: CornerRounding? = null,
perVertexRounding: List<CornerRounding>? = null,
centerX: Float = 0f,
centerY: Float = 0f
): RoundedPolygon {
...
}
Final
Demo: https://github.com/clwater/AndroidComposeCanvas
[1]:developer.android.com/jetpack/and...
[3]:developer.android.com/jetpack/com...
[4]:developer.android.com/jetpack/com...
[5]: 当前使用的版本为1.0.0-alpha05, 不保证后续此特性继续保留.