Saturday, April 17, 2021

jetpack compose - Draw circle on canvas

MainActivity.kt

package com.cfsuman.jetpackcompose

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContent {
            MainContent()
        }
    }


    @Composable
    fun MainContent(){
        Canvas(
            modifier = Modifier
                .fillMaxSize()
                .background(Color(0xFFFAD6A5))
        )
        {
            val canvasWidth = size.width
            val canvasHeight = size.height

            drawCircle(
                color = Color(0xFFE12C2C),
                center = Offset(
                    x = canvasWidth - (canvasWidth / 3),
                    y = canvasHeight / 4
                ),
                radius = size.minDimension / 6
            )

            drawCircle(
                color = Color(0xFF4F42B5),
                center = Offset(
                    x = canvasWidth - (canvasWidth / 3) * 2,
                    y = canvasHeight - canvasHeight / 4
                ),
                radius = size.minDimension / 6
            )
        }
    }


    @Preview
    @Composable
    fun ComposablePreview(){
        //MainContent()
    }
}