#鸿蒙通关秘籍#如何在ArkTS卡片中自定义绘制图形?

HarmonyOS
1天前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
hm673ff0953ed07

通过Canvas组件和CanvasRenderingContext2D对象可以在ArkTS卡片中进行自定义绘制。在如下代码中创建一个画布,并在画布中心绘制一个笑脸:

@Entry @Component struct CustomCanvasDrawingCard { private canvasWidth: number = 0; private canvasHeight: number = 0; private settings: RenderingContextSettings = new RenderingContextSettings(true); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);

build() { Column() { Row() { Canvas(this.context) .width('100%') .height('100%') .onReady(() => { this.canvasWidth = this.context.width; this.canvasHeight = this.context.height; this.context.fillStyle = '#EEF0FF'; this.context.fillRect(0, 0, this.canvasWidth, this.canvasHeight);

        // Draw face circle
        this.context.beginPath();
        let radius = this.context.width / 3;
        let circleX = this.context.width / 2;
        let circleY = this.context.height / 2;
        this.context.arc(circleX, circleY, radius, 0, 2 * Math.PI);
        this.context.fillStyle = '#5A5FFF';
        this.context.fill();

        // Draw left eye
        let eyeX = circleX - (radius / 2.3);
        let eyeY = circleY - (radius / 4.5);
        this.context.beginPath();
        this.context.arc(eyeX, eyeY, radius / 13, 0, 2 * Math.PI);
        this.context.strokeStyle = '#FFFFFF';
        this.context.lineWidth = 15;
        this.context.stroke();

        // Draw right eye
        eyeX = circleX + (radius / 2.3);
        this.context.beginPath();
        this.context.arc(eyeX, eyeY, radius / 13, 0, 2 * Math.PI);
        this.context.stroke();

        // Draw nose
        this.context.beginPath();
        this.context.moveTo(circleX, circleY - 20);
        this.context.lineTo(circleX - 8, circleY + 20);
        this.context.lineTo(circleX + 8, circleY + 20);
        this.context.stroke();

        // Draw mouth
        this.context.beginPath();
        this.context.arc(circleX, circleY + 10, radius / 2, Math.PI / 1.4, Math.PI / 3.4);
        this.context.stroke();
      })
  }
}.height('100%').width('100%')

} }

分享
微博
QQ
微信
回复
1天前
相关问题
使用Native、XComponent和EGL绘制图形
981浏览 • 1回复 待解决
画布上绘制图如何实现?
334浏览 • 1回复 待解决
HarmonyOS Canvas中关于绘制图片问题
364浏览 • 1回复 待解决