Friday, April 16, 2021

jetpack compose - Draw line 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.graphics.StrokeCap
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(0xFFACE5EE))
        )
        {
            val canvasWidth = size.width
            val canvasHeight = size.height

            drawLine(
                color = Color(0xFF0018A8),
                start = Offset(x = 100F, y = 100F),
                end = Offset(x = canvasWidth - 100F, y = canvasHeight - 100F),
                strokeWidth = 50F,
                cap = StrokeCap.Round
            )
        }
    }


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