按照设置显示视频的关键帧图片,没使用过coil可以先看我的上一篇文章:[Android][Compose]Coil框架-CSDN博客
依赖
implementation("io.coil-kt:coil-video:2.6.0")
要在Android开发中使用改库,需要在imageLoader添加配置
val imageLoader = ImageLoader.Builder(context)
.components {
add(VideoFrameDecoder.Factory())
}
.build()
Compose框架
创建ImageRequest
要指定从视频中提取帧的时间,请使用videoFrameMillis或videoFrameMicros,下文代码作用是视频距离0秒最近的关键帧:
val imageRequest = ImageRequest.Builder(LocalContext.current)
.data("/path/to/video.mp4")
.crossfade(true)
.placeholder(R.drawable.place_holder)
.apply{
//显示视频距离0秒最近的关键帧
videoFrameMillis(0)
}
.build()
如果没有指定帧位置,则将对视频的第一帧进行解码。
创建AsyncImagePainter
需要把上文创建出来的imageRequest和imageLoader传进来
val painter = rememberAsyncImagePainter(model = imageRequest,
imageLoader = imageLoader)
Image
将创建好的painter传入Image组件
Image(
painter = painter,
modifier = Modifier
.fillMaxSize()
.graphicsLayer {
alpha = picShowAnim.value
},
contentDescription = "VideoFrame",
contentScale = ContentScale.FillBounds,
)
AsyncImage
也可以使用AsyncImage,上面我为了更好的展示出来,所以分离了好几步。下面是是使用AsyncImage来实现:
AsyncImage(
model = ImageRequest.Builder(LocalContext.current)
.data("/path/to/video.mp4")
.crossfade(true)
.apply{
//显示视频距离0秒最近的关键帧
videoFrameMillis(0)
}
.build(),
placeholder = painterResource(R.drawable.placeholder),
ccontentDescription = "VideoFrame",
//最好整个app共享一个ImageLoader
imageLoader = imageLoader,
contentScale = ContentScale.FillBounds,
modifier = Modifier.clip(CircleShape)
)
Xml框架
上面详细的说了如何在compose框架下使用视频获取帧,下面就通过xml框架分别列出其他的视频获取帧方式:
- 要指定从视频中提取帧的时间,请使用videoFrameMillis或videoFrameMicros,下文代码作用是视频距离1秒最近的关键帧:
imageView.load("/path/to/video.mp4") {
videoFrameMillis(1000) // extracts the frame at 1 second of the video
}
- 要指定确切的帧数,请使用videoFrameIndex(需要API级别28):
imageView.load("/path/to/video.mp4") {
videoFrameIndex(1234) // extracts the 1234th frame of the video
}
- 要根据视频总持续时间的百分比选择视频帧,请使用videoFramePercent:
imageView.load("/path/to/video.mp4") {
videoFramePercent(0.5) // extracts the frame in the middle of the video's duration
}