• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# 自定义绘制设置
2<!--Kit: ArkUI-->
3<!--Subsystem: ArkUI-->
4<!--Owner: @xiang-shouxing-->
5<!--Designer: @xiang-shouxing-->
6<!--Tester: @sally__-->
7<!--Adviser: @HelloCrease-->
8
9当某些组件本身的绘制内容不满足需求时,可使用自定义组件绘制功能,在原有组件基础上部分绘制、或者全部自行绘制,以达到预期效果。例如:独特的按钮形状、文字和图像混合的图标等。自定义组件绘制提供了自定义绘制修改器,来实现更自由地组件绘制。
10
11> **说明:**
12>
13> 从API version 12开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
14
15## drawModifier
16
17drawModifier(modifier: DrawModifier | undefined): T
18
19设置组件的自定义绘制修改器。
20
21**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
22
23**系统能力:** SystemCapability.ArkUI.ArkUI.Full
24
25**组件支持范围:**
26
27AlphabetIndexer、Badge、Blank、Button、CalendarPicker、Checkbox、CheckboxGroup、Circle、Column、ColumnSplit、Counter、DataPanel、DatePicker、Ellipse、Flex、FlowItem、FolderStack、FormLink、Gauge、Grid、GridCol、GridItem、GridRow、Hyperlink、Image、ImageAnimator、ImageSpan、Line、List、ListItem、ListItemGroup、LoadingProgress、Marquee、Menu、MenuItem、MenuItemGroup、NavDestination、Navigation、Navigator、NavRouter、NodeContainer、Path、PatternLock、Polygon、Polyline、Progress、QRCode、Radio、Rating、Rect、Refresh、RelativeContainer、RichEditor、Row、RowSplit、Scroll、ScrollBar、Search、Select、Shape、SideBarContainer、Slider、Stack、Stepper、StepperItem、Swiper、SymbolGlyph、TabContent、Tabs、Text、TextArea、TextClock、TextInput、TextPicker、TextTimer、TimePicker、Toggle、WaterFlow、XComponent
28
29**参数:**
30
31| 参数名 | 类型                                                 | 必填 | 说明                                                         |
32| ------ | ---------------------------------------------------- | ---- | ------------------------------------------------------------ |
33| modifier  | &nbsp;[DrawModifier](#drawmodifier-1)&nbsp;\|&nbsp;undefined | 是   | 自定义绘制修改器,其中定义了自定义绘制的逻辑。 <br> 默认值:undefined <br/>**说明:** <br/> 每个自定义修改器只对当前绑定组件的FrameNode生效,对其子节点不生效。 |
34
35**返回值:**
36
37| 类型 | 说明 |
38| --- | --- |
39| T | 返回当前组件。 |
40
41## DrawModifier
42
43DrawModifier可设置前景(drawForeground)、内容前景(drawFront)、内容(drawContent)和内容背景(drawBehind)的绘制方法,还提供主动触发重绘的方法[invalidate](#invalidate)。每个DrawModifier实例只能设置到一个组件上,禁止进行重复设置。
44
45自定义层级示例图
46
47![drawModifier.gif](figures/drawModifier.png)
48
49**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
50
51**系统能力:** SystemCapability.ArkUI.ArkUI.Full
52
53### drawFront
54
55drawFront?(drawContext: DrawContext): void
56
57自定义绘制内容前景的接口,若重载该方法则可进行内容前景的自定义绘制。
58
59**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
60
61**系统能力:** SystemCapability.ArkUI.ArkUI.Full
62
63**参数:**
64
65| 参数名  | 类型                                                   | 必填 | 说明             |
66| ------- | ------------------------------------------------------ | ---- | ---------------- |
67| drawContext | [DrawContext](#drawcontext) | 是   | 图形绘制上下文。 |
68
69### drawContent
70
71drawContent?(drawContext: DrawContext): void
72
73自定义绘制内容的接口,若重载该方法则可进行内容的自定义绘制,会替换组件原本的内容绘制函数。
74
75**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
76
77**系统能力:** SystemCapability.ArkUI.ArkUI.Full
78
79**参数:**
80
81| 参数名  | 类型                                                   | 必填 | 说明             |
82| ------- | ------------------------------------------------------ | ---- | ---------------- |
83| drawContext | [DrawContext](#drawcontext) | 是   | 图形绘制上下文。 |
84
85### drawBehind
86
87drawBehind?(drawContext: DrawContext): void
88
89自定义绘制背景的接口,若重载该方法则可进行背景的自定义绘制。
90
91**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
92
93**系统能力:** SystemCapability.ArkUI.ArkUI.Full
94
95**参数:**
96
97| 参数名  | 类型                                                   | 必填 | 说明             |
98| ------- | ------------------------------------------------------ | ---- | ---------------- |
99| drawContext | [DrawContext](#drawcontext) | 是   | 图形绘制上下文。 |
100
101### drawForeground<sup>20+</sup>
102
103drawForeground(drawContext: DrawContext): void
104
105自定义绘制前景的接口,若重载该方法则可进行前景的自定义绘制。需要对其组件的前景层进行绘制时重载该方法。
106
107**原子化服务API:** 从API version 20开始,该接口支持在原子化服务中使用。
108
109**系统能力:** SystemCapability.ArkUI.ArkUI.Full
110
111**参数:**
112
113| 参数名  | 类型                                                   | 必填 | 说明             |
114| ------- | ------------------------------------------------------ | ---- | ---------------- |
115| drawContext | [DrawContext](#drawcontext) | 是   | 图形绘制上下文。 |
116
117### invalidate
118
119invalidate(): void
120
121主动触发重绘的接口,开发者无需也无法重载,调用会触发所绑定组件的重绘。
122
123**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
124
125**系统能力:** SystemCapability.ArkUI.ArkUI.Full
126
127### DrawContext
128
129type DrawContext = DrawContext
130
131**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
132
133**系统能力:** SystemCapability.ArkUI.ArkUI.Full
134
135| 类型                                                      | 说明                    |
136| --------------------------------------------------------- | ----------------------- |
137| [DrawContext](../js-apis-arkui-graphics.md#drawcontext) | 图形绘制上下文。 |
138
139## 示例
140
141### 示例1(通过DrawModifier进行自定义绘制)
142
143通过DrawModifier对Text组件进行自定义绘制。
144
145```ts
146// xxx.ets
147import { drawing } from '@kit.ArkGraphics2D';
148import { AnimatorResult } from '@kit.ArkUI';
149
150class MyFullDrawModifier extends DrawModifier {
151  public scaleX: number = 1;
152  public scaleY: number = 1;
153  uiContext: UIContext;
154
155  constructor(uiContext: UIContext) {
156    super();
157    this.uiContext = uiContext;
158  }
159
160  drawBehind(context: DrawContext): void {
161    const brush = new drawing.Brush();
162    brush.setColor({
163      alpha: 255,
164      red: 255,
165      green: 0,
166      blue: 0
167    });
168    context.canvas.attachBrush(brush);
169    const halfWidth = context.size.width / 2;
170    const halfHeight = context.size.height / 2;
171    context.canvas.drawRect({
172      left: this.uiContext.vp2px(halfWidth - 50 * this.scaleX),
173      top: this.uiContext.vp2px(halfHeight - 50 * this.scaleY),
174      right: this.uiContext.vp2px(halfWidth + 50 * this.scaleX),
175      bottom: this.uiContext.vp2px(halfHeight + 50 * this.scaleY)
176    });
177  }
178
179  drawContent(context: DrawContext): void {
180    const brush = new drawing.Brush();
181    brush.setColor({
182      alpha: 255,
183      red: 0,
184      green: 255,
185      blue: 0
186    });
187    context.canvas.attachBrush(brush);
188    const halfWidth = context.size.width / 2;
189    const halfHeight = context.size.height / 2;
190    context.canvas.drawRect({
191      left: this.uiContext.vp2px(halfWidth - 30 * this.scaleX),
192      top: this.uiContext.vp2px(halfHeight - 30 * this.scaleY),
193      right: this.uiContext.vp2px(halfWidth + 30 * this.scaleX),
194      bottom: this.uiContext.vp2px(halfHeight + 30 * this.scaleY)
195    });
196  }
197
198  drawFront(context: DrawContext): void {
199    const brush = new drawing.Brush();
200    brush.setColor({
201      alpha: 255,
202      red: 0,
203      green: 0,
204      blue: 255
205    });
206    context.canvas.attachBrush(brush);
207    const halfWidth = context.size.width / 2;
208    const halfHeight = context.size.height / 2;
209    const radiusScale = (this.scaleX + this.scaleY) / 2;
210    context.canvas.drawCircle(this.uiContext.vp2px(halfWidth), this.uiContext.vp2px(halfHeight), this.uiContext.vp2px(20 * radiusScale));
211  }
212}
213
214class MyFrontDrawModifier extends DrawModifier {
215  public scaleX: number = 1;
216  public scaleY: number = 1;
217  uiContext: UIContext;
218
219  constructor(uiContext: UIContext) {
220    super();
221    this.uiContext = uiContext;
222  }
223
224  drawFront(context: DrawContext): void {
225    const brush = new drawing.Brush();
226    brush.setColor({
227      alpha: 255,
228      red: 0,
229      green: 0,
230      blue: 255
231    });
232    context.canvas.attachBrush(brush);
233    const halfWidth = context.size.width / 2;
234    const halfHeight = context.size.height / 2;
235    const radiusScale = (this.scaleX + this.scaleY) / 2;
236    context.canvas.drawCircle(this.uiContext.vp2px(halfWidth), this.uiContext.vp2px(halfHeight), this.uiContext.vp2px(20 * radiusScale));
237  }
238}
239
240@Entry
241@Component
242struct DrawModifierExample {
243  private fullModifier: MyFullDrawModifier = new MyFullDrawModifier(this.getUIContext());
244  private frontModifier: MyFrontDrawModifier = new MyFrontDrawModifier(this.getUIContext());
245  private drawAnimator: AnimatorResult | undefined = undefined;
246  @State modifier: DrawModifier = new MyFrontDrawModifier(this.getUIContext());
247  private count = 0;
248
249  create() {
250    let self = this;
251    this.drawAnimator = this.getUIContext().createAnimator({
252      duration: 1000,
253      easing: 'ease',
254      delay: 0,
255      fill: 'forwards',
256      direction: 'normal',
257      iterations: 1,
258      begin: 0,
259      end: 2
260    });
261    this.drawAnimator.onFrame = (value: number) => {
262      console.log('frame value =', value);
263      const tempModifier = self.modifier as MyFullDrawModifier | MyFrontDrawModifier;
264      tempModifier.scaleX = Math.abs(value - 1);
265      tempModifier.scaleY = Math.abs(value - 1);
266      self.modifier.invalidate();
267    };
268  }
269
270  build() {
271    Column() {
272      Row() {
273        Text('test text')
274          .width(100)
275          .height(100)
276          .margin(10)
277          .backgroundColor(Color.Gray)
278          .onClick(() => {
279            const tempModifier = this.modifier as MyFullDrawModifier | MyFrontDrawModifier;
280            tempModifier.scaleX -= 0.1;
281            tempModifier.scaleY -= 0.1;
282          })
283          .drawModifier(this.modifier)
284      }
285
286      Row() {
287        Button('create')
288          .width(100)
289          .height(100)
290          .margin(10)
291          .onClick(() => {
292            this.create();
293          })
294        Button('play')
295          .width(100)
296          .height(100)
297          .margin(10)
298          .onClick(() => {
299            if (this.drawAnimator) {
300              this.drawAnimator.play();
301            }
302          })
303        Button('changeModifier')
304          .width(100)
305          .height(100)
306          .margin(10)
307          .onClick(() => {
308            this.count += 1;
309            if (this.count % 2 === 1) {
310              console.log('change to full modifier');
311              this.modifier = this.fullModifier;
312            } else {
313              console.log('change to front modifier');
314              this.modifier = this.frontModifier;
315            }
316          })
317      }
318    }
319    .width('100%')
320    .height('100%')
321  }
322}
323```
324
325![drawModifier.gif](figures/drawModifier.gif)
326
327### 示例2(通过DrawModifier对容器的前景进行自定义绘制)
328
329通过DrawModifier对Column容器的前景进行自定义绘制。
330
331```ts
332// xxx.ets
333import { drawing } from '@kit.ArkGraphics2D';
334
335class MyForegroundDrawModifier extends DrawModifier {
336  public scaleX: number = 3;
337  public scaleY: number = 3;
338  uiContext: UIContext;
339
340  constructor(uiContext: UIContext) {
341    super();
342    this.uiContext = uiContext;
343  }
344
345  // 重载drawForeground方法,实现自定义绘制前景。
346  drawForeground(context: DrawContext): void {
347    const brush = new drawing.Brush();
348    brush.setColor({
349      alpha: 255,
350      red: 0,
351      green: 50,
352      blue: 100
353    });
354    context.canvas.attachBrush(brush);
355    const halfWidth = context.size.width / 2;
356    const halfHeight = context.size.height / 2;
357    context.canvas.drawRect({
358      left: this.uiContext.vp2px(halfWidth - 30 * this.scaleX),
359      top: this.uiContext.vp2px(halfHeight - 30 * this.scaleY),
360      right: this.uiContext.vp2px(halfWidth + 30 * this.scaleX),
361      bottom: this.uiContext.vp2px(halfHeight + 30 * this.scaleY)
362    });
363  }
364}
365
366@Entry
367@Component
368struct DrawModifierExample {
369  // 将自定义绘制前景的类实例化,传入UIContext实例。
370  private foregroundModifier: MyForegroundDrawModifier = new MyForegroundDrawModifier(this.getUIContext());
371
372  build() {
373    Column() {
374      Text('此文本是子节点')
375        .fontSize(36)
376        .width('100%')
377        .height('100%')
378        .textAlign(TextAlign.Center)
379    }
380    .margin(50)
381    .width(280)
382    .height(300)
383    .backgroundColor(0x87CEEB)
384    // 调用此接口并传入自定义绘制前景的类实例,即可实现自定义绘制前景。
385    .drawModifier(this.foregroundModifier)
386  }
387}
388
389```
390![drawForeground.png](figures/drawForeground.png)