0
0
Android Kotlinmobile~10 mins

Custom drawing (Canvas) in Android Kotlin - UI Render Trace

Choose your learning style9 modes available
Component - Custom drawing (Canvas)

This UI component uses a Canvas to draw custom shapes directly on the screen. It allows drawing lines, circles, and other shapes by controlling pixels, giving full freedom to create unique visuals beyond standard UI widgets.

Widget Tree
FrameLayout
└── CustomView (extends View)
    └── Canvas (used internally for drawing)
The root layout is a FrameLayout that holds a CustomView. The CustomView overrides the onDraw method and uses a Canvas object internally to draw shapes like circles and lines. This Canvas is not a widget but a drawing surface provided by the system.
Render Trace - 3 Steps
Step 1: FrameLayout
Step 2: CustomView
Step 3: Canvas (inside CustomView.onDraw)
State Change - Re-render
Trigger:Calling invalidate() on CustomView to refresh drawing
Before
Canvas shows red circle and blue diagonal line
After
Canvas redraws the same red circle and blue diagonal line
Re-renders:Only the CustomView's onDraw method is called to redraw the canvas
UI Quiz - 3 Questions
Test your understanding
What does the Canvas object do in the CustomView?
AIt manages user input events like clicks and touches
BIt provides a surface to draw shapes and lines directly on the screen
CIt arranges child views inside the CustomView
DIt loads images from the internet
Key Insight
Using Canvas for custom drawing lets you create unique visuals by controlling pixels directly. Remember to keep drawing code efficient and call invalidate() to refresh the view when needed. This approach is powerful for games, charts, or any custom graphics beyond standard UI widgets.