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

相关推荐
Jabes.yang几秒前
Java求职面试:从Spring Boot到Kafka的技术探讨
java·spring boot·面试·kafka·互联网大厂
千里马-horse9 分钟前
Async++ 源码分析7--parallel_reduce.h
开发语言·c++·async++·parallel_reduce
叫我龙翔19 分钟前
【MySQL】从零开始了解数据库开发 --- 数据表的约束
android·c++·mysql·数据库开发
量化交易曾小健(金融号)20 分钟前
Python美股量化交易填坑记录——3.盈透(Interactive Brokers)证券API接口
开发语言·python
canonical_entropy43 分钟前
DDD本质论:从哲学到数学,再到工程实践的完整指南之实践篇
java·后端·领域驱动设计
2501_9160137443 分钟前
iOS 上架 App 全流程实战,应用打包、ipa 上传、App Store 审核与工具组合最佳实践
android·ios·小程序·https·uni-app·iphone·webview
2501_915106321 小时前
iOS 26 能耗监测全景,Adaptive Power、新电池视图
android·macos·ios·小程序·uni-app·cocoa·iphone
Madison-No71 小时前
【C++】探秘string的底层实现
开发语言·c++
_Power_Y1 小时前
Java面试常用算法api速刷
java·算法·面试
纪莫1 小时前
技术面:Spring (事务传播机制、事务失效的原因、BeanFactory和FactoryBean的关系)
java·spring·java面试⑧股