Skip to content

Instantly share code, notes, and snippets.

@armcha
Created October 26, 2023 10:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save armcha/53abcf8efeb6c5049b36eb79a92d09c9 to your computer and use it in GitHub Desktop.
Save armcha/53abcf8efeb6c5049b36eb79a92d09c9 to your computer and use it in GitHub Desktop.
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