Saturday, July 11, 2020

android kotlin - Canvas draw multiple lines

MainActivity.kt

package com.example.jetpack

import android.graphics.*
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*


class MainActivity : AppCompatActivity() {

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

        // 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("#E9D66B"))
    }

    val paint = Paint().apply {
        color = Color.parseColor("#545AA7")
        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"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/constraintLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#F2E8D7"
    tools:context=".MainActivity">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="2dp"
        android:layout_marginEnd="8dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:srcCompat="@tools:sample/avatars" />

</androidx.constraintlayout.widget.ConstraintLayout>