Skip to content

Instantly share code, notes, and snippets.

@TalbotGooday
Last active May 11, 2019 10:22
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 TalbotGooday/b53664196432f9a2630604c660d8db2a to your computer and use it in GitHub Desktop.
Save TalbotGooday/b53664196432f9a2630604c660d8db2a to your computer and use it in GitHub Desktop.
Draw avatar plcaholder and save to cache dir. Need no permissions
fun drawTextToBitmapOrGetCache(context: Context, text: String, @ColorRes textColor: Int, @ColorRes backgroundColor: Int, textSize: Float = 33f): Bitmap? {
val name = "${text}_image"
val file = File(context.cacheDir, name)
Log.d("CACHE_IMAGE", "${file.exists()} $name ${file.absolutePath}")
return if (file.exists()) {
getNamePlaceholderFromCache(file)
} else {
val namePlaceholderBitmap = drawTextToBitmap(context, text, textColor, backgroundColor, textSize)
writeNamePlaceholderToCache(file, namePlaceholderBitmap)
namePlaceholderBitmap
}
}
fun getNamePlaceholderFromCache(file: File): Bitmap {
val options = BitmapFactory.Options()
options.inPreferredConfig = Bitmap.Config.ARGB_8888
Log.d("CACHE_IMAGE_GET", file.absolutePath)
return BitmapFactory.decodeFile(file.absolutePath, options)
}
fun writeNamePlaceholderToCache(file: File, bitmap: Bitmap) {
try {
val outputStream = FileOutputStream(file)
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, outputStream)
outputStream.flush()
outputStream.close()
Log.d("CACHE_IMAGE_WRITE", file.absolutePath)
}catch(e: Exception){
e.printStackTrace()
}
}
fun drawTextToBitmap(context: Context, text: String, @ColorRes textColor: Int, @ColorRes backgroundColor: Int, textSize: Float = 33f): Bitmap {
val size = context.resources.getDimensionPixelSize(R.dimen.helpcrunch_icon_message_size)
var bitmap = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888)
var bitmapConfig: Bitmap.Config? = bitmap.config
if (bitmapConfig == null) {
bitmapConfig = Bitmap.Config.ARGB_8888
}
bitmap = bitmap.copy(bitmapConfig, true)
val canvas = Canvas(bitmap)
val paint = Paint(Paint.ANTI_ALIAS_FLAG)
paint.color = context.color(textColor)
paint.textSize = textSize
paint.setShadowLayer(1f, 0f, 1f, Color.WHITE)
paint.typeface = ResourcesCompat.getFont(context, R.font.sfp_regular)
val paintCircle = Paint()
paintCircle.color = context.color(backgroundColor)
paintCircle.style = Paint.Style.FILL
paintCircle.flags = Paint.ANTI_ALIAS_FLAG
canvas.drawRect(0f, 0f, bitmap.width.toFloat(), bitmap.height.toFloat(), paintCircle)
val bounds = Rect()
paint.getTextBounds(text, 0, text.length, bounds)
val x = (bitmap.width - bounds.width()) / 2
val y = (bitmap.height + bounds.height()) / 2
canvas.drawText(text, x.toFloat(), y.toFloat(), paint)
return bitmap
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment