vendredi 14 mai 2021

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

What is the Android Compose approach to tile an image to fill my background with a small pattern?

In Android XML you can easily create XML to repeat a bitmap

<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
android:src="@drawable/pattern_bitmap" 
android:tileMode="repeat" />

Or if you need to tile a vector you can use a custom Drawable class to achieve your goal

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
    }

}

Aucun commentaire:

Enregistrer un commentaire