- Image(
- modifier = Modifier
- .fillMaxWidth()
- .height(200.dp),
- painter = painterResource(id = R.drawable.img),
- contentDescription = "描述",
- //0~1完全透明到完全不透明设置
- alpha = 1f,
- //图片拉伸或裁剪设置
- contentScale = ContentScale.Crop
- )
加载本地图片通过painter属性设置图片。
alpha设置图片的透明程度,0到1从完全透明到完全不透明。
contentScale属性设置图片拉伸方式。
- AsyncImage(
- modifier = Modifier
- .fillMaxWidth()
- .height(200.dp),
- model = "https://pic.lvmama.com/uploads/pc/place2/2017-05-23/c362e80d-eadf-4b26-807c-629eec13bb4f.jpg",
- contentDescription = "描述",
- //图片拉伸或裁剪设置
- contentScale = ContentScale.Crop
- )
加载网络图片需要引入三方库
implementation("io.coil-kt:coil-compose:2.4.0")
引用coil库后通过AsyncImage下的model属性设置图片地址。
加载网络图片需要添加网络权限
<uses-permission android:name="android.permission.INTERNET" />
完整代码:
- import android.os.Bundle
- import androidx.activity.ComponentActivity
- import androidx.activity.compose.setContent
- import androidx.compose.foundation.Image
- import androidx.compose.foundation.layout.Column
- import androidx.compose.foundation.layout.fillMaxSize
- import androidx.compose.foundation.layout.fillMaxWidth
- import androidx.compose.foundation.layout.height
- import androidx.compose.material3.MaterialTheme
- import androidx.compose.material3.Surface
- import androidx.compose.runtime.Composable
- import androidx.compose.ui.Modifier
- import androidx.compose.ui.layout.ContentScale
- import androidx.compose.ui.res.painterResource
- import androidx.compose.ui.tooling.preview.Preview
- import androidx.compose.ui.unit.dp
- import coil.compose.AsyncImage
- import com.cwj.composedemo.ui.theme.ComposeDemoTheme
-
- class MainActivity : ComponentActivity() {
- override fun onCreate(savedInstanceState: Bundle?) {
- super.onCreate(savedInstanceState)
- setContent {
- ComposeDemoTheme {
- // A surface container using the 'background' color from the theme
- Surface(
- modifier = Modifier.fillMaxSize(),
- color = MaterialTheme.colorScheme.background
- ) {
- Greeting()
- }
- }
- }
- }
- }
-
- @Composable
- fun Greeting() {
- ImageTest()
- }
-
- @Composable
- fun ImageTest() {
- Column {
- //加载本地图片
- Image(
- modifier = Modifier
- .fillMaxWidth()
- .height(200.dp),
- painter = painterResource(id = R.drawable.img),
- contentDescription = "描述",
- //0~1完全透明到完全不透明设置
- alpha = 1f,
- //图片拉伸或裁剪设置
- contentScale = ContentScale.Crop
- )
-
- //加载网络图片
- AsyncImage(
- modifier = Modifier
- .fillMaxWidth()
- .height(200.dp),
- model = "https://pic.lvmama.com/uploads/pc/place2/2017-05-23/c362e80d-eadf-4b26-807c-629eec13bb4f.jpg",
- contentDescription = "描述",
- //图片拉伸或裁剪设置
- contentScale = ContentScale.Crop
- )
-
- }
- }
-
- @Preview(showBackground = true, showSystemUi = true)
- @Composable
- fun GreetingPreview() {
- ComposeDemoTheme {
- Greeting()
- }
- }