Skip to main content

How to create a circular ImageView in Kotlin Android

How to create a circular ImageView in Kotlin Android.

Here's a step-by-step tutorial on how to create a circular ImageView in Kotlin for Android:

Step 1: Create a new Android project

Start by creating a new Android project in Android Studio. Choose an appropriate project name and package name according to your preference.

Step 2: Add ImageView to your layout XML

Open the XML file for the layout where you want to add the circular ImageView. Inside the layout tags, add the following code:

<ImageView
android:id="@+id/circularImageView"
android:layout_width="200dp"
android:layout_height="200dp"
android:src="@drawable/image"
android:scaleType="centerCrop"
android:layout_gravity="center"
android:background="@drawable/circular_background" />

In this code snippet, we have added an ImageView with an id of "circularImageView". Adjust the width and height according to your requirements. The src attribute specifies the image you want to display, and the scaleType attribute determines how the image should be scaled to fit the ImageView. The layout_gravity attribute centers the ImageView within its parent, and the background attribute sets a circular background for the ImageView.

Step 3: Create a circular background drawable

Create a new XML file in the res/drawable directory and name it "circular_background.xml". Add the following code to create a circular shape:

<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<solid android:color="#FF0000" />
</shape>

In this code snippet, we are using an oval shape and setting the solid color to red (#FF0000). You can change the color code to any color of your choice.

Step 4: Convert ImageView to a circular shape programmatically

Open the Kotlin file for the activity or fragment where you want to use the circular ImageView. Inside the onCreate method, add the following code:

val circularImageView: ImageView = findViewById(R.id.circularImageView)
val circularBitmapDrawable: RoundedBitmapDrawable = RoundedBitmapDrawableFactory.create(resources, yourBitmap)
circularBitmapDrawable.isCircular = true
circularImageView.setImageDrawable(circularBitmapDrawable)

Replace "yourBitmap" with the Bitmap you want to display in the circular ImageView. This code creates a RoundedBitmapDrawable from the given Bitmap and sets its isCircular property to true. Finally, the circularImageView is updated with the circularBitmapDrawable.

Step 5: Run the app

Build and run your Android app on a device or emulator to see the circular ImageView in action. The ImageView should now display the specified image in a circular shape.

That's it! You have successfully created a circular ImageView in Kotlin for your Android app. Feel free to customize the size, shape, and appearance of the ImageView according to your needs.