How to create circular imageview with Jetpack compose?
Last updated Aug 08, 2021 In this Jetpack compose tutorial we will learn how to create circular imageview in Android application.
Circular Image View is used in many of the apps. These types of images are generally used to represent the profile picture of the user and many more images.
Let's say I have a rectangular image like the one below, how can I force it to be drawn as a circle in Jetpack Compose?
Let's get started
Step 1: Create android application in android studio
Step 2: Follow step for setup Jetpack Compose with Android Studio
Step 3: let us display an Image with circular shape. Add Circular Image In MainActivity.kt.
There's a clip modifier which can be applied to any composable as well as the Image, just pass a CicularShape into it:
package com.example.jetpack
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MaterialTheme {
// A surface container using the 'background' color from the theme
Surface(color = MaterialTheme.colors.background) {
CircularImageViewDemo()
}
}
}
}
}
@Composable
fun CircularImageViewDemo() {
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Image(
painter = painterResource(R.drawable.image1),
contentDescription = "avatar",
contentScale = ContentScale.Crop,
// crop the image if it's not a square
modifier = Modifier
.size(100.dp)
// clip to the circle shape
.clip(CircleShape)
// add a border (optional)
.border(2.dp, Color.Gray, CircleShape)
)
}
}
@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
CircularImageViewDemo()
}
|
Image
Conclusion: In this compose tutorial we covered how to create a circular imageview in android studio.