gpt4 book ai didi

android - Jetpack 撰写 : How to create a rating bar?

转载 作者:行者123 更新时间:2023-12-05 09:26:29 27 4
gpt4 key购买 nike

我正在尝试实现评级栏。我指的是https://gist.github.com/vitorprado/0ae4ad60c296aefafba4a157bb165e60但我对此代码一无所知。它有效,但是当我使用这段代码时,星星没有圆角。我想实现如下内容:

最佳答案

我为此制作了非常基本的示例,它将给出创建带有示例边框和填充 png 文件的评级栏的基本想法。

@Composable
private fun RatingBar(
modifier: Modifier = Modifier,
rating: Float,
spaceBetween: Dp = 0.dp
) {

val image = ImageBitmap.imageResource(id = R.drawable.star)
val imageFull = ImageBitmap.imageResource(id = R.drawable.star_full)

val totalCount = 5

val height = LocalDensity.current.run { image.height.toDp() }
val width = LocalDensity.current.run { image.width.toDp() }
val space = LocalDensity.current.run { spaceBetween.toPx() }
val totalWidth = width * totalCount + spaceBetween * (totalCount - 1)


Box(
modifier
.width(totalWidth)
.height(height)
.drawBehind {
drawRating(rating, image, imageFull, space)
})
}

private fun DrawScope.drawRating(
rating: Float,
image: ImageBitmap,
imageFull: ImageBitmap,
space: Float
) {

val totalCount = 5

val imageWidth = image.width.toFloat()
val imageHeight = size.height

val reminder = rating - rating.toInt()
val ratingInt = (rating - reminder).toInt()

for (i in 0 until totalCount) {

val start = imageWidth * i + space * i

drawImage(
image = image,
topLeft = Offset(start, 0f)
)
}

drawWithLayer {
for (i in 0 until totalCount) {
val start = imageWidth * i + space * i
// Destination
drawImage(
image = imageFull,
topLeft = Offset(start, 0f)
)
}

val end = imageWidth * totalCount + space * (totalCount - 1)
val start = rating * imageWidth + ratingInt * space
val size = end - start

// Source
drawRect(
Color.Transparent,
topLeft = Offset(start, 0f),
size = Size(size, height = imageHeight),
blendMode = BlendMode.SrcIn
)
}
}

private fun DrawScope.drawWithLayer(block: DrawScope.() -> Unit) {
with(drawContext.canvas.nativeCanvas) {
val checkPoint = saveLayer(null, null)
block()
restoreToCount(checkPoint)
}
}

用法

Column {
RatingBar(rating = 3.7f, spaceBetween = 3.dp)
RatingBar(rating = 2.5f, spaceBetween = 2.dp)
RatingBar(rating = 4.5f, spaceBetween = 2.dp)
RatingBar(rating = 1.3f, spaceBetween = 4.dp)
}

结果

enter image description here

还创建了一个使用手势、其他 png 文件和矢量作为评级项目的库可用 here .

RatingBar(
rating = rating,
space = 2.dp,
imageBackground = imageBackground,
imageForeground = imageForeground,
animationEnabled = false,
gestureEnabled = true,
itemSize = 60.dp
) {
rating = it
}

enter image description here

关于android - Jetpack 撰写 : How to create a rating bar?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73948960/

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