Sunday, July 12, 2020

android kotlin - Canvas draw text on path

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
import kotlin.math.min


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(drawTextOnPath())
    }
}



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


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


    // paint to draw path
    val paint = Paint().apply {
        isAntiAlias = true
        color = Color.parseColor("#333399")
        strokeWidth = 125F
        style = Paint.Style.STROKE
    }


    // add circle to path
    val path = Path()
    path.addCircle(
        canvas.width/2F,
        canvas.height/2F,
        min(canvas.width,canvas.height)/2 - 100F,
        Path.Direction.CCW
    )


    // draw path on canvas
    canvas.drawPath(path, paint)


    // text paint to draw text on path
    val textPaint = TextPaint().apply {
        isAntiAlias = true
        color = Color.parseColor("#F0FFFF")
        textSize = 80F
    }


    // finally, draw text on path
    canvas.drawTextOnPath(
        "Android Development", // text to draw
        path, // path the text should follow for its baseline
        //  distance along the path to add
        //  to the text's starting position
        1250F,
        // distance above(-) or below(+) the
        // path to position the text
        30F,
        textPaint // paint
    )

    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>