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

相关推荐
laowangpython10 分钟前
Rust 入门:GitHub 热门内存安全编程语言
开发语言·其他·rust·github
我叫汪枫14 分钟前
在后台管理系统中,如何递归和选择保留的思路来过滤菜单
开发语言·javascript·node.js·ecmascript
_.Switch16 分钟前
东方财富股票数据JS逆向:secids字段和AES加密实战
开发语言·前端·javascript·网络·爬虫·python·ecmascript
软件技术NINI16 分钟前
webkit简介及工作流程
开发语言·前端·javascript·udp·ecmascript·webkit·yarn
Brendan_00116 分钟前
JavaScript的Stomp.over
开发语言·javascript·ecmascript
念23417 分钟前
f5 shape分析
开发语言·javascript·ecmascript
苍穹之跃20 分钟前
某量JS逆向
开发语言·javascript·ecmascript
思茂信息21 分钟前
CST软件如何进行参数化扫描?
运维·开发语言·javascript·windows·ecmascript·软件工程·软件需求
赈早见.琥珀猪21 分钟前
vue启动ReferenceError: ReadableStream is not defined
开发语言·javascript·ecmascript
爱吃牛肉的大老虎21 分钟前
JS异步中async、await讲解
开发语言·javascript·ecmascript