// 创建一个可变的State来保存BitmapPainter
// 类型(MutableState<BitmapPainter?>)不能缺失,因为初始值是null
val painter: MutableState<BitmapPainter?> = mutableStateOf(null)
val mGalleryLauncher = registerForActivityResult(ActivityResultContracts.GetContent()){ uri->
uri?.let {
// 不同版本取得方式
val bitmap = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
ImageDecoder.decodeBitmap(ImageDecoder.createSource(this.contentResolver, it))
} else {
MediaStore.Images.Media.getBitmap(this.contentResolver, it)
}
//BitmapPainter只能接收ImageBitmap类型
painter.value = BitmapPainter(bitmap.asImageBitmap())
}
}
Button(onClick = {
// 这会启动一个intent并指定文件格式
mGalleryLauncher.launch("image/*")
}) {
Text(text = "打开相册")
}
painter.value?.let {
androidx.compose.foundation.Image(painter = it,
contentDescription = "取来的照片",
modifier = Modifier.size(width = 300.dp, height = 200.dp))
}