android compose Canvas 绘制图案居中展示

在 Jetpack Compose 中,你可以使用 Canvas 组件绘制内容,并可以将 Bitmap 绘制在 Canvas 上。要将一个 Bitmap 相对于 Canvas 居中,你可以计算绘制位置,使其位于 Canvas 的中心。

以下是一个示例,演示如何将 Drawable 转换为 Bitmap,并在 Canvas 中居中绘制该 Bitmap

Kotlin 复制代码
import android.graphics.Bitmap
import android.graphics.drawable.BitmapDrawable
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.drawscope.drawIntoCanvas
import androidx.compose.ui.graphics.nativeCanvas

@Composable
fun drawableToBitmap(drawableResId: Int): Bitmap {
    val context = LocalContext.current
    val drawable = context.getDrawable(drawableResId)
    if (drawable is BitmapDrawable) {
        return drawable.bitmap
    } else {
        throw IllegalArgumentException("Resource is not a BitmapDrawable")
    }
}

@Composable
fun CenteredBitmapCanvas(drawableResId: Int) {
    val bitmap = drawableToBitmap(drawableResId).asImageBitmap()

    Canvas(modifier = Modifier.fillMaxSize()) {
        val canvasWidth = size.width
        val canvasHeight = size.height
        val bitmapWidth = bitmap.width.toFloat()
        val bitmapHeight = bitmap.height.toFloat()

        val xOffset = (canvasWidth - bitmapWidth) / 2
        val yOffset = (canvasHeight - bitmapHeight) / 2

        drawImage(
                image = bitmap, topLeft = Offset(xOffset, yOffset)
            )
    }
}

在这个示例中:

  1. drawableToBitmap 函数将 Drawable 资源转换为 Bitmap
  2. CenteredBitmapCanvas 组件使用 Canvas 绘制 Bitmap
  3. Canvas 中,通过计算 xOffsetyOffset,将 Bitmap 居中绘制。

你可以在 Composable 函数中调用 CenteredBitmapCanvas,并传入你想要绘制的 Drawable 资源 ID:

Kotlin 复制代码
@Composable
fun MyScreen() {
    CenteredBitmapCanvas(drawableResId = R.drawable.your_drawable)
}

这样,指定的 Drawable 将被转换为 Bitmap 并在 Canvas 中居中绘制。

---- 文章由 ChatGPT 生成

相关推荐
FrankYoou36 分钟前
Jenkins 与 GitLab CI/CD 的核心对比
java·docker
麦兜*1 小时前
Spring Boot启动优化7板斧(延迟初始化、组件扫描精准打击、JVM参数调优):砍掉70%启动时间的魔鬼实践
java·jvm·spring boot·后端·spring·spring cloud·系统架构
Coding小公仔1 小时前
C++ bitset 模板类
开发语言·c++
KK溜了溜了1 小时前
JAVA-springboot 整合Redis
java·spring boot·redis
雨白1 小时前
Jetpack系列(二):Lifecycle与LiveData结合,打造响应式UI
android·android jetpack
小赖同学啊2 小时前
物联网数据安全区块链服务
开发语言·python·区块链
天河归来2 小时前
使用idea创建springboot单体项目
java·spring boot·intellij-idea
shimly1234562 小时前
bash 脚本比较 100 个程序运行时间,精确到毫秒,脚本
开发语言·chrome·bash
weixin_478689762 小时前
十大排序算法汇总
java·算法·排序算法