Sunday, April 18, 2021

jetpack compose - Draw image 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.*
import androidx.compose.ui.res.imageResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp

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

        setContent {
            MainContent()
        }
    }


    @Composable
    fun MainContent(){
        Canvas(
            modifier = Modifier
                .fillMaxSize()
                .background(Color(0xFFA17A74))
        )
        {
            drawImage(
                image = ImageBitmap.imageResource(
                    res = resources,
                    id = R.drawable.flower9
                ),
                topLeft = Offset(
                    x = 25.dp.toPx(),
                    y = 25.dp.toPx()
                ),
                colorFilter = ColorFilter.tint(
                    color = Color(0xFFFFAA1D),
                    blendMode = BlendMode.ColorBurn
                )
            )
        }
    }


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