There is described how to draw some text on an image from the resource.
I wanted to make dynamically text and draw text in a circle on the template of the image.
My template for painting:
I implemented next function:
//Change text size according text lengthprivate fun getTextSize(text1: String, text2: String) =
if (text1.length >= 21 || text2.length >= 20) 90 else 125
private fun drawTextToBitmap(context: Context, gResId: Int, textSize: Int = 78, text1: String, text2: String): Bitmap {
val resources = context.resources
val scale = resources.displayMetrics.density
var bitmap = BitmapFactory.decodeResource(resources, gResId)
var bitmapConfig = bitmap.config;
// set default bitmap config if none
if (bitmapConfig == null) {
bitmapConfig = android.graphics.Bitmap.Config.ARGB_8888
}
// resource bitmaps are imutable,
// so we need to convert it to mutable one
bitmap = bitmap.copy(bitmapConfig, true)
val canvas = Canvas(bitmap)
// new antialised Paint
val paint = Paint(Paint.ANTI_ALIAS_FLAG)
paint.color = Color.rgb(93, 101, 67)
// text size in pixels
paint.textSize = (textSize * scale).roundToInt().toFloat()
//custom fonts val fontFace = ResourcesCompat.getFont(context, R.font.acrobat)
paint.typeface = Typeface.create(fontFace, Typeface.NORMAL)
// text shadow
paint.setShadowLayer(1f, 0f, 1f, Color.WHITE)
// draw text to the Canvas center
val bounds = Rect() //draw the first text
paint.getTextBounds(text1, 0, text1.length, bounds)
var x = (bitmap.width - bounds.width()) / 2f - 470
var y = (bitmap.height + bounds.height()) / 2f - 140
canvas.drawText(text1, x, y, paint) //draw the second text
paint.getTextBounds(text2, 0, text2.length, bounds)
x = (bitmap.width - bounds.width()) / 2f - 470
y = (bitmap.height + bounds.height()) / 2f + 235
canvas.drawText(text2, x, y, paint)
return bitmap
}
After that I tested my application and I get exception:
java.lang.RuntimeException: Canvas: trying to draw too large(136676736bytes) bitmap.
For example, it’s not worth loading a 1024x768 pixel image into memory if it will eventually be displayed in a 128x96 pixel thumbnail in an ImageView
. To solve this should read this documentation. But I didn’t need display in the ImageView, because I send the bitmap to a SDK.
The result:
Thus I could created the image for posting in social network (vk.com).
Google play: https://play.google.com/store/apps/details?id=ru.a1024bits.bytheway.release