gpt4 book ai didi

Android Compose - 如何平铺/重复位图/矢量?

转载 作者:行者123 更新时间:2023-12-04 23:42:10 28 4
gpt4 key购买 nike

什么是 Android Compose 方法来平铺图像以用小图案填充我的背景?
没有旋转的位图的天真方法可能是这样的:

@Composable
fun TileImage() {
val pattern = ImageBitmap.imageResource(R.drawable.pattern_bitmap)

Canvas(modifier = Modifier.fillMaxSize()) {
// rotate(degrees = -15f) { // The rotation does not produce the desired effect
val totalWidth = size.width / pattern.width
val totalHeight = size.height / pattern.height

var x = 0f
var y = 0f
for (i in 0..totalHeight.toInt()) {
y = (i * pattern.height).toFloat()
for (j in 0..totalWidth.toInt()) {
x = (j * pattern.width).toFloat()

drawImage(
pattern,
colorFilter = giftColorFilter,
topLeft = Offset(x, y)
)
}
}
// }
}
}
在 Android XML 中,您可以轻松地创建 XML 来重复位图
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
android:src="@drawable/pattern_bitmap"
android:tileMode="repeat" />
或者,如果您需要平铺矢量,您可以使用自定义 Drawable 类来实现您的目标
TileDrawable(AppCompatResources.getDrawable(context, R.drawable.pattern_vector), Shader.TileMode.REPEAT)

class TileDrawable(drawable: Drawable, tileMode: Shader.TileMode, private val angle: Float? = null) : Drawable() {

private val paint: Paint = Paint().apply {
shader = BitmapShader(getBitmap(drawable), tileMode, tileMode)
}

override fun draw(canvas: Canvas) {
angle?.let {
canvas.rotate(it)
}
canvas.drawPaint(paint)
}

override fun setAlpha(alpha: Int) {
paint.alpha = alpha
}

override fun getOpacity() = PixelFormat.TRANSLUCENT

override fun setColorFilter(colorFilter: ColorFilter?) {
paint.colorFilter = colorFilter
}

private fun getBitmap(drawable: Drawable): Bitmap {
if (drawable is BitmapDrawable) {
return drawable.bitmap
}
val bmp = Bitmap.createBitmap(
drawable.intrinsicWidth, drawable.intrinsicHeight,
Bitmap.Config.ARGB_8888
)
val c = Canvas(bmp)
drawable.setBounds(0, 0, drawable.intrinsicWidth, drawable.intrinsicHeight)
drawable.draw(c)
return bmp
}

}

最佳答案

如果你想使用原生 Canvas ,你可以在 jetpack compose 中执行类似的操作。


Canvas(
modifier = Modifier
.fillMaxSize()
) {

val paint = Paint().asFrameworkPaint().apply {
isAntiAlias = true
shader = ImageShader(pattern, TileMode.Repeated, TileMode.Repeated)
}

drawIntoCanvas {
it.nativeCanvas.drawPaint(paint)
}
paint.reset()
}

如果您想将重复限制在某个高度和宽度,您可以在 Canvas 中使用剪辑修饰符,如下所示,否则它将填满整个屏幕。

Canvas(
modifier = Modifier
.width(300.dp)
.height(200.dp)
.clip(RectangleShape)
) {
----
}

关于Android Compose - 如何平铺/重复位图/矢量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67535896/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com