Open In App

Draw a Line in Android using Jetpack Compose

Last Updated : 07 Mar, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

In Android, a Canvas is used when we need to draw objects of different shapes and types. Canvas is a class in Android that performs 2D drawings of different objects onto the screen. It can also be used for drawing a straight line between two given points. So in this article, we will show you how you could draw a straight line between two given points on the screen in Android using Jetpack Compose. Follow the below steps once the IDE is ready.

Step by Step Implementation

Step 1 : Create a New Project in Android Studio

To create a new project in the Android Studio, please refer to How to Create a new Project in Android Studio with Jetpack Compose.

Step 2 : Working with the MainActivity.kt file

Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.

MainActivity.kt:

package com.geeksforgeeks.demo

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.Surface
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import com.geeksforgeeks.demo.ui.theme.DemoTheme

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            DemoTheme(dynamicColor = false, darkTheme = false) {
                Surface(color = Color.White) {
                    DrawLine()
                }
            }
        }
    }
}

@Composable
fun DrawLine() {
    Column(
        Modifier.fillMaxSize(),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ) {

        // Creating a Canvas for drawing a straight
        // line between two points x and y
        Canvas(modifier = Modifier.fillMaxSize()) {

            // Fetching width and height for
            // setting start x and end y
            val canvasWidth = size.width
            val canvasHeight = size.height

            // drawing a line between start(x,y) and end(x,y)
            drawLine(
                start = Offset(x = canvasWidth, y = 0f),
                end = Offset(x = 0f, y = canvasHeight),
                color = Color.Red,
                strokeWidth = 5F
            )
        }
    }
}

Output:

draw-line-compose




Article Tags :

Similar Reads

three90RightbarBannerImg