How to Draw Oval Shape Using Canvas in Android Jetpack Compose

By Mohammed Rashid •  Updated on: February 22nd, 2023 • 

Canvas is a powerful tool that allows developers to create and manipulate 2D graphics in their Android apps. It provides a surface on which to perform drawing operations, such as drawing shapes, lines, and images.

In this blog post, let’s learn how to draw an oval using Canvas in Jetpack Compose. See the code snippet given below.

Canvas(modifier = Modifier.fillMaxSize()) {
        val canvasWidth = size.width
        val canvasHeight = size.height
        drawOval(
            color = Color.Red,
            topLeft = Offset(x = canvasWidth / 4, y = canvasHeight / 3),
            size = Size(height = 300F, width = 500F),
        )
    }

We the drawOval function provided by Canvas. This function is used to draw an oval shape on the Canvas. Here we used the following parameters.

You will get the following output.

jetpack compose canvas draw oval

Following is the complete code.

package com.example.myapplication

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import com.example.myapplication.ui.theme.MyApplicationTheme

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MyApplicationTheme {
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colorScheme.background
                ) {
                    CanvasExample()
                }
            }
        }
    }
}

@Composable
fun CanvasExample() {
    Canvas(modifier = Modifier.fillMaxSize()) {
        val canvasWidth = size.width
        val canvasHeight = size.height
        drawOval(
            color = Color.Red,
            topLeft = Offset(x = canvasWidth / 4, y = canvasHeight / 3),
            size = Size(height = 300F, width = 500F),
        )
    }
}

@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
    MyApplicationTheme {
        CanvasExample()
    }
}

That’s how you draw oval shapes using Canvas in Jetpack Compose.

Keep Reading