androidkotlinandroid-drawableandroid-bitmapandroid-icons

Android: How can I apply a tint to a Drawable/Bitmap in Kotlin?


I wanted to create a shortcut using a tinted icon, so I could not just add a tint to an ImageView. I did it this way:

val drawableExample: Drawable
val colorExample: Int

drawable?.colorFilter = PorterDuffColorFilter(colorExample, PorterDuff.Mode.SRC_IN)

val icon: Icon = Icon.createWithBitmap(drawable?.toBitmap(256, 256, null))

See the accepted answer for details on how to do this if your source image already is a Bitmap. It put me on the right track to find a slightly simpler solution that is suitable for me.


Solution

  • You can use colorFilter

    val paint = Paint()
    paint.setColorFilter(PorterDuffColorFilter(targetColor, PorterDuff.Mode.SRC_IN))
    canvas.drawBitmap(resource, matrix, paint)