Junior — Middle
Could you explain what operations the onDraw method performs in the View component during rendering?
sobes.tech AI
Answer from AI
The onDraw(Canvas canvas) method in Android is called by the system to draw the contents of a View component. In this method:
- You obtain a Canvas object on which you can draw.
- You perform drawing operations: rendering text, shapes, images, etc.
- You use Paint to set colors, styles, and other drawing parameters.
For example, if you want to draw a circle, override onDraw like this:
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Paint paint = new Paint();
paint.setColor(Color.RED);
canvas.drawCircle(getWidth() / 2, getHeight() / 2, 50, paint);
}
It is important to call super.onDraw(canvas) if the base class implements any drawing, to preserve the default behavior.