【问题标题】:How to override the onDraw() function in Component for Harmony OS?如何覆盖 Harmony OS 组件中的 onDraw() 函数?
【发布时间】:2021-07-31 05:23:13
【问题描述】:

我在组件中找不到onDraw() 方法。有人可以向我解释如何在 Harmony OS 中覆盖组件的 onDraw 方法吗?

【问题讨论】:

    标签: java android huawei-mobile-services huawei-developers harmonyos


    【解决方案1】:
    1. 首先您必须在您的自定义组件中实现 Component.DrawTask,然后您将能够覆盖 onDraw() 并执行自定义绘图操作。例如,
     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) {
            ...
        }
    
     }
    

    【讨论】:

      【解决方案2】:

      实现Component.DrawTask接口,使用onDraw方法执行绘制任务。您可以使用该方法提供的Canvas 来精确控制UI 元素的外观。在执行绘制任务之前,需要定义一个Paint

      示例代码如下:

      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);
          }
      
          ...
      }
      

      关于Harmony OS中覆盖onDraw()方法的详细信息,请参考Docs

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-01-29
        • 1970-01-01
        • 2017-05-29
        • 2017-04-20
        • 2020-08-29
        • 2019-09-05
        • 1970-01-01
        • 2015-10-02
        相关资源
        最近更新 更多