Skip to content

Instantly share code, notes, and snippets.

@mootoh
Created November 21, 2019 10:15
Show Gist options
  • Save mootoh/1bb1ec6f0e1ffb9b8cef6e6456917a10 to your computer and use it in GitHub Desktop.
Save mootoh/1bb1ec6f0e1ffb9b8cef6e6456917a10 to your computer and use it in GitHub Desktop.
Load remote image with Coil into Jetpack Compose Image
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MaterialTheme {
Column {
ItemCell(item = Item("cat 1", "https://thumbs-prod.si-cdn.com/s-rtW1rEAQTIGcmUVNFSSPC4s3I=/800x600/filters:no_upscale()/https://public-media.si-cdn.com/filer/56/4a/564a542d-5c37-4be7-8892-98201ab13180/cat-2083492_1280.jpg"))
ItemCell(item = Item("cat 2", "https://images.pexels.com/photos/104827/cat-pet-animal-domestic-104827.jpeg?auto=compress&cs=tinysrgb&h=750&w=1260"))
}
}
}
}
}
data class Item(val name: String, val imageURL: String)
@Model
class ItemState {
var image: Image = Image(64, 64)
}
@Composable
fun ItemCell(item: Item) {
val state = ItemState()
GlobalScope.launch {
val drawable = Coil.get(item.imageURL) {}
MainScope().launch {
state.image = RemoteImage(drawable.toBitmap())
}
}
Column {
Text(item.name)
Container(width = 180.dp, height = 180.dp) {
DrawImage(image = state.image)
}
}
}
// NOTE: copied from androidx.ui.graphics.AndroidImage
class RemoteImage(private val bitmap: Bitmap) : Image {
override val width = bitmap.width
override val height = bitmap.height
override val config = ImageConfig.Argb8888
override val colorSpace = ColorSpaces.Srgb
override val hasAlpha = bitmap.hasAlpha()
override val nativeImage = bitmap
override fun prepareToDraw() = bitmap.prepareToDraw()
}
@mootoh
Copy link
Author

mootoh commented Nov 21, 2019

Result

Result

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment