2
votes

I am trying to create bitmap with semi-transparent background (not black). I use the next code:

    val result = drawable.bitmap.copy(Bitmap.Config.ARGB_8888, true)
    for (y in 0 until result.height) for (x in 0 until result.width) {
        val dstColor = Color.argb(100, 255, 255, 255)
        result.setPixel(x, y, dstColor)
    }

But all I see is white opaque white color. I've tried to set alpha param to 0, use different colors (read, green), but it doesn't work. What the possible reasons?

2

2 Answers

1
votes

After getting a copy of the bitmap, execute the following line to create an alpha channel:

result.setHasAlpha(true)

Everything else should work as is.

For example, take your code and make the changes as follows:

// Get the bitmap. What the bitmap is doesn't really matter. Here it is just a jpg.
val drawable = ResourcesCompat.getDrawable(resources, R.drawable.somebitmap, null) as BitmapDrawable
val result = drawable.bitmap.copy(Bitmap.Config.ARGB_8888, true)
result.setHasAlpha(true)
val dstColor = Color.argb(100, 255, 255, 255)
for (y in 0 until result.height) for (x in 0 until result.width) {
    result.setPixel(x, y, dstColor)
}

image.setImageBitmap(result)

If result.setHasAlpha(true) is commented out, then we will see the following image. Here there is no translucence on the image.

enter image description here

If we uncomment result.setHasAlpha(true) then we can see the translucence:

enter image description here

0
votes

I test the next approach creating a layout with only an image view (bitmap_container id), and it works, but i needed to change the background viewgroup color to see it:

val bitmap = Bitmap.createBitmap(
    100,
    100,
    Bitmap.Config.ARGB_8888
)
val color = Color.argb(100, 255, 255, 255)
Canvas(bitmap).apply { drawColor(color) }
bitmap_container.setImageBitmap(bitmap)