1. Requirement description
The project has a requirement to display text on a full-screen image and generate a new image and share it. The image is full-screen and the text is centered.
So I thought of using Canvas to draw directly.
2. Implement the code
private fun createImg(imageView: ImageView, textView: TextView): Bitmap {
//返回具有指定宽度和高度的可变位图
val imageViewBitmap =
Bitmap.createBitmap(imageView.width, imageView.height, Bitmap.Config.ARGB_8888)
//使用指定的位图构造一个画布以绘制到其中。位图必须是可变的。
val imageViewCanvas = Canvas(imageViewBitmap)
//手动将此视图(及其所有子视图)渲染到给定的Canvas。
imageView.draw(imageViewCanvas)
val textViewText = textView.text.toString()
val textViewTextSize = textView.textSize
val textViewTextColor = textView.currentTextColor
val combinedBitmap =
Bitmap.createBitmap(imageView.width, imageView.height, Bitmap.Config.ARGB_8888)
val combinedCanvas = Canvas(combinedBitmap)
//绘制指定的位图,其上角/左角位于(x,y),并由当前矩阵变换。
combinedCanvas.drawBitmap(imageViewBitmap, 0f, 0f, null)
val textPaint = TextPaint()
textPaint.textSize = textViewTextSize
textPaint.color = textViewTextColor
val maxWidth = 300f * textView.context.resources.displayMetrics.density
val textLayout = StaticLayout(
textViewText,
textPaint,
maxWidth.toInt(),
Layout.Alignment.ALIGN_CENTER,
1.0f,
0.0f,
false
)
//文案居中
val textY = (imageView.height - textLayout.height) / 2
combinedCanvas.save()
combinedCanvas.translate((imageView.width - maxWidth) / 2, textY.toFloat())
//文本绘制到画布中去
textLayout.draw(combinedCanvas)
combinedCanvas.restore()
return combinedBitmap
}
The specific principles are commented in the code.
2023.11.06
I found that it is not necessary. Just generate a picture from the parent layout. The above method takes a lot of time and is not performance friendly.
val width = mBinding.allContentCL.width
val height = mBinding.allContentCL.height
val bitmap: Bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
mBinding.allContentCL.draw(canvas)
That'll be fine. This bitmap object is the picture generated by this control