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 生成

相关推荐
Lei活在当下1 小时前
【Perfetto从入门到精通】2. 使用 Perfetto 追踪/分析 APP 的 Native/Java 内存
android·性能优化·架构
愤怒的代码2 小时前
🔗 深度解析 SystemUI 进程间通信机制(一)
android·操作系统·app
HerayChen2 小时前
HbuilderX 内存溢出报错
java·大数据·linux
diegoXie2 小时前
Python / R 向量顺序分割与跨步分割
开发语言·python·r语言
程序员小白条3 小时前
0经验如何找实习?
java·开发语言·数据结构·数据库·链表
liulilittle3 小时前
C++ 浮点数封装。
linux·服务器·开发语言·前端·网络·数据库·c++
小马爱打代码3 小时前
Spring AI:搭建自定义 MCP Server:获取 QQ 信息
java·人工智能·spring
郭涤生3 小时前
QT 架构笔记
java·数据库·系统架构
daidaidaiyu3 小时前
基于LangGraph开发复杂智能体学习一则
java·ai
RainyJiang3 小时前
聊聊协程里的 Semaphore:别让协程挤爆门口
android·kotlin