Monday, July 13, 2020

android kotlin - Canvas draw dashed line

MainActivity.kt

package com.cfsuman.kotlintutorials

import android.app.Activity
import android.graphics.*
import android.os.Bundle
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(drawDashedLine())
    }
}



// function to draw dashed line on canvas
fun drawDashedLine():Bitmap?{
    val bitmap = Bitmap.createBitmap(
        1500,
        850,
        Bitmap.Config.ARGB_8888
    )


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


    // paint to draw dashed line
    val paint = Paint().apply {
        isAntiAlias = true
        color = Color.parseColor("#333399")

        strokeWidth = 25F
        style = Paint.Style.STROKE

        pathEffect = DashPathEffect(
            // array of ON and OFF distances
            floatArrayOf(20F, 30F, 40F, 50F),
            0F // phase : offset into the intervals array
        )
    }


    // draw a line path
    val path = Path().apply {
        // move to line starting point
        moveTo(100F,100F)

        // draw line
        // add a quadratic bezier
        quadTo(
            100F,
            100F,
            canvas.width - 100F,
            canvas.height - 100F
        )
    }


    // finally, draw the path (dashed line) on canvas
    canvas.drawPath(path, 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>