Saturday, July 11, 2020

android kotlin - Canvas draw multiple lines

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



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


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


    val paint = Paint().apply {
        color = Color.parseColor("#333399")
        strokeWidth = 25F
        style = Paint.Style.STROKE
        strokeCap = Paint.Cap.SQUARE
        strokeMiter = 20F
    }


    // list to hold lines xy positions
    val list = mutableListOf<Float>()


    // first line starting point x y
    list.add(50F) // x
    list.add(50F) // y

    // first line ending point x y
    list.add(canvas.width / 2F - 200)
    list.add(canvas.height / 2F)


    // second line starting x y
    list.add(canvas.width / 2F - 200)
    list.add(canvas.height / 2F)

    // second line ending point x y
    list.add(50F)
    list.add(canvas.height - 50F)


    // third line starting point x y
    list.add(canvas.width - 50F)
    list.add(50F)

    // third line ending point x y
    list.add(canvas.width / 2f + 200)
    list.add(canvas.height / 2F)


    // fourth line starting point x y
    list.add(canvas.width / 2f + 200)
    list.add(canvas.height / 2F)

    // fourth line ending point x y
    list.add(canvas.width - 50F)
    list.add(canvas.height - 50F)


    // finally, draw lines on canvas
    canvas.drawLines(
        list.toFloatArray(), 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>