Sur*_*nde 10 android android-jetpack android-jetpack-compose
我正在尝试使用Android Jetpack Compose将图像添加到活动中,但出现错误:
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.foundation.Image
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
Image(bitmap = imageFromResource(res = resources, resId =R.drawable.ic_launcher_background))
}
}
}
Run Code Online (Sandbox Code Playgroud)
大多数本地图像加载的情况都可以使用Image中的PainterResource来完成
例如:
Image(painter = painterResource(id = R.drawable.ic_launcher_background), contentDescription = "")
Run Code Online (Sandbox Code Playgroud)
或者如果您有兴趣更改图像资源的颜色,请使用Icon和PainterResource
Icon(painter = painterResource(id = R.drawable.ic_launcher_background), contentDescription = "", tint = Color.Red)
Run Code Online (Sandbox Code Playgroud)
或者如果您想从远程 URL加载,则使用Coil
添加依赖:
implementation "dev.chrisbanes.accompanist:accompanist-coil:0.6.1"
Run Code Online (Sandbox Code Playgroud)
然后像下面这样使用它:
CoilImage(
data = "https://www.instaily.com/images/android.jpg",
contentDescription = "android",
alignment = Alignment.TopCenter,
modifier = Modifier
.fillMaxWidth()
.fillMaxHeight(.60f),
contentScale = ContentScale.Crop,
loading = {
Box(
modifier = Modifier.background(
shape = RoundedCornerShape(20.dp),
color = Teal200
)
)
},
error = {
Box(
modifier = Modifier.background(
shape = RoundedCornerShape(20.dp),
color = Teal200
)
)
}
)
Run Code Online (Sandbox Code Playgroud)
其中任何一个都可以用来获取图像资源。
使用PainterResource API 加载矢量绘图或光栅化资源格式(如 PNG)。您不需要知道可绘制对象的类型,只需使用painterResource即可。
import androidx.compose.ui.res.painterResource
Image(painterResource(id = imageResource), contentDescription = contentDescription)
Run Code Online (Sandbox Code Playgroud)
或者
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.res.imageResource
Image(ImageBitmap.imageResource(id = imageResource), contentDescription = contentDescription)
Run Code Online (Sandbox Code Playgroud)
或者
import androidx.compose.ui.res.vectorResource
Image(ImageVector.vectorResource(id = imageResource), contentDescription = contentDescription)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
17331 次 |
最近记录: |