0
0
Android Kotlinmobile~7 mins

Surface and shape in Android Kotlin

Choose your learning style9 modes available
Introduction

Surfaces and shapes help you create and control the look of your app's screen and elements. They make your app look nice and easy to use.

When you want to draw custom shapes like circles or rectangles on the screen.
When you need to create a background with rounded corners or shadows.
When you want to control how your app's UI elements appear and respond visually.
When you want to use a Canvas to draw graphics in your app.
When you want to create a custom view with a specific shape or style.
Syntax
Android Kotlin
val surfaceView = SurfaceView(context)
surfaceView.holder.addCallback(object : SurfaceHolder.Callback {
  override fun surfaceCreated(holder: SurfaceHolder) {
    val canvas = holder.lockCanvas()
    canvas.drawColor(Color.WHITE)
    val paint = Paint().apply {
      color = Color.RED
      style = Paint.Style.FILL
    }
    canvas.drawCircle(100f, 100f, 50f, paint)
    holder.unlockCanvasAndPost(canvas)
  }
  override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {}
  override fun surfaceDestroyed(holder: SurfaceHolder) {}
})

SurfaceView provides a dedicated drawing surface embedded inside your app's view hierarchy.

You use SurfaceHolder.Callback to know when the surface is ready to draw on.

Examples
This draws a blue oval shape on the canvas.
Android Kotlin
val shapeDrawable = ShapeDrawable(OvalShape())
shapeDrawable.paint.color = Color.BLUE
shapeDrawable.setBounds(50, 50, 200, 200)
shapeDrawable.draw(canvas)
This draws a rectangle with rounded corners.
Android Kotlin
val rect = RectF(10f, 10f, 150f, 150f)
canvas.drawRoundRect(rect, 20f, 20f, paint)
Sample App

This custom SurfaceView draws a green rectangle on a white background when the surface is ready.

Android Kotlin
class MySurfaceView(context: Context) : SurfaceView(context), SurfaceHolder.Callback {
  private val paint = Paint().apply {
    color = Color.GREEN
    style = Paint.Style.FILL
  }

  init {
    holder.addCallback(this)
  }

  override fun surfaceCreated(holder: SurfaceHolder) {
    val canvas = holder.lockCanvas()
    canvas.drawColor(Color.WHITE)
    canvas.drawRect(50f, 50f, 250f, 150f, paint)
    holder.unlockCanvasAndPost(canvas)
  }

  override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {}
  override fun surfaceDestroyed(holder: SurfaceHolder) {}
}
OutputSuccess
Important Notes

Always unlock the canvas after drawing to display your changes.

SurfaceView is useful for animations or games where you need fast drawing.

Use Paint to set colors, styles, and effects for your shapes.

Summary

SurfaceView gives you a special area to draw graphics directly.

Use shapes and Paint to create colorful and styled drawings.

Remember to manage the surface lifecycle with SurfaceHolder.Callback.