I want to add a layer of StaticLayout when rendering a custom View. However, the draw(canvas) method of StaticLayout does not support alpha. ChatGPT suggested two solutions:
- Use saveLayerAlpha.
- Generate a BitmapDrawable and set the paint’s alpha when drawing.
Intuitively, using saveLayerAlpha to create an extra layer seems better than generating a bitmap.
However, my requirement involves running an alpha animation (e.g., from 0 to 255). Using solution 1 would create an extra layer in each frame during invalidate/onDraw, while solution 2 only generates a temporary BitmapDrawable, changes the paint’s alpha, and draws it on the custom View’s layer. It seems that solution 2 generates fewer objects.
example code
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
drawOthers()
drawStaticLayoutWithAlpha()
}
- Solution 1 example
fun drawStaticLayoutWithAlpha(canvas: Canvas) {
val saveCount = canvas.saveLayerAlpha(0f, 0f, width.toFloat(), height.toFloat(), alphaValue)
staticLayout.draw(canvas)
canvas.restoreToCount(saveCount)
}
- Solution 2 example
use bitmapDrawable or bitmap。 The efficiency of using bitmap or BitmapDrawable is about the same, I guess.
fun drawStaticLayoutWithAlpha(canvas: Canvas) {
drawable.alpha = alphaValue
drawable.setBounds(0, 0, width, height)
drawable.draw(canvas)
// or
val paint = Paint()
paint.alpha = alpha
canvas.drawBitmap(bitmap, x, y, paint)
}
My question is, please comment on the two solutions. Which one is better when there is an animation involved?