package com.example.customdrawing
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View
class CustomDrawingView @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null
) : View(context, attrs) {
private val paint = Paint().apply {
isAntiAlias = true
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
// Set background color to white
canvas.drawColor(Color.WHITE)
// Draw blue circle
paint.color = Color.BLUE
val circleRadius = width.coerceAtMost(height) / 6f
val circleX = width / 2f
val circleY = circleRadius + 20f
canvas.drawCircle(circleX, circleY, circleRadius, paint)
// Draw red rectangle below the circle
paint.color = Color.RED
val rectLeft = width / 4f
val rectTop = circleY + circleRadius + 20f
val rectRight = width * 3 / 4f
val rectBottom = rectTop + circleRadius
canvas.drawRect(rectLeft, rectTop, rectRight, rectBottom, paint)
}
}We override onDraw to do custom drawing on the canvas.
First, we fill the background with white using canvas.drawColor(Color.WHITE).
Then, we draw a blue circle centered horizontally near the top. We calculate the radius as one-sixth of the smaller dimension and position it with some padding.
Below the circle, we draw a red rectangle spanning the middle half of the width and with height equal to the circle's radius, positioned with some spacing.
We use a single Paint object and change its color before each shape.