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(
drawLinearGradient()
)
}
}
// function to draw linear gradient on canvas
fun drawLinearGradient():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 linear gradient
val paint = Paint().apply {
isAntiAlias = true
style = Paint.Style.FILL
// linear gradient shader
shader = LinearGradient(
// x0, x-coordinate for the start of the gradient line
0F,
// y0, y-coordinate for the start of the gradient line
0F,
// x1, x-coordinate for the end of the gradient line
rectF.width(),
// y1, y-coordinate for the end of the gradient line
rectF.height(),
// color0, sRGB color at the start of the gradient line
Color.parseColor("#00CC99"),
// color1, sRGB color at the end of the gradient line
Color.parseColor("#E30022"),
// shader tiling mode
Shader.TileMode.MIRROR
)
}
// finally, draw linear gradient rectangle on canvas
canvas.drawRect(rectF, 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>
- android kotlin - Get app first install time
- android kotlin - Detect screen orientation change
- android kotlin - Convert dp to pixels programmatically
- android kotlin - RecyclerView horizontal
- android kotlin - GridView item height
- android kotlin - CheckBox checked change listener
- android kotlin - RadioButton circle color programmatically
- android kotlin - TextView margin programmatically
- android kotlin - Coroutines start undispatched
- android kotlin - Coroutines delay
- android kotlin - Paint gradient path
- android kotlin - Paint gradient circle
- android kotlin - Canvas draw point
- android kotlin - Canvas erase drawing
- android kotlin - Canvas draw text shadow