【问题标题】:Jetpack Compose draw on image with PainterJetpack Compose 使用 Painter 在图像上绘图
【发布时间】:2021-02-13 15:43:37
【问题描述】:

有了painter,可以用sn-p在ImageBitmap上绘图

   val imageBitmap: ImageBitmap = imageResource(id = R.drawable.landscape3)

    val customPainter = remember {
        object : Painter() {

            override val intrinsicSize: Size
                get() = Size(imageBitmap.width.toFloat(), imageBitmap.height.toFloat())

            override fun DrawScope.onDraw() {
                drawImage(imageBitmap)
                drawLine(
                    color = Color.Red,
                    start = Offset(0f, 0f),
                    end = Offset(imageBitmap.width.toFloat(), imageBitmap.height.toFloat()),
                    strokeWidth = 5f
                )
            }
        }
    }
    Image(painter = customPainter, contentDescription = null)

loadFontResource 已弃用。请改用 fontResource。 imageResource、loadImageResource、vectorResource 和 loadVectorResource 已弃用。请改用painterResource。 (I6b809)

alpha12 imageResource 已弃用。 painterdrawImage(imageBitmap) 绘制图像的函数没有替换或除以imageBitmap 作为参数之外的其他函数?

从 alpha12 开始 ImageBitmap 有什么意义,因为没有不推荐使用的函数来使用资源创建它,并且不存在从 Painter 获取 ImageBitmap 的函数。

【问题讨论】:

    标签: android android-jetpack-compose


    【解决方案1】:

    Compose UI 1.0.0-beta01开始

    imageResource 和 vectorResource 现在分别是 ImageBitmap 和 ImageVector 同伴的扩展函数。 load{Image,Vector,Font}资源函数已被删除。 (I89130)

    import androidx.compose.ui.res.imageResource
    // ...
    val imageBitmap: ImageBitmap = ImageBitmap.imageResource(R.drawable.landscape3)
    

    painterResource 在后台调用imageFromResource,所以我们也可以使用它:

      val imageBitmap: ImageBitmap = imageFromResource(
        LocalContext.current.resources,
        R.drawable.landscape3
      )
    

    【讨论】:

    • 是的,看起来这是用来创建 imageBitmap 的。
    • 从 beta01 开始,我猜它已经消失了。没有一种组合方式可以从资源或可绘制对象中获取 ImageBitmap 吗?
    • @Thracian 现在是扩展功能imageResource
    【解决方案2】:

    我使用这种方法来使用位图或 SVG

    Image(
        painterResource(id = R.drawable.video),
        contentDescription = "",
    )
    

    【讨论】:

      【解决方案3】:

      使用 Compose 1.0 及以上稳定版,您应该使用

      useResource("image.png") { loadImageBitmap(it) }

      这将返回一个ImageBitmap 对象。

      还有painterResource("image.png"),但这将返回一个Painter 对象。

      【讨论】:

        【解决方案4】:

        如果您需要从可绘制文件夹中设置 ImageVector,请使用:

        ImageVector.vectorResource(id = R.drawable.ic_example)
        

        ic_example 是从 svg 文件添加的矢量“.xml”文件

        【讨论】:

          猜你喜欢
          • 2020-04-09
          • 2022-09-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-01-21
          • 2021-04-15
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多