I can't find the onDraw()
method in Component. Can someone explain to me how to override the onDraw method for Component in Harmony OS?
Asked
Active
Viewed 191 times
1

zhangxaochen
- 32,744
- 15
- 77
- 108

Shrey Shrivastava
- 51
- 3
2 Answers
0
- First you have to implement Component.DrawTask to your custom Component, Then you will be able to override onDraw() and perform custom Drawing operations. For Example,
public class CustomComponent extends Component implements Component.DrawTask {
public CustomComponent(Context context) {
super(context);
// DrawTask
addDrawTask(this::onDraw);
}
@Override
public void onDraw(Component component, Canvas canvas) {
...
}
}

Gowtham GS
- 478
- 2
- 5
0
Implement the Component.DrawTask
interface, and execute the draw task using the onDraw
method. You can use the Canvas
provided by this method to accurately control the appearance of UI elements. Before executing a draw task, you need to define a Paint
.
The sample code is as follows:
public class CustomComponent extends Component implements Component.DrawTask,Component.EstimateSizeListener {
// Circle width
private static final float CIRCLE_STROKE_WIDTH = 100f;
// Paint for drawing the circle
private Paint circlePaint;
public CustomComponent(Context context) {
super(context);
// Initialize the Paint.
initPaint();
// Add a draw task.
addDrawTask(this);
}
private void initPaint(){
circlePaint = new Paint();
circlePaint.setColor(Color.BLUE);
circlePaint.setStrokeWidth(CIRCLE_STROKE_WIDTH);
circlePaint.setStyle(Paint.Style.STROKE_STYLE);
}
@Override
public void onDraw(Component component, Canvas canvas) {
// Draw a circle whose center coordinate is (500,500) and radius is 400.
canvas.drawCircle(500,500,400,circlePaint);
}
...
}
For details about the override onDraw()
method in Harmony OS, pls kindly refer to the Docs.

zhangxaochen
- 32,744
- 15
- 77
- 108