效果图
网络图片加载库Coil
implementation("io.coil-kt:coil-compose:2.6.0")
核心组件
Coil(AsyncImage) +HorizontalPager+LaunchedEffect
测试数据
val imgList = listOf(
"https://img.lovestu.com/uploads/2024/03/xzm2024.webp",
"https://img.lovestu.com/uploads/2023/10/adobe2024banner.webp",
"https://img.lovestu.com/uploads/2021/10/windows11banner1.png",
"https://img.lovestu.com/uploads/2021/03/office2021banner2.png"
)
状态变量
val pagerState = rememberPagerState(
initialPage = 0,
initialPageOffsetFraction = 0f,
pageCount = { imgList.size }
)
val nowPageIndex = pagerState.currentPage
val scope = rememberCoroutineScope()
定时器
LaunchedEffect(pagerState.settledPage) {
delay(3000)
val scroller =
if (pagerState.currentPage + 1 == imgList.size) 0 else pagerState.currentPage + 1
pagerState.animateScrollToPage(scroller)
}
轮播Banner代码
Box {
HorizontalPager(
state = pagerState,
contentPadding = PaddingValues(horizontal = 50.dp),
modifier = Modifier
.height(180.dp)
.padding(top = 15.dp),
beyondBoundsPageCount = imgList.size
) { index ->
val imgScale by animateFloatAsState(
targetValue = if (nowPageIndex == index)
1f else 0.8f,
animationSpec = tween(300), label = ""
)
AsyncImage(
modifier = Modifier
.fillMaxSize()
.scale(imgScale)
.clip(
RoundedCornerShape(10.dp)
),
model = ImageRequest
.Builder(LocalContext.current)
.data(imgList[index])
.scale(Scale.FILL)
.build(),
contentDescription = "图片$index",
contentScale = ContentScale.FillBounds
)
}
Row(
modifier = Modifier
.fillMaxWidth()
.align(Alignment.BottomCenter)
.padding(bottom = 5.dp),
horizontalArrangement = Arrangement.Center
) {
imgList.indices.forEach { radioIndex ->
RadioButton(selected = nowPageIndex == radioIndex, onClick = {
scope.launch {
pagerState.animateScrollToPage(radioIndex)
}
})
}
}
}