How to show Border around Image in Android Jetpack Compose

By Mohammed Rashid •  September 4th, 2022 • 

Borders can make your UI elements distinct and beautiful. Let’s learn how to show a border around the image in this Android Jetpack Compose tutorial.

Image composable helps to display images and you can add border with the Modifier. See the code snippet given below.

@Composable
fun BorderImage() {
    Column() {
        Image(
            painter = painterResource(R.drawable.woman),
            contentDescription = "Image with Border",
            contentScale = ContentScale.Crop,
            modifier = Modifier
                .size(250.dp)
                .border(3.dp, Color.Red)
        )
    }
}

Following is the complete code.

package com.example.example
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.Image
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.size
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
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
import com.example.example.ui.theme.ExampleTheme

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            ExampleTheme {
                // A surface container using the 'background' color from the theme
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colors.background
                ) {
                    BorderImage()
                }
            }
        }
    }
}

@Preview(showBackground = true)
@Composable
fun BorderImage() {
    Column() {
        Image(
            painter = painterResource(R.drawable.woman),
            contentDescription = "Image with Border",
            contentScale = ContentScale.Crop,
            modifier = Modifier
                .size(250.dp)
                .border(3.dp, Color.Red)
        )
    }
}


@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
    ExampleTheme {
        BorderImage()
    }
}

Following is the output.

That’s how you add borders to an image in Jetpack Compose.

Mohammed Rashid

Keep Reading