Monday, July 13, 2020

android kotlin - Paint gradient circle

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


class MainActivity : AppCompatActivity() {

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

        // show drawing on image view
        imageView.setImageBitmap(
            drawGradientCircle()
        )
    }
}


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

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

    // radius of circle and gradient
    val radius = min(canvas.width, canvas.height) / 2F - 25F

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

        // radial gradient shader
        shader = RadialGradient(
            canvas.width / 2F, // center x
            canvas.height / 2F, // center y
            radius, // radius
            intArrayOf( // colors
                Color.parseColor("#E30022"),
                Color.parseColor("#F7E7CE"),
                Color.parseColor("#FFF600")
            ),
            // stops - may be null, valid values are between 0.0f and 1.0f
            null,
            Shader.TileMode.MIRROR // shader titling mode
        )
    }

    // finally, draw gradient circle on canvas
    canvas.drawCircle(
        canvas.width / 2F, // cx
        canvas.height / 2F, // cy
        radius, // radius
        paint // paint to draw
    )

    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="#EDEAE0"
    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>