Sunday, July 12, 2020

android kotlin - Canvas draw text shadow

MainActivity.kt

package com.cfsuman.kotlintutorials

import android.app.Activity
import android.graphics.*
import android.os.Bundle
import android.text.TextPaint
import android.widget.ImageView


class MainActivity : Activity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // get the widgets reference from XML layout
        val imageView = findViewById<ImageView>(R.id.imageView)


        // show drawing on image view
        imageView.setImageBitmap(drawTextShadow())
    }
}



// function to draw text shadow on canvas
fun drawTextShadow():Bitmap?{
    val bitmap = Bitmap.createBitmap(
        1400,
        900,
        Bitmap.Config.ARGB_8888
    )


    // canvas for drawing
    val canvas = Canvas(bitmap).apply {
        drawColor(Color.parseColor("#A2A2D0"))
    }


    // text paint to draw text
    val textPaint = TextPaint().apply {
        isAntiAlias = true
        color = Color.parseColor("#333399")
        textSize = 280F
        textAlign = Paint.Align.CENTER
        typeface = Typeface.DEFAULT_BOLD

        // This draws a shadow layer below the main layer,
        // with the specified offset and color, and blur radius.
        setShadowLayer(
            20F, // radius
            5F, // dx
            5F, // dy
            Color.parseColor("#333399") // color
        )
    }


    // calculate center position to draw text on canvas
    val x = canvas.width / 2F
    val y = (canvas.height /2 ) - (textPaint.descent()
            + textPaint.ascent()) / 2


    // finally, draw text with shadow on canvas
    canvas.drawText(
        "ANDROID",
        x,
        y,
        textPaint
    )

    return bitmap
}
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/rootLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#DCDCDC"
    android:padding="24dp">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>