Android 撰写 - 如何 tile/repeat 一个 bitmap/vector?

Android Compose - How to tile/repeat a bitmap/vector?

什么是 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 class 来实现您的目标

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)
    ) {
        ----
    }