こんな時
- StringをどうしてもBitmapの形に変換したい時
- BitmapをどうしてもDrawableの形に変換したい時
- StringをどうしてもDrawableの形に変換したい時
前提
- Composable関数の中で書く
- coilを使うのでgradleに以下追加
implementation("io.coil-kt:coil-compose:2.1.0")
コード
コルーチンの中で変換します。
以下は String -> Bitmap -> Drawableの順に変換してます。
val myString = "画像URLとか"
val context = LocalContext.current
val coroutineScope = rememberCoroutineScope()
coroutineScope.launch{
val loader = ImageLoader(context)
val request = ImageRequest.Builder(context)
.data(myString)
.allowHardware(false)
.build()
val result = (loader.execute(request) as SuccessResult).drawable
val myBitmap = (result as BitmapDrawable).bitmap
val myDrawable = context.imageLoader
.execute(ImageRequest.Builder(context).data(myBitmap).build())
.drawable
}
myBitmapがbitmapの形になってます。
myDrawableがDrawableの形になってます。
参考