Monday, April 19, 2021

jetpack compose - Draw text on canvas

MainActivity.kt

package com.cfsuman.jetpackcompose

import android.graphics.Paint
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.graphics.Color
import androidx.compose.ui.graphics.nativeCanvas
import androidx.compose.ui.graphics.toArgb
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(0xFFE6E6FA))
        )
        {
            val paint = Paint().apply {
                textAlign = Paint.Align.CENTER
                textSize = 300f
                color = Color(0xFF0018A8).toArgb()
            }

            drawContext.canvas.nativeCanvas.drawText(
                "Android",
                center.x,
                center.y,
                paint
            )
        }
    }


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