实现类似人脸认证时中间镂空,四周颜色变换闪烁的效果?

如题:实现类似人脸认证时中间镂空,四周颜色变换闪烁的效果?

阅读 264
1 个回答

功能场景描述及使用场景

实现类似人脸认证那种中间镂空,四周颜色变换闪烁的效果

使用的核心API

OffscreenCanvasRenderingContext2D.clearRect(x: number, y: number, w: number, h: number): void

OffscreenCanvasRenderingContext2D.beginPath(): void

OffscreenCanvasRenderingContext2D.lineTo(x: number, y: number): void

OffscreenCanvasRenderingContext2D.stroke(path?: Path2D): void

核心代码解释

画图思路 : 1.清空画布;2.设置填充颜色;3.开始路径 移动画笔到左上角,开始画外框;4.移动画笔到圆开始的地方,开始画圆(圆从右边起来开始画);5.结束路径并填充。

@Entry
@Component
struct Index {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
@State bgColor: Color = Color.Red
@State circleCenterX: number = 0
@State circleCenterY: number = 0
@State circleRadius: number = 100
private colorList: string[] = ["#ff8787", "#f783ac", "#da77f2", "#228be6", '#40c057', '#f59f00']
​
drawCircle(fillColor: string) {
  this.context.clearRect(0, 0, this.context.width, this.context.height)
  this.context.fillStyle = fillColor
​
  this.context.beginPath()
  this.context.moveTo(0, 0)
  this.context.lineTo(0, this.context.height)
  this.context.lineTo(this.context.width, this.context.height)
  this.context.lineTo(this.context.width, 0)
  this.context.lineTo(0, 0)
  this.context.arc(this.circleCenterX, this.circleCenterY, this.circleRadius, 0, Math.PI * 2)
  this.context.fill()
  this.context.closePath()
​
  console.log("drawCircle" + fillColor)
}
​
build() {
  Column() {
    Button("开始闪烁").onClick(() => {
      this.colorList.forEach((item: string, index: number) => {
        setTimeout(() => {
          this.drawCircle(item)
        }, index * 500)
      })
    })
    Stack() {
      Image($r("app.media.startIcon")).width(100).height(100)
      Canvas(this.context)
        .width('100%')
        .aspectRatio(1)
        .backgroundColor(Color.Transparent)
        .onReady(() => {
          this.circleCenterX = this.context.width / 2
          this.circleCenterY = this.context.height / 2
          // 绘制底色
          this.drawCircle(this.colorList[0])
        })
    }
  }.width("100%")
  .height("100%")
}
}

实现效果

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进