Skip to content

Instantly share code, notes, and snippets.

Created October 26, 2023 10:18
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
fun Context.textAsBitmap(
text: String,
fontSize: TextUnit,
color: Color = Color.Black,
letterSpacing: Float = 0.1f,
font: Int
): Bitmap {
val paint = TextPaint(Paint.ANTI_ALIAS_FLAG)
paint.textSize = spToPx(fontSize.value, this)
paint.color = color.toArgb()
paint.letterSpacing = letterSpacing
paint.typeface = ResourcesCompat.getFont(this, font)
val baseline = -paint.ascent()
val width = (paint.measureText(text)).toInt()
val height = (baseline + paint.descent()).toInt()
val image = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
val canvas = Canvas(image)
canvas.drawText(text, 0f, baseline, paint)
return image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment