gpt4 book ai didi

android - 使用 kotlin 协程的正确方法

转载 作者:行者123 更新时间:2023-12-02 13:28:46 25 4
gpt4 key购买 nike

我正在使用 kotlin coroutinescope 从视频 uri 加载缩略图,并在线性布局中添加带有该位图的 ImageView 。
目前在所有缩略图加载后,我正在添加到线性布局中。任何人都可以建议我一一获取 bitmao 并添加到线性布局中吗?

private fun loadThumbnails(uri: Uri) {
val metaDataSource = MediaMetadataRetriever()
metaDataSource.setDataSource(context, uri)

val videoLength = (metaDataSource.extractMetadata(
MediaMetadataRetriever.METADATA_KEY_DURATION).toInt() * 1000).toLong()

val thumbnailCount = 8

val interval = videoLength / thumbnailCount

var listOfImage: ArrayList<Bitmap?> = ArrayList()

for (i in 0 until thumbnailCount - 1) {

try {
var bitmap: Bitmap? = null
val job = CoroutineScope(Dispatchers.IO).launch {
val frameTime = i * interval
bitmap = metaDataSource.getFrameAtTime(frameTime, MediaMetadataRetriever.OPTION_CLOSEST)

bitmap?.let {
val targetWidth: Int
val targetHeight: Int
if (it.height > it.width) {
targetHeight = frameDimension
val percentage = frameDimension.toFloat() / it.height
targetWidth = (it.width * percentage).toInt()
} else {
targetWidth = frameDimension
val percentage = frameDimension.toFloat() / it.width
targetHeight = (it.height * percentage).toInt()
}
bitmap = Bitmap.createScaledBitmap(it, targetWidth, targetHeight, false)
}
listOfImage.add(bitmap)
metaDataSource.release()
}

} catch (e: Exception) {
e.printStackTrace()
}

}

listOfImage.forEach {
container_thumbnails.addView(ThumbnailView(context).apply { setImageBitmap(it) })
}

}

最佳答案

请尝试下一个方法:

val job = CoroutineScope(Dispatchers.Main).launch {
val frameTime = i * interval
val bitmap = loadBitmap(frameTime) // loads bitmap asynchronously using withContext(Dispatchers.IO)

// ... use bitmap to set into a view
}

suspend fun loadBitmap(frameTime: Int): Bitmap? = withContext(Dispatchers.IO) {
bitmap = metaDataSource.getFrameAtTime(frameTime, MediaMetadataRetriever.OPTION_CLOSEST)

bitmap?.let {
val targetWidth: Int
val targetHeight: Int
if (it.height > it.width) {
targetHeight = frameDimension
val percentage = frameDimension.toFloat() / it.height
targetWidth = (it.width * percentage).toInt()
} else {
targetWidth = frameDimension
val percentage = frameDimension.toFloat() / it.width
targetHeight = (it.height * percentage).toInt()
}
Bitmap.createScaledBitmap(it, targetWidth, targetHeight, false)
}
}

关于android - 使用 kotlin 协程的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62549104/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com