Tuesday, July 14, 2020

android kotlin - Paint gradient path

MainActivity.kt

package com.cfsuman.kotlintutorials

import android.app.Activity
import android.graphics.*
import android.os.Bundle
import android.widget.*


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



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


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


    // initialize a rectF instance
    val margin = 50F
    val rectF = RectF(
        margin, // left
        margin, // top
        canvas.width - margin, // right
        canvas.height - margin // bottom
    )


    // paint to draw sweep gradient
    val paint = Paint().apply {
        isAntiAlias = true
        style = Paint.Style.FILL

        // sweep gradient shader
        shader = SweepGradient(
            rectF.width() / 2F, // cx, x-coordinate of the center
            rectF.height() / 2F, // cy, y-coordinate of the center
            // sRGB colors to be distributed between around the center
            intArrayOf(
                Color.parseColor("#D92121"),
                Color.parseColor("#5A4FCF"),
                Color.parseColor("#98FF98"),
                Color.parseColor("#EAA221"),
                Color.parseColor("#FFDB58")
            ),
            // relative position of each corresponding
            // color in the colors array
            null
        )
    }


    // make a rounded rectangle path
    val path = Path().apply {
        addRoundRect(
            rectF,
            100F,
            100F,
            Path.Direction.CCW
        )
    }


    // finally, draw sweep gradient path 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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/rootLayout"
    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>