0

Is it possible to problematically "draw" text to a Shape or Drawable in Android (using Kotlin) to use the result as image for an ImageView?

In iOS it is no problem to draw custom text to a UIImageContext which can then be used to create a UIImage (e.g as described here). Is something similar possible in Android as well?

Andrei Herford
  • 17,570
  • 19
  • 91
  • 225

1 Answers1

1

You can make your own Drawable implementation. Android drawing is done via Paint and a Canvas. Here's an example:

class TextIconDrawable: Drawable() {
    private var alpha = 255
    private var textPaint = TextPaint().apply {
        textAlign = Paint.Align.CENTER
    }
    var text by Delegates.observable("") { _, _, _ -> invalidateSelf() }
    var textColor by Delegates.observable(Color.BLACK) { _, _, _ -> invalidateSelf() }

    private fun fitText(width: Int) {
        textPaint.textSize = 48f
        val widthAt48 = textPaint.measureText(text)
        textPaint.textSize = 48f / widthAt48 * width.toFloat()
    }

    override fun draw(canvas: Canvas) {
        val width = bounds.width()
        val height = bounds.height()
        fitText(width)
        textPaint.color = ColorUtils.setAlphaComponent(textColor, alpha)
        canvas.drawText(text, width / 2f, height / 2f, textPaint)
    }

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

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

    override fun getOpacity(): Int = PixelFormat.TRANSLUCENT

}

Usage:

val drawable = TextIconDrawable().apply {
    text = "Hello, world!"
    textColor = Color.BLACK
}
requireView().findViewById<ImageView>(R.id.imageView).setImageDrawable(drawable)

You can of course customize what properties are exposed. Or if this is a one-time use thing, just set the properties as needed on the paint instance.

Tenfour04
  • 83,111
  • 11
  • 94
  • 154