// 定义一个名为Index的应用入口组件@Entry@Componentstruct Index { // 初始化绘图上下文所需的设置 private settings: RenderingContextSettings = new RenderingContextSettings(true); // 创建两个用于绘制不同图案的Canvas绘图上下文 private contextForRectangle: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); private contextForCircle: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
// 构建UI build() { // 使用Column布局,设置每个子元素之间的间隔为5 Column({ space: 5 }) { // 第一个示例:实心矩形镂空 Text('1. 实心矩形镂空')
Stack() { // 在Stack中放置一个图像作为背景 Image($r('app.media.startIcon')).width(200).height(200).enableAnalyzer(true)
// 创建一个Canvas,并在准备就绪后执行绘图逻辑 Canvas(this.contextForRectangle).width(80).height(80).backgroundColor(undefined).onReady(async () => { // 设置填充色 this.contextForRectangle.fillStyle = 'rgba(0, 255, 255, 1)';
// 绘制一个覆盖整个Canvas的矩形 this.contextForRectangle.fillRect(0, 0, 80, 80);
// 在矩形中心位置创建一个镂空矩形 this.contextForRectangle.clearRect(10, 20, 50, 40); }); }.width(300)
// 第二个示例:实心圆镂空 Text('2. 实心圆镂空')
Stack() { Image($r('app.media.startIcon')).width(200).height(200).enableAnalyzer(true)
// 创建一个Canvas,并在准备就绪后执行绘图逻辑 Canvas(this.contextForCircle).width(80).height(80).backgroundColor(undefined).onReady(async () => { // 清除背景 this.contextForCircle.clearRect(0, 0, 80, 80);
// 设置填充色 this.contextForCircle.fillStyle = 'rgba(0, 255, 255, 1)';
// 绘制一个覆盖整个Canvas的矩形 this.contextForCircle.fillRect(0, 0, 80, 80);
// 画一个圆形镂空 this.contextForCircle.beginPath(); this.contextForCircle.arc(40, 40, 30, 0, Math.PI * 2); // 圆心坐标为(40, 40),半径为30 this.contextForCircle.globalCompositeOperation = 'destination-out'; this.contextForCircle.fill(); }); }
// 第三个示例:文字镂空 Text('3. 文字镂空')
Stack() { // 背景图像 Image($r('app.media.startIcon')).width(200).height(200).enableAnalyzer(true)
Stack() { // 在内部Stack中绘制镂空文字 Text('鸿蒙') .fontSize(30) .fontWeight(FontWeight.Bold) .blendMode(BlendMode.XOR, BlendApplyType.OFFSCREEN) }.blendMode(BlendMode.SRC_OVER, BlendApplyType.OFFSCREEN) .backgroundColor('rgba(0, 255, 255, 1)') .width(80).height(80)
}.width(200).height(200) }.width('100%') }}
评论