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

相关推荐
Want5951 分钟前
C/C++圣诞树①
c语言·开发语言·c++
生擒小朵拉5 分钟前
STM32添加库函数
java·javascript·stm32
Z_z在努力11 分钟前
【杂类】Spring 自动装配原理
java·spring·mybatis
老赵的博客12 分钟前
c++ 杂记
开发语言·c++
jimmy.hua15 分钟前
[C++刷怪笼]:set/map--优质且易操作的容器
开发语言·c++
小小菜鸡ing39 分钟前
pymysql
java·服务器·数据库
getapi41 分钟前
shareId 的产生与传递链路
java
w2sfot1 小时前
Passing Arguments as an Object in JavaScript
开发语言·javascript·ecmascript
郝学胜-神的一滴2 小时前
避免使用非const全局变量:C++中的最佳实践 (C++ Core Guidelines)
开发语言·c++·程序人生
我没想到原来他们都是一堆坏人2 小时前
(未完待续...)如何编写一个用于构建python web项目镜像的dockerfile文件
java·前端·python