Sobes.tech
Junior

What is Canvas in Android?

sobes.tech AI

Answer from AI

Canvas in Android is a surface for drawing. It provides methods to draw primitive graphics (points, lines, rectangles, circles, text, images) on a bitmap or another surface.

Main concepts:

  • Drawing: Canvas offers APIs for drawing operations like drawPoint(), drawLine(), drawRect(), drawCircle(), drawText(), drawBitmap().
  • Coordinate system: Uses a 2D coordinate system with (0,0) at the top-left corner.
  • State: Canvas has a state including current transformations (translate, scale, rotate) and clip region, which can be saved and restored (save() and restore()).
  • Paint: Paint objects define style (color, stroke width, shading, fonts). Canvas uses the current Paint for each drawing operation.

Example in custom View:

// Inside onDraw()
public void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    // Create a Paint object
    Paint paint = new Paint();
    paint.setColor(Color.RED); // Set color

    // Draw rectangle
    canvas.drawRect(10, 10, 100, 100, paint);

    // Draw circle
    paint.setColor(Color.BLUE);
    canvas.drawCircle(150, 150, 50, paint);

    // Draw text
    paint.setColor(Color.BLACK);
    paint.setTextSize(30);
    canvas.drawText("Hello, Canvas!", 10, 200, paint);
}

Canvas is closely related to View objects. When the system draws a View, it creates a Canvas and passes it to onDraw(). The View then uses this Canvas to draw its content.