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

Val*_*kov 5 android android-jetpack android-jetpack-compose

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

在此处输入图片说明

Val*_*kov 36

有一个剪辑修饰符可以应用于任何可组合以及Image,只需将 a 传递给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)
)
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

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

在此处输入图片说明


Eyj*_*afl 6

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


Jam*_*guo 5

另外,您可以尝试

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)
            )
Run Code Online (Sandbox Code Playgroud)

欲了解更多组件,请访问LandScapist