How to change Image Opacity in Android Jetpack Compose

By Mohammed Rashid •  November 20th, 2022 • 

Opacity is an important design aspect and different levels of opacity are used to distinguish UI elements. Let’s check how to change image opacity in Android using Jetpack Compose.

Image composable has many useful parameters and alpha is one among them. The alpha parameter helps us to change the opacity of a given image. See the code snippet given below.

@Composable
fun ImageOpacityExample() {
    val image = painterResource(id = R.drawable.animal)
    Image(painter = image, contentDescription = null,
    alpha = 0.5f)
}

Here, we show an image with 50% opacity. The output screenshot is given below.

jetpack compose image opacity example

Following is the complete code for this Jetpack Compose Image opacity example.

package com.example.myapplication

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Check
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.foundation.Image
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.myapplication.ui.theme.MyApplicationTheme

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MyApplicationTheme {
                Surface(
                    color = MaterialTheme.colors.background,
                    modifier = Modifier.fillMaxSize()
                ) {
                    ImageOpacityExample()
                }
            }
        }
    }
}

@Composable
fun ImageOpacityExample() {
    val image = painterResource(id = R.drawable.animal)
    Image(painter = image, contentDescription = null,
    alpha = 0.5f)
}

@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
    MyApplicationTheme {
        ImageOpacityExample()
    }
}

That’s how you change the opacity or the transparency of an image in Jetpack Compose.

Mohammed Rashid

Keep Reading