• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# CanvasGradient
2
3渐变对象。
4
5>  **说明:**
6>
7>  从 API Version 8 开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
8
9
10
11## addColorStop
12
13addColorStop(offset: number, color: string): void
14
15设置渐变断点值,包括偏移和颜色。
16
17**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。
18
19**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
20
21**系统能力:** SystemCapability.ArkUI.ArkUI.Full
22
23**参数:**
24
25| 参数名 | 类型 | 必填 | 说明 |
26| ------ | ------ | ---- | ---------------------------------------- |
27| offset | number | 是  | 设置渐变点距离起点的位置占总体长度的比例,范围为[0, 1]。</br>设置offset<0或offset>1无渐变效果。             |
28| color  | string | 是  | 设置渐变的颜色。颜色格式参考[ResourceColor](ts-types.md#resourcecolor)中string类型说明。</br>未按格式设置颜色无渐变效果。 |
29
30
31## 示例
32
33通过addColorStop设置渐变断点值,包括偏移和颜色。
34
35  ```ts
36  // xxx.ets
37  @Entry
38  @Component
39  struct AddColorStop {
40    private settings: RenderingContextSettings = new RenderingContextSettings(true)
41    private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
42
43    build() {
44      Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
45        Canvas(this.context)
46          .width('100%')
47          .height('100%')
48          .backgroundColor('#ffff00')
49          .onReady(() => {
50            let grad = this.context.createLinearGradient(50, 0, 300, 100)
51            grad.addColorStop(0.0, '#ff0000')
52            grad.addColorStop(0.5, '#ffffff')
53            grad.addColorStop(1.0, '#00ff00')
54            this.context.fillStyle = grad
55            this.context.fillRect(0, 0, 400, 400)
56          })
57      }
58      .width('100%')
59      .height('100%')
60    }
61  }
62  ```
63  ![zh-cn_image_0000001194032516](figures/zh-cn_image_0000001194032516.jpeg)
64
65