【最新鸿蒙应用开发】——ArkTS图形绘制

361 阅读13分钟

 1. Shape组件绘制几何图形

绘制组件用于在页面绘制图形,Shape组件是绘制组件的父组件,父组件中会描述所有绘制组件均支持的通用属性。

1.1. 创建绘制组件

绘制组件可以由以下两种形式创建:

  • 绘制组件使用Shape作为父组件,实现类似SVG的效果。接口调用为以下形式:

    Shape(value?: PixelMap)
    

    该接口用于创建带有父组件的绘制组件,其中value用于设置绘制目标,可将图形绘制在指定的PixelMap对象中,若未设置,则在当前绘制目标中进行绘制。

    Shape() {  Rect().width(300).height(50)}
    
  • 绘制组件单独使用,用于在页面上绘制指定的图形。有7种绘制类型,分别为Circle(圆形)、Ellipse(椭圆形)、Line(直线)、Polyline(折线)、Polygon(多边形)、Path(路径)、Rect(矩形)。以Circle的接口调用为例:

    Circle(options?: {width?: string | number, height?: string | number}
    

    该接口用于在页面绘制圆形,其中width用于设置圆形的宽度,height用于设置圆形的高度,圆形直径由宽高最小值确定。

    Circle({ width: 150, height: 150 })
    

    img

1.2. 形状视口viewport

viewPort{ x?: number | string, y?: number | string, width?: number | string, height?: number | string }

形状视口viewport指定用户空间中的一个矩形,该矩形映射到为关联的SVG元素建立的视区边界。viewport属性的值包含x、y、width和height四个可选参数,x和y表示视区的左上角坐标,width和height表示其尺寸。

以下3个示例讲解viewport具体用法:

  • 通过形状视口对图形进行放大与缩小。

    class tmp{
      x:number = 0
      y:number = 0
      width:number = 75
      height:number = 75
    }
    let viep:tmp = new tmp()
    class tmp1{
      x:number = 0
      y:number = 0
      width:number = 300
      height:number = 300
    }
    let viep1:tmp1 = new tmp1()
    // 画一个宽高都为75的圆
    Text('原始尺寸Circle组件')
    Circle({width: 75, height: 75}).fill('#E87361')
    ​
    Row({space:10}) {
      Column() {
        // 创建一个宽高都为150的shape组件,背景色为黄色,一个宽高都为75的viewport。用一个蓝色的矩形来填充viewport,在viewport中绘制一个直径为75的圆。
        // 绘制结束,viewport会根据组件宽高放大两倍
        Text('shape内放大的Circle组件')
        Shape() {
          Rect().width('100%').height('100%').fill('#0097D4')
          Circle({width: 75, height: 75}).fill('#E87361')
        }
        .viewPort(viep)
        .width(150)
        .height(150)
        .backgroundColor('#F5DC62')
      }
      Column() {
        // 创建一个宽高都为150的shape组件,背景色为黄色,一个宽高都为300的viewport。用一个绿色的矩形来填充viewport,在viewport中绘制一个直径为75的圆。
        // 绘制结束,viewport会根据组件宽高缩小两倍。
        Text('Shape内缩小的Circle组件')
        Shape() {
          Rect().width('100%').height('100%').fill('#BDDB69')
          Circle({width: 75, height: 75}).fill('#E87361')
        }
        .viewPort(viep1)
        .width(150)
        .height(150)
        .backgroundColor('#F5DC62')
      }
    }
    

    img

  • 创建一个宽高都为300的shape组件,背景色为黄色,一个宽高都为300的viewport。用一个蓝色的矩形来填充viewport,在viewport中绘制一个半径为75的圆。

    class tmp{
      x:number = 0
      y:number = 0
      width:number = 300
      height:number = 300
    }
    let viep:tmp = new tmp()
    class tmp1{
      x:number = -150
      y:number = -150
      width:number = 300
      height:number = 300
    }
    let viep1:tmp1 = new tmp1()
    Shape() {
      Rect().width("100%").height("100%").fill("#0097D4")
      Circle({ width: 150, height: 150 }).fill("#E87361")
    }
      .viewPort(viep)
      .width(300)
      .height(300)
      .backgroundColor("#F5DC62")
    

    img

  • 创建一个宽高都为300的shape组件,背景色为黄色,创建一个宽高都为300的viewport。用一个蓝色的矩形来填充viewport,在viewport中绘制一个半径为75的圆,将viewport向右方和下方各平移150。

    Shape() {
      Rect().width("100%").height("100%").fill("#0097D4")
      Circle({ width: 150, height: 150 }).fill("#E87361")
    }
      .viewPort(viep1)
      .width(300)
      .height(300)
      .backgroundColor("#F5DC62")
    

    img

1.3. 自定义样式

绘制组件支持通过各种属性对组件样式进行更改。

  • 通过fill可以设置组件填充区域颜色。

    Path()
      .width(100)
      .height(100)
      .commands('M150 0 L300 300 L0 300 Z')
      .fill("#E87361")
    

    img

  • 通过stroke可以设置组件边框颜色。

    Path()
      .width(100)
      .height(100)
      .fillOpacity(0)
      .commands('M150 0 L300 300 L0 300 Z')
      .stroke(Color.Red)
    

    img

  • 通过strokeOpacity可以设置边框透明度。

    Path()
      .width(100)
      .height(100)
      .fillOpacity(0)
      .commands('M150 0 L300 300 L0 300 Z')
      .stroke(Color.Red)
      .strokeWidth(10)
      .strokeOpacity(0.2)
    

    img

  • 通过strokeLineJoin可以设置线条拐角绘制样式。拐角绘制样式分为Bevel(使用斜角连接路径段)、Miter(使用尖角连接路径段)、Round(使用圆角连接路径段)。

    Polyline()
      .width(100)
      .height(100)
      .fillOpacity(0)
      .stroke(Color.Red)
      .strokeWidth(8)
      .points([[20, 0], [0, 100], [100, 90]])
       // 设置折线拐角处为圆弧
      .strokeLineJoin(LineJoinStyle.Round)
    

    img

  • 通过strokeMiterLimit设置斜接长度与边框宽度比值的极限值。

    斜接长度表示外边框外边交点到内边交点的距离,边框宽度即strokeWidth属性的值。strokeMiterLimit取值需大于等于1,且在strokeLineJoin属性取值LineJoinStyle.Miter时生效。

    Polyline()
      .width(100)
      .height(100)
      .fillOpacity(0)
      .stroke(Color.Red)
      .strokeWidth(10)
      .points([[20, 0], [20, 100], [100, 100]])
      // 设置折线拐角处为尖角
      .strokeLineJoin(LineJoinStyle.Miter)
      // 设置斜接长度与线宽的比值
      .strokeMiterLimit(1/Math.sin(45))
    Polyline()
      .width(100)
      .height(100)
      .fillOpacity(0)
      .stroke(Color.Red)
      .strokeWidth(10)
      .points([[20, 0], [20, 100], [100, 100]])
      .strokeLineJoin(LineJoinStyle.Miter)
      .strokeMiterLimit(1.42)
    

    img

  • 通过antiAlias设置是否开启抗锯齿,默认值为true(开启抗锯齿)。

    //开启抗锯齿
    Circle()
      .width(150)
      .height(200)
      .fillOpacity(0)
      .strokeWidth(5)
      .stroke(Color.Black)
    

    img

    //关闭抗锯齿
    Circle()
      .width(150)
      .height(200)
      .fillOpacity(0)
      .strokeWidth(5)
      .stroke(Color.Black)
      .antiAlias(false)
    

    img

1.4. 场景示例

  • 在Shape的(-80, -5)点绘制一个封闭路径,填充颜色0x317AF7,线条宽度3,边框颜色红色,拐角样式锐角(默认值)。

    @Entry
    @Component
    struct ShapeExample {
      build() {
        Column({ space: 10 }) {
          Shape() {
            Path().width(200).height(60).commands('M0 0 L400 0 L400 150 Z')
          }
          .viewPort({ x: -80, y: -5, width: 500, height: 300 })
          .fill(0x317AF7)
          .stroke(Color.Red)
          .strokeWidth(3)
          .strokeLineJoin(LineJoinStyle.Miter)
          .strokeMiterLimit(5)
        }.width('100%').margin({ top: 15 })
      }
    }
    

    img

  • 绘制一个直径为150的圆,和一个直径为150、线条为红色虚线的圆环(宽高设置不一致时以短边为直径)。

    @Entry
    @Component
    struct CircleExample {
      build() {
        Column({ space: 10 }) {
          //绘制一个直径为150的圆
          Circle({ width: 150, height: 150 })
          //绘制一个直径为150、线条为红色虚线的圆环
          Circle()
            .width(150)
            .height(200)
            .fillOpacity(0)
            .strokeWidth(3)
            .stroke(Color.Red)
            .strokeDashArray([1, 2])
        }.width('100%')
      }
    }
    

    img

2. Canvas画布绘制自定义图形

Canvas提供画布组件,用于自定义绘制图形,开发者使用CanvasRenderingContext2D对象和OffscreenCanvasRenderingContext2D对象在Canvas组件上进行绘制,绘制对象可以是基础形状、文本、图片等。

可以由以下三种形式在画布绘制自定义图形:

  • 使用CanvasRenderingContext2D对象在Canvas画布上绘制。

    @Entry
    @Component
    struct CanvasExample1 {
      //用来配置CanvasRenderingContext2D对象的参数,包括是否开启抗锯齿,true表明开启抗锯齿。
      private settings: RenderingContextSettings = new RenderingContextSettings(true)
      //用来创建CanvasRenderingContext2D对象,通过在canvas中调用CanvasRenderingContext2D对象来绘制。
      private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
    ​
      build() {
        Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
          //在canvas中调用CanvasRenderingContext2D对象。
          Canvas(this.context)
            .width('100%')
            .height('100%')
            .backgroundColor('#F5DC62')
            .onReady(() => {
              //可以在这里绘制内容。
              this.context.strokeRect(50, 50, 200, 150);
            })
        }
        .width('100%')
        .height('100%')
      }
    }
    

    img

  • 离屏绘制是指将需要绘制的内容先绘制在缓存区,再将其转换成图片,一次性绘制到Canvas上,加快了绘制速度。过程为:

    1. 通过transferToImageBitmap方法将离屏画布最近渲染的图像创建为一个ImageBitmap对象。
    2. 通过CanvasRenderingContext2D对象的transferFromImageBitmap方法显示给定的ImageBitmap对象。

    具体使用参考OffscreenCanvasRenderingContext2D对象

    @Entry
    @Component
    struct CanvasExample2 {
    //用来配置CanvasRenderingContext2D对象和OffscreenCanvasRenderingContext2D对象的参数,包括是否开启抗锯齿。true表明开启抗锯齿
      private settings: RenderingContextSettings = new RenderingContextSettings(true)
      private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
    //用来创建OffscreenCanvas对象,width为离屏画布的宽度,height为离屏画布的高度。通过在canvas中调用OffscreenCanvasRenderingContext2D对象来绘制。
      private offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600)
     
      build() {
        Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
          Canvas(this.context)
            .width('100%')
            .height('100%')
            .backgroundColor('#F5DC62')
            .onReady(() =>{
              let offContext = this.offCanvas.getContext("2d", this.settings)
              //可以在这里绘制内容
              offContext.strokeRect(50, 50, 200, 150);
              //将离屏绘值渲染的图像在普通画布上显示
              let image = this.offCanvas.transferToImageBitmap();
              this.context.transferFromImageBitmap(image);
            })
        }
        .width('100%')
        .height('100%')
      }
    }
    

    img

    说明

    在画布组件中,通过CanvasRenderingContext2D对象和OffscreenCanvasRenderingContext2D对象在Canvas组件上进行绘制时调用的接口相同,另接口参数如无特别说明,单位均为vp。

  • 在Canvas上加载Lottie动画时,需要先按照如下方式下载Lottie。

    import lottie from '@ohos/lottie'
    

    具体接口请参考Lottie

2.1. 初始化画布组件

onReady(event: () => void)是Canvas组件初始化完成时的事件回调,调用该事件后,可获取Canvas组件的确定宽高,进一步使用CanvasRenderingContext2D对象和OffscreenCanvasRenderingContext2D对象调用相关API进行图形绘制。

Canvas(this.context)
  .width('100%')
  .height('100%')
  .backgroundColor('#F5DC62')
  .onReady(() => {
    this.context.fillStyle = '#0097D4';
    this.context.fillRect(50, 50, 100, 100);
  })

img

2.2. 画布组件绘制方式

在Canvas组件生命周期接口onReady()调用之后,开发者可以直接使用canvas组件进行绘制。或者可以脱离Canvas组件和onReady()生命周期,单独定义Path2d对象构造理想的路径,并在onReady()调用之后使用Canvas组件进行绘制。

  • 通过CanvasRenderingContext2D对象和OffscreenCanvasRenderingContext2D对象直接调用相关API进行绘制。

    Canvas(this.context)
      .width('100%')
      .height('100%')
      .backgroundColor('#F5DC62')
      .onReady(() =>{
        this.context.beginPath();
        this.context.moveTo(50, 50);
        this.context.lineTo(280, 160);
        this.context.stroke();
       })
    

    img

  • 先单独定义path2d对象构造理想的路径,再通过调用CanvasRenderingContext2D对象和OffscreenCanvasRenderingContext2D对象的stroke接口或者fill接口进行绘制,具体使用可以参考Path2D对象

    Canvas(this.context)
      .width('100%')
      .height('100%')
      .backgroundColor('#F5DC62')
      .onReady(() =>{
         let region = new Path2D();
         region.arc(100, 75, 50, 0, 6.28);
         this.context.stroke(region);
      })
    

    img

2.3. 画布组件常用方法

OffscreenCanvasRenderingContext2D对象和CanvasRenderingContext2D对象提供了大量的属性和方法,可以用来绘制文本、图形,处理像素等,是Canvas组件的核心。常用接口有fill(对封闭路径进行填充)、clip(设置当前路径为剪切路径)、stroke(进行边框绘制操作)等等,同时提供了fillStyle(指定绘制的填充色)、globalAlpha(设置透明度)与strokeStyle(设置描边的颜色)等属性修改绘制内容的样式。将通过以下几个方面简单介绍画布组件常见使用方法:

  • 基础形状绘制。

    可以通过arc(绘制弧线路径)、 ellipse(绘制一个椭圆)、rect(创建矩形路径)等接口绘制基础形状。

    Canvas(this.context)
      .width('100%')
      .height('100%')
      .backgroundColor('#F5DC62')
      .onReady(() =>{
         //绘制矩形
         this.context.beginPath();
         this.context.rect(100, 50, 100, 100);
         this.context.stroke();
         //绘制圆形
         this.context.beginPath();
         this.context.arc(150, 250, 50, 0, 6.28);
         this.context.stroke();
         //绘制椭圆
         this.context.beginPath();
         this.context.ellipse(150, 450, 50, 100, Math.PI * 0.25, Math.PI * 0, Math.PI * 2);
         this.context.stroke();
      })
    

    img

  • 文本绘制。

    可以通过fillText(绘制填充类文本)、strokeText(绘制描边类文本)等接口进行文本绘制。

    Canvas(this.context)
      .width('100%')
      .height('100%')
      .backgroundColor('#F5DC62')
      .onReady(() =>{
         //绘制填充类文本
         this.context.font = '50px sans-serif';
         this.context.fillText("Hello World!", 50, 100);
         //绘制描边类文本
         this.context.font = '55px sans-serif';
         this.context.strokeText("Hello World!", 50, 150);
      })
    

    img

  • 绘制图片和图像像素信息处理。

    可以通过drawImage(图像绘制)、putImageData(使用ImageData数据填充新的矩形区域)等接口绘制图片,通过createImageData(创建新的ImageData 对象)、getPixelMap(以当前canvas指定区域内的像素创建PixelMap对象)、getImageData(以当前canvas指定区域内的像素创建ImageData对象)等接口进行图像像素信息处理。

    @Entry
    @Component
    struct GetImageData {
     private settings: RenderingContextSettings = new RenderingContextSettings(true)
     private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
     private offCanvas: OffscreenCanvas = new OffscreenCanvas(600, 600)
     private img:ImageBitmap = new ImageBitmap("/common/images/1234.png")
    ​
      build() {
        Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
          Canvas(this.context)
            .width('100%')
            .height('100%')
            .backgroundColor('#F5DC62')
            .onReady(() =>{
              let offContext = this.offCanvas.getContext("2d", this.settings)
              // 使用drawImage接口将图片画在(0,0)为起点,宽高130的区域
              offContext.drawImage(this.img,0,0,130,130);
              // 使用getImageData接口,获得canvas组件区域中,(50,50)为起点,宽高130范围内的绘制内容
              let imagedata = offContext.getImageData(50,50,130,130);
              // 使用putImageData接口将得到的ImageData画在起点为(150, 150)的区域中
              offContext.putImageData(imagedata,150,150);
              // 将离屏绘制的内容画到canvas组件上
              let image = this.offCanvas.transferToImageBitmap();
              this.context.transferFromImageBitmap(image);
            })
        }
        .width('100%')
        .height('100%')
      }
    }
    

    img

  • 其他方法。

    Canvas中还提供其他类型的方法。渐变(CanvasGradient对象)相关的方法:createLinearGradient(创建一个线性渐变色)、createRadialGradient(创建一个径向渐变色)等。

     Canvas(this.context)
      .width('100%')
      .height('100%')
      .backgroundColor('#F5DC62')
      .onReady(() =>{
         //创建一个径向渐变色的CanvasGradient对象
         let grad = this.context.createRadialGradient(200,200,50, 200,200,200)
         //为CanvasGradient对象设置渐变断点值,包括偏移和颜色
         grad.addColorStop(0.0, '#E87361');
         grad.addColorStop(0.5, '#FFFFF0');
         grad.addColorStop(1.0, '#BDDB69');
         //用CanvasGradient对象填充矩形
         this.context.fillStyle = grad;
         this.context.fillRect(0, 0, 400, 400);
      })
    

    img

2.4. 场景示例

  • 规则基础形状绘制。

    @Entry
    @Component
    struct ClearRect {
     private settings: RenderingContextSettings = new RenderingContextSettings(true);
     private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
    ​
      build() {
        Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
          Canvas(this.context)
            .width('100%')
            .height('100%')
            .backgroundColor('#F5DC62')
            .onReady(() =>{
              // 设定填充样式,填充颜色设为蓝色
              this.context.fillStyle = '#0097D4';
              // 以(50, 50)为左上顶点,画一个宽高200的矩形
              this.context.fillRect(50,50,200,200);
              // 以(70, 70)为左上顶点,清除宽150高100的区域
              this.context.clearRect(70,70,150,100);
          })
        }
        .width('100%')
        .height('100%')
      }
    }
    

    img

  • 不规则图形绘制。

    @Entry
    @Component
    struct Path2d {
      private settings: RenderingContextSettings = new RenderingContextSettings(true);
      private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
      
      build() {
        Row() {
          Column() {
            Canvas(this.context)
              .width('100%')
              .height('100%')
              .backgroundColor('#F5DC62')
              .onReady(() =>{
                // 使用Path2D的接口构造一个五边形
                let path = new Path2D();
                path.moveTo(150, 50);
                path.lineTo(50, 150);
                path.lineTo(100, 250);
                path.lineTo(200, 250);
                path.lineTo(250, 150);
                path.closePath();
                // 设定填充色为蓝色
                this.context.fillStyle = '#0097D4';
                // 使用填充的方式,将Path2D描述的五边形绘制在canvas组件内部
                this.context.fill(path);
              })
          }
          .width('100%')
        }
        .height('100%')
      }
    }
    

    img

参考官方文档:

显示图形-UI开发(ArkTS声明式开发范式)-ArkUI(方舟UI框架)-开发 | 华为开发者联盟 (huawei.com)