Skip to content

Instantly share code, notes, and snippets.

@Turskyi
Last active July 24, 2021 10:27
Show Gist options
  • Save Turskyi/8e5a62a5e8f38b409d01eea716f9e50b to your computer and use it in GitHub Desktop.
Save Turskyi/8e5a62a5e8f38b409d01eea716f9e50b to your computer and use it in GitHub Desktop.
Convenient string extensions for kotlin
fun String.fromHtmlToSpanned(): Spanned = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Html.fromHtml(this, Html.FROM_HTML_MODE_LEGACY)
} else {
HtmlCompat.fromHtml(this, HtmlCompat.FROM_HTML_MODE_LEGACY)
}
/** turn string into the picture */
fun String.convertToBitmap(textSize: Float, textColor: Int): Bitmap {
val paint = Paint(Paint.ANTI_ALIAS_FLAG)
paint.textSize = textSize
paint.color = textColor
paint.textAlign = Paint.Align.LEFT
/* ascent() is negative */
val baseline: Float = -paint.ascent()
/* round */
val width = (paint.measureText(this) + 0.5f).toInt()
val height = (baseline + paint.descent() + 0.5f).toInt()
val image = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
val canvas = Canvas(image)
canvas.drawText(this, 0F, baseline, paint)
return image
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment