Skip to main content

How to add a border to an image in ImageView in Kotlin Android

How to add a border to an image in ImageView in Kotlin Android.

Here's a step-by-step tutorial on adding a border to an image in ImageView in Kotlin Android.

Step 1: Create a new Android project

Start by creating a new Android project in Android Studio. Give it a name and choose the appropriate settings for your project.

Step 2: Add an ImageView to your layout file

Open the activity_main.xml layout file and add an ImageView element. Set the desired width, height, and other attributes according to your requirements.

<ImageView
android:id="@+id/imageView"
android:layout_width="200dp"
android:layout_height="200dp"
android:src="@drawable/image"
android:scaleType="fitCenter"
android:padding="10dp" />

In this example, we've set the width and height to 200dp, and added a padding of 10dp to create space for the border.

Step 3: Create a border drawable resource file

Next, create a new XML file in the res/drawable directory and name it border.xml. This file will define the border style.

<shape xmlns:android="http://schemas.android.com/apk/res/android">
<stroke
android:width="2dp"
android:color="#FF0000" /> <!-- Set the border color here -->
</shape>

In this example, we've set the border width to 2dp and the border color to red (#FF0000). You can customize these values to your liking.

Step 4: Apply the border drawable to the ImageView

In your activity or fragment code, find the ImageView by its ID and set the border drawable as the background.

val imageView: ImageView = findViewById(R.id.imageView)
imageView.setBackgroundResource(R.drawable.border)

This sets the border.xml drawable as the background of the ImageView, effectively adding the border to the image.

Step 5: Run the app

Build and run your app on an emulator or device to see the result. The ImageView should now display the image with a border around it.

That's it! You have successfully added a border to an image in ImageView using Kotlin in Android. Feel free to customize the border style by modifying the border.xml file or the ImageView attributes.