如何在Android Jetpack合成中绘制圆形图像?

2lpgd968  于 2023-02-17  发布在  Android
关注(0)|答案(4)|浏览(127)

假设我有一个像下面这样的矩形头像,我如何在Jetpack Compose中强制将其绘制为圆形?

hjzp0vay

hjzp0vay1#

有一个clip修饰符可以应用于任何可组合对象以及Image,只需将一个CircleShape传入其中:

Image(
    painter = painterResource(R.drawable.sample_avatar),
    contentDescription = "avatar",
    contentScale = ContentScale.Crop,            // crop the image if it's not a square
    modifier = Modifier
        .size(64.dp)
        .clip(CircleShape)                       // clip to the circle shape
        .border(2.dp, Color.Gray, CircleShape)   // add a border (optional)
)

您可以使用任何其他形状来剪切图像,例如CircleShape,它只是RoundedCornerShape(percent = 50)。让我们尝试RoundedCornerShape(percent = 10)

uelo1irk

uelo1irk2#

此外,你也可以尝试
implementation "com.github.skydoves:landscapist-glide:1.3.6"
通过使用Modifier.clip(CircleShape)

GlideImage(
            modifier = Modifier
                    .width(50.dp)
                    .height(50.dp)
                    .clip(CircleShape)
                    .clickable(enabled = true, onClick = onClick),
            imageModel = "https://avatars.githubusercontent.com/u/27887884?v=4",
                // Crop, Fit, Inside, FillHeight, FillWidth, None
            contentScale = ContentScale.Crop,
                // shows an image with a circular revealed animation.
            circularReveal = CircularReveal(duration = 250),
                // shows a placeholder ImageBitmap when loading.
            placeHolder = ImageBitmap.imageResource(R.drawable.avater),
                // shows an error ImageBitmap when the request failed.
            error = ImageBitmap.imageResource(id = R.drawable.avater)
            )

更多组件请访问LandScapist

llew8vvj

llew8vvj3#

对于那些想知道如何在不显式设置图像大小的情况下使图像变成方形(或圆形)的人,有Modifier.aspectRatio(1f)

vlf7wbxs

vlf7wbxs4#


我们可以使用修饰符中的***background字段***来实现这一点。

Image(
  painter = painterResource(id = R.drawable.ic_arrow_right),
  contentDescription = "",
  modifier = Modifier
             .padding(4.dp, 4.dp).background(colorResource(id = R.color.greenColor), CircleShape)
              .clip(CircleShape),
  colorFilter = ColorFilter.tint(colorResource(id = R.color.white)),
            contentScale = ContentScale.Crop,
 )

相关问题