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:
Canvasoffers APIs for drawing operations likedrawPoint(),drawLine(),drawRect(),drawCircle(),drawText(),drawBitmap(). - Coordinate system: Uses a 2D coordinate system with (0,0) at the top-left corner.
- State:
Canvashas a state including current transformations (translate, scale, rotate) and clip region, which can be saved and restored (save()andrestore()). - Paint:
Paintobjects define style (color, stroke width, shading, fonts).Canvasuses the currentPaintfor 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.