android kotlin - Canvas draw text rotate

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)


        // draw rotated text on canvas
        imageView.setImageBitmap(drawTextRotate())
    }
}



// function to draw text rotate on canvas
fun drawTextRotate():Bitmap?{
    val bitmap = Bitmap.createBitmap(
        1500,
        850,
        Bitmap.Config.ARGB_8888
    )


    // canvas to draw text
    val canvas = Canvas(bitmap).apply {
        drawColor(Color.parseColor("#A2A2D0"))
    }


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


    // text margin
    val margin = 50F


    // rotate canvas 90 degrees
    canvas.save()
    canvas.rotate(90F)
    canvas.drawText(
        "Angle 90 degrees",
        canvas.height / 2F,
        - margin,
        paint
    )


    // save canvas before restore
    canvas.restore() // restore canvas
    canvas. save()


    // change text color
    paint.apply {
        color = Color.parseColor("#333399")
    }


    // rotate canvas -90 degrees
    canvas.rotate(-90F)
    canvas.drawText(
        "Angle -90 degrees",
        -canvas.height / 2F,
        canvas.width - margin,
        paint
    )

    canvas.restore() // restore canvas
    canvas.save() // save canvas state


    // change text color
    paint.apply {
        color = Color.parseColor("#333399")
    }


    // draw text with no angle
    canvas.drawText(
        "Normal Text",
        canvas.width / 2F,
        canvas.height / 2F,
        paint
    )
    canvas.save()

    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>
More android kotlin tutorials