0
0
Android Kotlinmobile~5 mins

Custom drawing (Canvas) in Android Kotlin

Choose your learning style9 modes available
Introduction

Custom drawing lets you create your own shapes and designs on the screen. It helps make your app look unique and show things that built-in widgets can't.

You want to draw a simple shape like a circle or rectangle that changes color.
You need to create a custom graph or chart that shows data visually.
You want to make a game with moving objects drawn on the screen.
You want to add decorations or patterns that are not standard UI elements.
Syntax
Android Kotlin
class MyView(context: Context) : View(context) {
  override fun onDraw(canvas: Canvas) {
    super.onDraw(canvas)
    // Your drawing code here
  }
}
Override the onDraw() method to do your custom drawing.
Use the Canvas object to draw shapes, text, or images.
Examples
This draws a red circle on a white background.
Android Kotlin
override fun onDraw(canvas: Canvas) {
  super.onDraw(canvas)
  canvas.drawColor(Color.WHITE) // Fill background
  val paint = Paint().apply {
    color = Color.RED
    style = Paint.Style.FILL
  }
  canvas.drawCircle(100f, 100f, 50f, paint)
}
This draws a blue rectangle outline.
Android Kotlin
override fun onDraw(canvas: Canvas) {
  super.onDraw(canvas)
  val paint = Paint().apply {
    color = Color.BLUE
    strokeWidth = 5f
    style = Paint.Style.STROKE
  }
  canvas.drawRect(50f, 50f, 200f, 200f, paint)
}
Sample App

This custom view fills the background with light gray and draws a big magenta circle in the center of the screen.

Android Kotlin
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.view.View

class CustomDrawingView(context: Context) : View(context) {
  private val paint = Paint().apply {
    color = Color.MAGENTA
    style = Paint.Style.FILL
  }

  override fun onDraw(canvas: Canvas) {
    super.onDraw(canvas)
    canvas.drawColor(Color.LTGRAY) // Light gray background
    canvas.drawCircle(width / 2f, height / 2f, 150f, paint) // Big magenta circle in center
  }
}
OutputSuccess
Important Notes

Always call super.onDraw(canvas) first to keep default drawing behavior.

Use Paint to set color, style, and stroke width for your shapes.

Coordinates and sizes are in pixels as floats, with (0,0) at top-left.

Summary

Custom drawing uses the onDraw() method and Canvas to draw shapes.

Paint controls how your shapes look (color, fill, stroke).

This lets you create unique visuals beyond standard UI components.