图形修饰符
Modifier.drawWithContent
作用域:ContentDrawScope,使用drawContent()绘制可组合内容。
DrawScope文章:https://wjhblog.cn/archives/androidx.compose.ui-ui-graphics-android#drawscope
Modifier.drawWithContent {
drawContent() //绘制可组合项内容
drawRect()
//...
}
Modifier.drawBehind
作用域:DrawScope,没有drawContent方法。
DrawScope文章:https://wjhblog.cn/archives/androidx.compose.ui-ui-graphics-android#drawscope
Modifier.drawWithCache
作用域:CacheDrawScope
Modifier.graphicsLayer
rotation
var rotationX by remember { mutableFloatStateOf(0f) }
var rotationY by remember { mutableFloatStateOf(0f) }
var rotationZ by remember { mutableFloatStateOf(0f) }
Column(modifier = Modifier.windowInsetsPadding(WindowInsets.systemBars).background(color = CustomTheme.colors.bgColor).graphicsLayer()) {
Button(onClick = {}, modifier = Modifier.graphicsLayer(rotationX = rotationX, rotationY = rotationY, rotationZ = rotationZ)) {
Text("查看效果")
}
Button(onClick = {
rotationX+=10
}) {
Text("X+10")
}
Button(onClick = {
rotationY+=10
}) {
Text("Y+10")
}
Button(onClick = {
rotationZ+=10
}) {
Text("Z+10")
}
}
其它属性
Modifier.graphicsLayer(
translationX = 10f, //左右平移
translationY = 10f, //上下平移
scaleX = 1f, // 横向收放,1f表示原始100%大小
scaleY = 1f, // 纵向收放,1f表示原始100%大小
alpha = 1f, //透明度,取值:0~1
//transformOrigin:动画原点,缩放、旋转等动画受它的影响,例如设为0f,0f,那么缩放时将会向左上角收缩;0f,1f表示左下角;1f,0f表示右上角等。通常取值:0~1
transformOrigin = TransformOrigin(.5f,.5f),
shadowElevation = 8f, //显示阴影
shape = RoundedCornerShape(20.dp), //形状
clip = true, //阴影会贴合形状,如果为false则阴影是直角
//控制3D透视效果。较小的值会增强透视效果(类似广角镜头),较大的值会减弱透视(类似长焦镜头)。默认为8f(小于0时会导致崩溃)
//仅当视图绕 X/Y 轴旋转时才会显现这个参数的效果。类似CSS中的perspective属性
cameraDistance = 8f,
)
rememberGraphicsLayer:GraphicsLayer
将一系列绘制结果存储在GraphicsLayer实例中,在其它地方复用。
记录Composable元素绘制
val graphicsLayer = rememberGraphicsLayer()
Column {
Column(modifier = Modifier
.windowInsetsPadding(WindowInsets.systemBars)
.background(color = CustomTheme.colors.bgColor).drawWithContent {
graphicsLayer.record {
this@drawWithContent.drawContent() //调用上一层(drawWithContent)作用域,先将Column的可组合项绘制在第一层
drawRect(color = Color.Red, size = Size(100f,100f)) //再绘制一个矩形在第二层
}
drawLayer(graphicsLayer) //将record中的内容绘制在这个Column中
})
{
Button(onClick = {
scale -= 0.1f
}) {
Text("scale-0.1")
}
Button(onClick = {
scale += 0.1f
}) {
Text("scale+0.1")
}
}
Column(modifier = Modifier
.windowInsetsPadding(WindowInsets.systemBars).height(300.dp)
.background(color = CustomTheme.colors.bgColor).drawWithContent {
drawLayer(graphicsLayer) //将graphicsLayer中存储的图像绘制在这个元素中
drawContent() //将Text("Column2")元素绘制在graphicsLayer之上
})
{
Text(text = "Column2")
}
}
记录图像绘制
val graphicsLayer = rememberGraphicsLayer()
graphicsLayer.record(LocalDensity.current,LayoutDirection.Ltr, IntSize(100,100)) {
rotate(45f) {
drawRect(color = Color.Red, size = Size(100f,100f))
}
}