如何通过定时器和画布实现一个时钟

通过定时器和画布实现一个时钟

HarmonyOS
2024-05-26 17:20:51
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
克里斯蒂东

使用的核心API

使用该画布作为绘制表盘、时针、分针及秒针。

Canvas(this.renderContext) 
  .width(this.canvasSize) 
  .aspectRatio(1) 
  .onReady(() => { 
    if (this.drawInterval === -1) { 
 
      this.startDrawTask(); 
    } 
  })

通过定时器每秒钟执行一次绘制任务,使时钟动起来。

this.timeId = setInterval(()=>{ 
  this.startDrawTask(); 
},1000)

核心代码解释

@Entry 
@Component 
struct ClockCard { 
  /* 
   * The action type. 
   */ 
  readonly ACTION_TYPE: string = 'router'; 
  /* 
   * The ability name. 
   */ 
  readonly ABILITY_NAME: string = 'EntryAbility'; 
  /* 
   * The message. 
   */ 
  readonly MESSAGE: string = 'add detail'; 
  /* 
   * The width percentage setting. 
   */ 
  readonly FULL_WIDTH_PERCENT: string = '100%'; 
  /* 
   * The height percentage setting. 
   */ 
  readonly FULL_HEIGHT_PERCENT: string = '100%'; 
  private settings: RenderingContextSettings = new RenderingContextSettings(true); 
  private renderContext: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); 
  private drawInterval: number = -1; 
  private canvasSize: number = 100; 
  private clockRadius: number = 0; 
  timeId: number = -1; 
 
  aboutToAppear() { 
    // 根据canvasSize初始化clockRadius 
    this.clockRadius = this.canvasSize / 2 - 2; 
  } 
 
  aboutToDisappear() { 
    // clearInterval(this.drawInterval); 
  } 
 
  onPageShow(): void { 
    //指针移动角度 
    this.timeId = setInterval(() => { 
      this.startDrawTask(); 
    }, 1000) 
  } 
 
  build() { 
    Column() { 
      Canvas(this.renderContext) 
        .width(this.canvasSize) 
        .aspectRatio(1) 
        .onReady(() => { 
          if (this.drawInterval === -1) { 
            this.renderContext.translate( 
              this.canvasSize / 2, // 126 
              this.canvasSize / 2); 
            console.log('画布画图'); 
          } 
        }) 
      Column({ space: 3 }) { 
        Text(DateUtil.getWeek()) 
          .letterSpacing(1) 
          .fontSize(10) 
          .fontWeight(FontWeight.Bolder) 
        Text(DateUtil.getYearAndMonthAndDay()) 
          .fontWeight(1) 
          .fontSize(10) 
          .letterSpacing(1) 
      } 
      .margin({ top: 5 }) 
    } 
    .margin({ top: 10 }) 
    .width("100%") 
    .height("100%") 
    .backgroundColor(Color.White) 
    .onClick(() => { 
      postCardAction(this, { 
        action: this.ACTION_TYPE, 
        abilityName: this.ABILITY_NAME, 
        params: { 
          message: this.MESSAGE 
        } 
      }); 
    }) 
  } 
 
  // 启动绘画任务 
  private startDrawTask() { 
    let that = this; 
    // translate() 方法,将 canvas 按原始 x 点的水平方向、原始的 y 点垂直方向进行平移变换 
    /*that.renderContext.translate( 
      this.canvasSize / 2, // 126 
      this.canvasSize / 2); // 126*/ 
    that.drawClockArea(); 
    // this.drawInterval = setInterval(() => { 
    //   that.drawClockArea(); 
    // }, 1000);// 1000毫秒,即一秒钟绘画一次 
  } 
 
  // 开始绘制时钟区域 
  private drawClockArea(): void { 
    // clearRect() 方法在一个矩形区域内设置所有像素都是透明的 (rgba(0,0,0,0))。这个矩形范围的左上角在 (x, y),宽度和高度分别由width和height确定。 
    this.renderContext.clearRect( 
      -this.canvasSize, // -252 
      -this.canvasSize / 2, // -126 
      this.canvasSize * 2, // 504 
      this.canvasSize); // 252 
 
    // 设置时间 
    let date = new Date(); 
    let hour = date.getHours(); 
    let minute = date.getMinutes(); 
    let second = date.getSeconds(); 
    this.drawClock(hour, minute, second); 
  } 
 
  private drawClock(hour: number, minute: number, second: number): void { 
 
    // 绘制表盘 
    this.drawPan(); 
    // 绘制时针 
    this.drawPointer( 
      30 * (hour > 12 
        ? hour - 12 
        : hour) 
        + minute / 12 * 6 
      , '/common/images/ic_hour_pointer.png'); 
    // 绘制分针 
    this.drawPointer(6 * minute, '/common/images/ic_minute_pointer.png'); 
    // 绘制秒针 
    this.drawPointer(6 * second, '/common/images/ic_second_pointer.png'); 
  } 
 
  // 绘制表盘 
  private drawPan(): void { 
    this.renderContext.beginPath(); 
    let secondImg = new ImageBitmap('/common/images/ic_clock_pan.png'); 
    let imgWidth = this.clockRadius * 2; // 248 
    this.renderContext.drawImage(secondImg, -this.clockRadius, -this.clockRadius, imgWidth, imgWidth); 
    this.renderContext.restore(); 
  } 
 
  // 绘制时钟的针 
  private drawPointer(degree: number, pointerImgRes: string) { 
    this.renderContext.save(); 
    let theta = (degree + 180) * Math.PI / 180; 
    this.renderContext.rotate(theta); 
 
    this.renderContext.beginPath(); 
    let secondImg = new ImageBitmap(pointerImgRes); 
    let imgWidth = 4; 
    this.renderContext.drawImage( 
      secondImg, 
      -imgWidth / 2, 
      -this.clockRadius, 
      imgWidth, 
      this.clockRadius * 2); 
    this.renderContext.restore(); 
  } 
} 
 
export default class DateUtil { 
  private static date: Date = new Date(); 
 
  public static getMonth(): number { 
 
    return DateUtil.date.getMonth() + 1; 
  } 
 
  public static getYearAndMonthAndDay(): string { 
 
    return DateUtil.date.getFullYear() + "年" 
      + DateUtil.getMonth() + '月' 
      + DateUtil.date.getDate() + '日'; 
  } 
 
  public static getWeek() { 
 
    let week: string = ""; 
    let weekDay: number = DateUtil.date.getDay(); 
    switch (weekDay) { 
      case 0: 
        week = '星期天'; 
        break; 
      case 1: 
        week = '星期一'; 
        break; 
      case 2: 
        week = '星期二'; 
        break; 
      case 3: 
        week = '星期三'; 
        break; 
      case 4: 
        week = '星期四'; 
        break; 
      case 5: 
        week = '星期五'; 
        break; 
      case 6: 
        week = '星期六'; 
        break; 
      default: 
        "未识别"; 
    } 
 
    return week; 
  } 
}

实现效果

分享
微博
QQ
微信
回复
2024-05-27 22:01:58
相关问题
如何设置组件定时任务定时器
519浏览 • 1回复 待解决
HarmonyOS 定时器API
195浏览 • 1回复 待解决
HarmonyOS uv timer定时器不准确?
328浏览 • 1回复 待解决
鸿蒙里如何实现一个本地定时通知?
159浏览 • 0回复 待解决
鸿蒙liteos_m定时器timer问题
8052浏览 • 2回复 待解决
有谁知道ArkTS支持定时器
2715浏览 • 1回复 待解决
如何实现一个倒计时
447浏览 • 1回复 待解决
怎样实现一个自定义播放
361浏览 • 1回复 待解决
如何实现一个折叠组件
990浏览 • 1回复 待解决
HarmonyOS 如何实现一个遮罩层
442浏览 • 1回复 待解决
如何实现一个下拉菜单?
622浏览 • 1回复 待解决
HarmonyOS 如何实现一个转圈效果
715浏览 • 2回复 待解决