在 Android Jetpack Compose 中更改图像的透明度
在 Android 中,我们使用 ImageView 在应用程序中显示图像。我们可以使用库存图像,甚至可以从应用程序中的本地设备导入它们来显示它们。当我们使用 Jetpack Compose 时,我们使用 Image函数来显示图像。图像透明度是图像的不透明度。从数学上讲,如果 opacity 为 1,则显示的图像与原始图像相同。不透明度或 alpha 值介于 0 和 1 之间。在本文中,我们将向您展示如何使用 Jetpack Compose 在 Android 中更改图像的透明度。 IDE 准备就绪后,请按照以下步骤操作。
分步实施
第 1 步:在 Android Studio 中创建一个新项目
要在 Android Studio 中创建新项目,请参阅如何在 Android Studio 中创建/启动新项目。选择模板时,选择Empty Compose Activity 。如果您没有找到此模板,请尝试将 Android Studio 升级到最新版本。我们在Kotlin中演示了该应用程序,因此请确保在创建新项目时选择 Kotlin 作为主要语言。
第 2 步:在 app > res > drawable 文件夹中添加图片
在可绘制文件夹中导入您选择的图像。在我们的应用程序中,我们将其命名为“sample_image”。
第 3 步:使用 MainActivity.kt 文件
转到MainActivity.kt文件并参考以下代码。下面是MainActivity.kt文件的代码。代码中添加了注释以更详细地理解代码。
Kotlin
package com.geeksforgeeks.jcimagetransparency
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
// Calling the composable function
// to display element and its contents
MainContent()
}
}
}
// Creating a composable
// function to display Top Bar
@Composable
fun MainContent(){
Scaffold(
topBar = {TopAppBar(
title = {Text(
"GFG | Change Image Transparency",
color = Color.White)},
backgroundColor = Color(0xff0f9d58)
) },
content = { MyContent()}
)
}
// Creating a composable function to
// create two Images and a spacer between them
// Calling this function as content in the above function
@Composable
fun MyContent(){
Column(Modifier.fillMaxSize(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally) {
// Displaying the original image
Image(
painter = painterResource(id = R.drawable.sample_image),
contentDescription = null,
)
// Adding a space of 100dp
Spacer(modifier = Modifier.height(100.dp))
// Displaying the image with
// less opacity (marked at 20%)
Image(
painter = painterResource(id = R.drawable.sample_image),
contentDescription = null,
alpha = 0.2F
)
}
}
// For displaying preview in
// the Android Studio IDE emulator
@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
MainContent()
}
输出:
当您运行该应用程序时,您将看到两个图像。第一个是不透明度为 100% 的原始图像,第二个是不透明度为 20% 的原始图像,如下所示。