Kotlin:旋转ImageVector

krcsximq  于 2023-06-24  发布在  Kotlin
关注(0)|答案(3)|浏览(194)

我把一个material icon存储在一个数据类中,如下所示:

  1. import androidx.compose.ui.graphics.vector.ImageVector
  2. data class Item(
  3. val icon: ImageVector
  4. )
  5. val item = Item(Icons.Filled.Send)

稍后将该项目传递给一个可组合对象,在该对象中使用VectorPainter进行绘制
如何将ImageVector旋转90度?理想情况下,这将产生一个ImageVector,我仍然可以存储在数据类中。

js81xvg6

js81xvg61#

可以使用**rotate**修饰符:
类似于:

  1. Icon(
  2. Icons.Filled.ArrowDropDown,
  3. null,
  4. Modifier.rotate(90f)
  5. )

您可以添加一个条件来实现旋转和非旋转图标。
类似于:

  1. @Composable
  2. fun TrailingIcon(expanded: Boolean) {
  3. Icon(
  4. Icons.Filled.ArrowDropDown,
  5. null,
  6. Modifier.rotate(if (expanded) 90f else 0f)
  7. )
  8. }
展开查看全部
368yc8dk

368yc8dk2#

正如我从评论中得到的,你的Composable没有修饰符参数,这不是一个好的设计。每一个可组合的,即使你不会马上使用它,应该总是有一个修饰符参数。
https://chrisbanes.me/posts/always-provide-a-modifier/
在过去的一年左右,我看到了很多看起来很棒的可组合,但它们有一个致命的缺陷:它们不会暴露修饰符:修改器参数。
如果你不想读整篇文章,TL;这篇博客文章的DR是:
你写的任何发出布局的组合(即使是一个简单的Box),都应该有一个修饰符:修改器参数,然后在布局中使用该参数。
即使Composable没有修饰符参数,您也可以首先将旋转参数添加到Item数据类

  1. data class Item(
  2. val icon: ImageVector,
  3. val rotation: Float
  4. )

然后将没有Modifier参数的Composable Package 为

  1. Box(modifier = Modifier.rotate(item.rotation) {
  2. // Your Composable here
  3. }

imageVector.root.rotationrotation暴露为不可变参数,您不能更改也不能暴露IconVector的路径,如果这是原因,则可以通过矩阵进行旋转。

  1. public val Icons.Filled.Send: ImageVector
  2. get() {
  3. if (_send != null) {
  4. return _send!!
  5. }
  6. _send = materialIcon(name = "Filled.Send") {
  7. materialPath {
  8. moveTo(2.01f, 21.0f)
  9. lineTo(23.0f, 12.0f)
  10. lineTo(2.01f, 3.0f)
  11. lineTo(2.0f, 10.0f)
  12. lineToRelative(15.0f, 2.0f)
  13. lineToRelative(-15.0f, 2.0f)
  14. close()
  15. }
  16. }
  17. return _send!!
  18. }
  19. private var _send: ImageVector? = null
展开查看全部
fhg3lkii

fhg3lkii3#

您可以使用“ImageVector”类提供的“rotate”方法。例如:

  1. data class Item(
  2. val icon: ImageVector
  3. )
  4. val item = Item(Icons.Filled.Send.rotate(90f))

相关问题