目录

绘制几何图形 (Shape)

绘制组件用于在页面绘制图形,Shape组件是绘制组件的父组件,包含所有绘制组件的通用属性。具体用法请参考Shape。

创建绘制组件

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

形状视口viewPort

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

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

以下三个示例说明如何使用viewPort:

自定义样式

示例通过commands来绘制路径,commands参数说明请参考SVG路径描述规范。

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

场景示例

[h2]绘制封闭路径

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

示例通过commands来绘制路径,commands参数说明请参考SVG路径描述规范。

@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('rgb(213, 213, 213)')
      .stroke('rgb(39, 135, 217)')
      .strokeWidth(3)
      .strokeLineJoin(LineJoinStyle.Miter)
      .strokeMiterLimit(5)
    }.width('100%').margin({ top: 15 })
  }
}

[h2]绘制圆和圆环

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

本示例通过strokeDashArray属性设置边框间隙来实现红色虚线的圆环,strokeDashArray属性参考strokeDashArray。

@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%')
  }
}

[h2]UI视觉属性作用效果

backgroundColor、linearGradient等通用属性作用于组件的背景区域,而不会在组件具体的内容区域生效。

@Entry
@Component
struct CircleExample {
  build() {
    Column({ space: 10 }) {
      // ...
      // 绘制一个直径为150的圆
      Circle()
        .width(150)
        .height(200)
        .backgroundColor(Color.Pink) // 会生效在一个150*200大小的矩形区域,而非仅在绘制的一个直径为150的圆形区域
    }.width('100%')
  }
}