未验证 提交 9988a2b8 编写于 作者: O openharmony_ci 提交者: Gitee

!9877 翻译完成 9115:arkui-ts文件夹整改

Merge pull request !9877 from ester.zhou/C-0923
...@@ -14,7 +14,7 @@ Below are the restrictions on using generator functions in TypeScript: ...@@ -14,7 +14,7 @@ Below are the restrictions on using generator functions in TypeScript:
- The generator function cannot contain local variables. - The generator function cannot contain local variables.
None of the above restrictions apply to anonymous function implementations of event handlers (such as **onClick**) None of the above restrictions apply to anonymous function implementations of event handlers (such as **onClick**).
Negative example: Negative example:
......
...@@ -38,7 +38,9 @@ ...@@ -38,7 +38,9 @@
- [Component ID](ts-universal-attributes-component-id.md) - [Component ID](ts-universal-attributes-component-id.md)
- [Touch Target](ts-universal-attributes-touch-target.md) - [Touch Target](ts-universal-attributes-touch-target.md)
- [Polymorphic Style](ts-universal-attributes-polymorphic-style.md) - [Polymorphic Style](ts-universal-attributes-polymorphic-style.md)
- [Hit Test Control](ts-universal-attributes-hit-test-behavior.md)
- [Background Blur](ts-universal-attributes-backgroundBlurStyle.md) - [Background Blur](ts-universal-attributes-backgroundBlurStyle.md)
- [restoreId](ts-universal-attributes-restoreId.md)
- Gesture Processing - Gesture Processing
- [Gesture Binding Methods](ts-gesture-settings.md) - [Gesture Binding Methods](ts-gesture-settings.md)
- Basic Gestures - Basic Gestures
...@@ -97,10 +99,13 @@ ...@@ -97,10 +99,13 @@
- [Counter](ts-container-counter.md) - [Counter](ts-container-counter.md)
- [Flex](ts-container-flex.md) - [Flex](ts-container-flex.md)
- [GridContainer](ts-container-gridcontainer.md) - [GridContainer](ts-container-gridcontainer.md)
- [GridCol](ts-container-gridcol.md)
- [GridRow](ts-container-gridrow.md)
- [Grid](ts-container-grid.md) - [Grid](ts-container-grid.md)
- [GridItem](ts-container-griditem.md) - [GridItem](ts-container-griditem.md)
- [List](ts-container-list.md) - [List](ts-container-list.md)
- [ListItem](ts-container-listitem.md) - [ListItem](ts-container-listitem.md)
- [ListItemGroup](ts-container-listitemgroup.md)
- [Navigator](ts-container-navigator.md) - [Navigator](ts-container-navigator.md)
- [Panel](ts-container-panel.md) - [Panel](ts-container-panel.md)
- [Refresh](ts-container-refresh.md) - [Refresh](ts-container-refresh.md)
......
# Property Animator # Property Animator
You can create a property animator to animate the universal attributes of a component. You can create a property animator to animate certain universal attributes of a component, including **width**, **height**, backgroundColor, **opacity**, **scale**, **rotate**, and **translate**.
> **NOTE** > **NOTE**
> >
> This event is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > This event is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
| API | Description | animation(value: {duration?: number, tempo?: number, curve?: string | Curve | ICurve, delay?:number, iterations: number, playMode?: PlayMode, onFinish?: () => void})
| ------------------------------ | ------------------------------------------------------------ |
| animation(value: AnimateParam) | Applies a property animator to this component to control the transition of the component from one state to another.|
## AnimateParam Applies a property animator to the component to animate its attributes over time.
- Attributes **Parameters**
| Name | Type | Default Value | Description | | Name | Type | Mandatory | Description |
| ---------- | ---------------------------------------- | --------------- | ----------------------- | | ---------- | ------------------------------------------| ---- | ------------------------------------------------------------ |
| duration | number | 1000 | Animation duration, in ms. The default duration is 1000 ms. | | duration | number | No | Animation duration, in ms.<br>Default value: **1000**|
| curve | [Curve](ts-appendix-enums.md#curve) | Curve.Linear | Animation curve. The default curve is linear. | | tempo | number | No | Animation playback speed. A greater value indicates a higher animation playback speed.<br>The value **0** indicates that no animation is applied.<br>Default value: **1**|
| delay | number | 0 | Delay of animation playback, in ms. By default, the playback is not delayed. | | curve | string&nbsp;\|&nbsp;[Curve](ts-appendix-enums.md#curve)&nbsp;\|&nbsp;ICurve<sup>9+</sup> | No | Animation curve.<br>Default value: **Curve.Linear** |
| iterations | number | 1 | Number of times that the animation is played. By default, the animation is played once. The value **-1** indicates that the animation is played for an unlimited number of times. | | delay | number | No | Delay of animation playback, in ms. The value **0** indicates that the playback is not delayed.<br>Default value: **0** |
| playMode | [PlayMode](ts-appendix-enums.md#playmode) | PlayMode.Normal | Animation playback mode. By default, the animation is played from the beginning after the playback is complete.| | iterations | number | No | Number of times that the animation is played. The value **-1** indicates that the animation is played for an unlimited number of times.<br>Default value: **1**|
| playMode | [PlayMode](ts-appendix-enums.md#playmode) | No | Animation playback mode. By default, the animation is played from the beginning after the playback is complete.<br>Default value: **PlayMode.Normal**|
| onFinish | () => void | No | Callback invoked when the animation playback is complete. |
## Example ## Example
...@@ -31,9 +31,9 @@ You can create a property animator to animate the universal attributes of a comp ...@@ -31,9 +31,9 @@ You can create a property animator to animate the universal attributes of a comp
@Entry @Entry
@Component @Component
struct AttrAnimationExample { struct AttrAnimationExample {
@State widthSize: number = 200 @State widthSize: number = 200;
@State heightSize: number = 100 @State heightSize: number = 100;
@State flag: boolean = true @State flag: boolean = true;
build() { build() {
Column() { Column() {
......
...@@ -8,6 +8,7 @@ ...@@ -8,6 +8,7 @@
| Blue | 0x0000ff | ![en-us_image_0000001174104404](figures/en-us_image_0000001174104404.png) | | Blue | 0x0000ff | ![en-us_image_0000001174104404](figures/en-us_image_0000001174104404.png) |
| Brown | 0xa52a2a | ![en-us_image_0000001219744201](figures/en-us_image_0000001219744201.png) | | Brown | 0xa52a2a | ![en-us_image_0000001219744201](figures/en-us_image_0000001219744201.png) |
| Gray | 0x808080 | ![en-us_image_0000001174264376](figures/en-us_image_0000001174264376.png) | | Gray | 0x808080 | ![en-us_image_0000001174264376](figures/en-us_image_0000001174264376.png) |
| Grey | 0x808080 | ![en-us_image_0000001174264376](figures/en-us_image_0000001174264376.png) |
| Green | 0x008000 | ![en-us_image_0000001174422914](figures/en-us_image_0000001174422914.png) | | Green | 0x008000 | ![en-us_image_0000001174422914](figures/en-us_image_0000001174422914.png) |
| Orange | 0xffa500 | ![en-us_image_0000001219662661](figures/en-us_image_0000001219662661.png) | | Orange | 0xffa500 | ![en-us_image_0000001219662661](figures/en-us_image_0000001219662661.png) |
| Pink | 0xffc0cb | ![en-us_image_0000001219662663](figures/en-us_image_0000001219662663.png) | | Pink | 0xffc0cb | ![en-us_image_0000001219662663](figures/en-us_image_0000001219662663.png) |
...@@ -70,6 +71,7 @@ ...@@ -70,6 +71,7 @@
| Press | The mouse button is pressed.| | Press | The mouse button is pressed.|
| Release | The mouse button is released.| | Release | The mouse button is released.|
| Move | The mouse cursor moves. | | Move | The mouse cursor moves. |
| Hover | The mouse pointer is hovered on an element. |
## Curve ## Curve
...@@ -100,10 +102,12 @@ ...@@ -100,10 +102,12 @@
## FillMode ## FillMode
| Name | Description | | Name | Description |
| -------- | -------------------------------- | | --------- | ------------------------------------------------------------ |
| None | After the playback is complete, the animation restores to the initial state. | | None | Before execution, the animation does not apply any styles to the target component. After execution, the animation restores the target component to its default state.|
| Forwards | After the playback is complete, the animation remains in the end state.| | Forwards | The target component retains the state set by the last keyframe encountered during execution of the animation. |
| Backwards | The animation applies the values defined in the first relevant keyframe once it is applied to the target component, and retains the values during the period set by **delay**. The first relevant keyframe depends on the value of **playMode**. If **playMode** is **Normal** or **Alternate**, the first relevant keyframe is in the **from** state. If **playMode** is **Reverse** or **AlternateReverse**, the first relevant keyframe is in the **to** state.|
| Both | The animation follows the rules for both **Forwards** and **Backwards**, extending the animation attributes in both directions.|
## PlayMode ## PlayMode
...@@ -133,11 +137,11 @@ ...@@ -133,11 +137,11 @@
| Name | Description | | Name | Description |
| -------- | ---------------------- | | -------- | ---------------------- |
| Top | Top edge in the vertical direction. | | Top | Top edge in the vertical direction. |
| Center | Center position in the vertical direction. | | Center<sup>(deprecated) </sup> | Center position in the vertical direction.<br> This API is deprecated since API version 9. |
| Bottom | Bottom edge in the vertical direction. | | Bottom | Bottom edge in the vertical direction. |
| Baseline | Text baseline position in the cross axis direction.| | Baseline<sup>(deprecated) </sup> | Text baseline position in the cross axis direction.<br> This API is deprecated since API version 9.|
| Start | Start position in the horizontal direction. | | Start | Start position in the horizontal direction. |
| Middle | Center position in the horizontal direction. | | Middle<sup>(deprecated) </sup> | Center position in the horizontal direction.<br>This API is deprecated since API version 9. |
| End | End position in the horizontal direction. | | End | End position in the horizontal direction. |
## Week ## Week
...@@ -217,9 +221,9 @@ ...@@ -217,9 +221,9 @@
| Name | Description | | Name | Description |
| ------ | -------------------- | | ------ | -------------------- |
| Butt | The ends of dividing lines are butt.| | Butt | The ends of the line are squared off, and the line does not extend beyond its two endpoints.|
| Round | The ends of dividing lines are rounded. | | Round | The line is extended at the endpoints by a half circle whose diameter is equal to the line width.|
| Square | The ends of dividing lines are butt.| | Square | The line is extended at the endpoints by a rectangle whose width is equal to half the line width and height equal to the line width.|
## Axis ## Axis
...@@ -251,12 +255,12 @@ ...@@ -251,12 +255,12 @@
| Name | Description | | Name | Description |
| -------- | ------------------------------------------------------------ | | -------- | ------------------------------------------------------------ |
| Auto | The default configuration in the Flex container is used. | | Auto | The default configuration in the flex container is used. |
| Start | The elements are in the Flex container, top-aligned in the cross-axis direction. | | Start | The elements are in the flex container, top-aligned in the cross-axis direction. |
| Center | The elements are in the Flex container, centered in the cross-axis direction. | | Center | The elements are in the flex container, centered in the cross-axis direction. |
| End | The elements are in the Flex container, bottom-aligned in the cross-axis direction. | | End | The elements are in the flex container, bottom-aligned in the cross-axis direction. |
| Stretch | The elements are in the Flex container, stretched and padded in the cross-axis direction. If the size is not set, the elements are stretched to the container size.| | Stretch | The elements are in the flex container, stretched and padded in the cross-axis direction. If the size is not set, the elements are stretched to the container size.|
| Baseline | The elements are in the Flex container, text baseline aligned in the cross-axis direction. | | Baseline | The elements are in the flex container, text baseline aligned in the cross-axis direction. |
## FlexDirection ## FlexDirection
...@@ -271,9 +275,9 @@ ...@@ -271,9 +275,9 @@
| Name | Description | | Name | Description |
| ----------- | ------------------------------------------------- | | ----------- | ------------------------------------------------- |
| NoWrap | The child components in the **\<Flex>** component are arranged in a single line, and they cannot overflow. | | NoWrap | The child components in the flex container are arranged in a single line, and they cannot overflow. |
| Wrap | The child components in the **\<Flex>** component are arranged in multiple lines, and they may overflow. | | Wrap | The child components in the flex container are arranged in multiple lines, and they may overflow. |
| WrapReverse | The child components in the **\<Flex>** component are reversely arranged in multiple lines, and they may overflow.| | WrapReverse | The child components in the flex container are reversely arranged in multiple lines, and they may overflow.|
## VerticalAlign ## VerticalAlign
...@@ -417,7 +421,7 @@ ...@@ -417,7 +421,7 @@
| Name | Description | | Name | Description |
| ----------- | -------------------- | | ----------- | -------------------- |
| Default | Both the node and its child node respond to the hit test of a touch event, and other nodes blocked by the node are not considered during the hit test. | | Default | Both the node and its child node respond to the hit test of a touch event, but its sibling node is blocked from the hit test. |
| Block | The node responds to the hit test of a touch event, and its child node and other nodes blocked by the node are not considered during the hit test. | | Block | The node responds to the hit test of a touch event, but its child node and sibling node are blocked from the hit test. |
| Transparent | Both the node and its child node respond to the hit test of a touch event, and other nodes blocked by the node are also considered during the hit test.| | Transparent | Both the node and its child node respond to the hit test of a touch event, and its sibling node is also considered during the hit test.|
| None | The node does not respond to the hit test of a touch event, but its child nodes are considered during the hit test.| | None | The node does not respond to the hit test of a touch event, but its child node and sibling node are considered during the hit test.|
# Blank # Blank
The **\<Blank>** component is able to automatically fill the empty spaces in the container along the main axis. It is valid only when the parent component is **\<Row>** or **\<Column>**.
> **NOTE** > **NOTE**
> >
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
The **\<Blank>** component supports automatic filling of the empty part of the container along the main axis. This component is valid only when the parent component is **\<Row>** or **\<Column>**.
## Required Permissions
None
## Child Components ## Child Components
...@@ -21,28 +14,25 @@ Not supported ...@@ -21,28 +14,25 @@ Not supported
## APIs ## APIs
Blank(min?: Length) Blank(min?: number | string)
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| min | [Length](../../ui/ts-types.md) | No | 0 | Minimum size of the **&lt;Blank&gt;** component in the container along the main axis. |
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| min | number \| string | No| Minimum size of the **\<Blank>** component in the container along the main axis.<br>Default value: **0**|
## Attributes ## Attributes
| Name | Type | Default Value | Description | In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported.
| -------- | -------- | -------- | -------- |
| color | [ResourceColor](../../ui/ts-types.md) | 0xffffff | Color to fill the blank. |
> **NOTE** | Name| Type| Description|
> | -------- | -------- | -------- |
> Universal attribute methods are not supported. | color | [ResourceColor](ts-types.md#resourcecolor) | Color to fill the empty spaces.|
## Example ## Example
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
......
...@@ -2,70 +2,63 @@ ...@@ -2,70 +2,63 @@
The **\<Button>** component can be used to create different types of buttons. The **\<Button>** component can be used to create different types of buttons.
> **NOTE** > **NOTE**
> >
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions ## Child Components
None This component can contain only one child component.
## Child Components ## APIs
Supported **Method 1:** Button(options?: {type?: ButtonType, stateEffect?: boolean})
**Parameters**
## APIs | Name | Type | Mandatory | Description |
| ----------- | ---------- | ------| --------------------------------- |
| type | ButtonType | No | Button type.<br>Default value: **ButtonType.Capsule** |
| stateEffect | boolean | No | Whether to enable the state switchover effect for when the button is touched or clicked. The value **false** indicates that the state switchover effect is disabled.<br>Default value: **true**|
- Button(options?: {type?: ButtonType, stateEffect?: boolean})
**Table 1** options parameters
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| type | ButtonType | No | Capsule | Button type. |
| stateEffect | boolean | No | true | Whether to enable the state switchover effect when a button is pressed. When the state is set to **false**, the state switchover effect is disabled. |
**Method 2:** Button(label?: ResourceStr, options?: { type?: ButtonType, stateEffect?: boolean })
- Button(label?: ResourceStr, options?: { type?: ButtonType, stateEffect?: boolean }) Creates a button component based on text content. In this case, the component cannot contain child components.
Creates a button component based on text content. In this case, the **\<Button>** component cannot contain child components.
**Table 2** Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- | -------- | | ------- | ----------------------------------- | ---- | ------------- |
| label | [ResourceStr](../../ui/ts-types.md) | No | - | Button text. | | label | [ResourceStr](ts-types.md#resourcestr) | No | Button text. |
| options | Object | No | - | For details, see the **options** parameters. | | options | Object | No | For details, see **options**.|
## Attributes ## Attributes
| Name | Type | Default Value | Description | | Name | Type | Description |
| -------- | -------- | -------- | -------- | | ----------- | ----------- | --------------------------------- |
| type | ButtonType | Capsule | Button type. | | type | ButtonType | Button type.<br>Default value: **ButtonType.Capsule** |
| stateEffect | boolean | true | Whether to enable the state switchover effect. When the state is set to **false**, the state switchover effect is disabled. | | stateEffect | boolean | Whether to enable the state switchover effect. The value **false** indicates that the state switchover effect is disabled.<br>Default value: **true**|
**ButtonType** enums ## ButtonType enums
| Name | Description | | Name | Description |
| -------- | -------- | | ------- | ------------------ |
| Capsule | Capsule-type button (the round corner is half of the height by default). | | Capsule | Capsule-type button (the round corner is half of the height by default).|
| Circle | Circle button. | | Circle | Circle button. |
| Normal | Normal button (without rounded corners by default). | | Normal | Normal button (without rounded corners by default). |
> **NOTE** > **NOTE**
> - The rounded corner of a button is set by using [Border](ts-universal-attributes-border.md). (The rounded corner cannot be set by using a border API.) > - The rounded corner of a button is set by using [borderRadius](ts-universal-attributes-border.md), rather than by using the **border** API.
> - When the button type is **Capsule**, the **borderRadius** settings do not take effect, and the rounded corner of the button is always half of the button height. > - For a button of the **Capsule** type, the **borderRadius** settings do not take effect, and its rounded corner is always half of the button height.
> - When the button type is **Circle**, the value of **borderRadius** is used as the button radius. If **borderRadius** is not set, the button radius is half of the width or height, whichever is smaller. > - For a button of the **Circle** type, its radius is the value of **borderRadius** (if set) or the width or height (whichever is smaller).
> - The button text is set using the [common text style](ts-universal-attributes-text-style.md). > - The button text is set using the [text style attributes](ts-universal-attributes-text-style.md).
## Example ## Example
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
...@@ -78,7 +71,7 @@ struct ButtonExample { ...@@ -78,7 +71,7 @@ struct ButtonExample {
Button('Ok', { type: ButtonType.Normal, stateEffect: true }).borderRadius(8).backgroundColor(0x317aff).width(90) Button('Ok', { type: ButtonType.Normal, stateEffect: true }).borderRadius(8).backgroundColor(0x317aff).width(90)
Button({ type: ButtonType.Normal, stateEffect: true }) { Button({ type: ButtonType.Normal, stateEffect: true }) {
Row() { Row() {
// You are advised to reference an image by using $r to create a Resource object. // To import an image, you are advised to create a Resource object through $r.
Image($r('app.media.loading')).width(20).height(20).margin({ left: 12 }) Image($r('app.media.loading')).width(20).height(20).margin({ left: 12 })
Text('loading').fontSize(12).fontColor(0xffffff).margin({ left: 5, right: 12 }) Text('loading').fontSize(12).fontColor(0xffffff).margin({ left: 5, right: 12 })
}.alignItems(VerticalAlign.Center) }.alignItems(VerticalAlign.Center)
......
...@@ -12,7 +12,7 @@ Not supported ...@@ -12,7 +12,7 @@ Not supported
## APIs ## APIs
Checkbox( option?: {name?: string, group?: string }) Checkbox(options?: {name?: string, group?: string })
**Parameters** **Parameters**
...@@ -29,7 +29,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the ...@@ -29,7 +29,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| Name | Type| Description| | Name | Type| Description|
| ------------- | ------- | -------- | | ------------- | ------- | -------- |
| select | boolean | Whether the check box is selected.<br>Default value: **false**| | select | boolean | Whether the check box is selected.<br>Default value: **false**|
| selectedColor | [ResourceColor](../../ui/ts-types.md) | Color of the check box when it is selected.| | selectedColor | [ResourceColor](ts-types.md#resourcecolor) | Color of the check box when it is selected.|
## Events ## Events
......
...@@ -12,7 +12,7 @@ None ...@@ -12,7 +12,7 @@ None
## APIs ## APIs
CheckboxGroup( group?: string ) CheckboxGroup(options?: { group?: string })
Creates a check box group so that you can select or deselect all check boxes in the group at the same time. Check boxes and the check box group that share the group name belong to the same group. Creates a check box group so that you can select or deselect all check boxes in the group at the same time. Check boxes and the check box group that share the group name belong to the same group.
...@@ -31,15 +31,21 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the ...@@ -31,15 +31,21 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| Name| Type| Description| | Name| Type| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| selectAll | boolean | Whether to select all.<br>Default value: **false**| | selectAll | boolean | Whether to select all.<br>Default value: **false**|
| selectedColor | [ResourceColor](../../ui/ts-types.md) | Color of the selected check box.| | selectedColor | [ResourceColor](ts-types.md#resourcecolor) | Color of the selected check box.|
## Events ## Events
In addition to the universal events (ts-universal-events-click.md), the following events are supported. In addition to the [universal events](ts-universal-events-click.md), the following events are supported.
| Name| Description| | Name| Description|
| -------- | -------- | | -------- | -------- |
| onChange (callback: (names: Array&lt;string&gt;, status: SelectStatus) => void ) |Triggered when the selection status of the check box group or any check box wherein changes.<br>- **names**: names of all selected check boxes in the group.<br>- **status**: selection status.| | onChange (callback: (event: CheckboxGroupResult) => void ) |Triggered when the selection status of the check box group or any check box wherein changes.|
## CheckboxGroupResult
| Name | Type | Description |
| ------ | ------ | ------- |
| name | Array&lt;string&gt; | Names of all the selected check boxes in the group.|
| status | SelectStatus | Selected status.|
## SelectStatus ## SelectStatus
......
# DataPanel # DataPanel
The **\<DataPanel>** component displays proportions in a chart. The **\<DataPanel>** component displays proportions in a chart.
> **NOTE** > **NOTE**
> >
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
None
## Child Components ## Child Components
...@@ -19,25 +16,25 @@ Not supported ...@@ -19,25 +16,25 @@ Not supported
## APIs ## APIs
DataPanel(value:{values: number[], max?: number, type?: DataPanelType}) DataPanel(options:{values: number[], max?: number, type?: DataPanelType})
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| values | number[] | Yes | - | Value list. A maximum of nine values are supported. |
| max | number | No | 100 | - When set to a value greater than 0, this parameter indicates the maximum value in the **values** list.<br/>- When set to a value equal to or smaller than 0, this parameter indicates the sum of values in the **values** list. The values are displayed in proportion. |
| type<sup>8+</sup> | DataPanelType | No | DataPanelType.Circle | Type of the data panel. |
| Name | Type | Mandatory | Description|
| ----------------- | -------- | ----- | -------- |
| values | number[] | Yes | Value list. A maximum of nine values are supported.|
| max | number | No | - When set to a value greater than 0, this parameter indicates the maximum value in the **values** list.<br>- When set to a value equal to or smaller than 0, this parameter indicates the sum of values in the **values** list. The values are displayed in proportion.<br>Default value: **100**|
| type<sup>8+</sup> | DataPanelType | No| Type of the data panel.<br>Default value: **DataPanelType.Circle**|
- DataPanelType enums
| Name | Description |
| -------- | -------- |
| Line | Line data panel. |
| Circle | Circle data panel. |
## DataPanelType enums
| Name| Description|
| -------| ------------ |
| Line | Line data panel.|
| Circle | Circle data panel.|
## Example
## Example
```ts ```ts
// xxx.ets // xxx.ets
......
# DatePicker # DatePicker
> **NOTE**<br>
> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
The **\<DatePicker>** component allows users to select a date from the given range. The **\<DatePicker>** component allows users to select a date from the given range.
> **NOTE**
>
> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
No
## Child Components ## Child Components
No Not supported
## APIs ## APIs
DatePicker(options?: DatePickerOptions) DatePicker(options?: {start?: Date, end?: Date, selected?: Date})
Creates a date picker in the given date range. Creates a date picker in the given date range.
- options parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description | | Name| Type| Mandatory | Description|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | ------------- | -------- |
| start | Date | No| Date('1970-1-1') | Start date of the picker. | | start | Date | No | Start date of the picker.<br>Default value: **Date('1970-1-1')**|
| end | Date | No| Date('2100-12-31') | End date of the picker. | | end | Date | No | End date of the picker.<br>Default value: **Date('2100-12-31')**|
| selected | Date | No| Current system date| Date of the selected item. | | selected | Date | No | Date of the selected item.<br>Default value: current system date |
## Attributes ## Attributes
| Name| Type | Default Value | Description | | Name | Type | Description |
| -------- | -------- | -------- | -------- | | ------| -------------- | -------- |
| lunar | boolean | false | Whether to display the lunar calendar.<br>-&nbsp;**true**: Display the lunar calendar.<br>-&nbsp;**false**: Do not display the lunar calendar. | | lunar | boolean | Whether to display the lunar calendar.<br>-&nbsp;**true**: Display the lunar calendar.<br>-&nbsp;**false**: Do not display the lunar calendar.<br>Default value: **false**|
## Events ## Events
| Name | Description | | Name| Description|
| -------- | -------- | | -------- | -------- |
| onChange(callback:&nbsp;(value:&nbsp;DatePickerResult)&nbsp;=&gt;&nbsp;void) | Invoked when a date is selected. | | onChange(callback:&nbsp;(value:&nbsp;DatePickerResult)&nbsp;=&gt;&nbsp;void) | Triggered when a date is selected.|
### DatePickerResult ## DatePickerResult
| Name | Type | Description |
| Name| Type| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| year | number | Year of the selected date. | | year | number | Year of the selected date.|
| month | number | Month of the selected date. The value ranges from 0 to 11. The value **0** indicates January, and the value **11** indicates December. | | month | number | Month of the selected date. The value ranges from 0 to 11. The value **0** indicates January, and **11** indicates December.|
| day | number | Day of the selected date. | | day | number | Day of the selected date.|
## Example ## Example
...@@ -57,7 +55,8 @@ Creates a date picker in the given date range. ...@@ -57,7 +55,8 @@ Creates a date picker in the given date range.
### Date Picker Sample Code (With Lunar Calendar) ### Date Picker Sample Code (With Lunar Calendar)
``` ```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct DatePickerExample01 { struct DatePickerExample01 {
...@@ -82,7 +81,8 @@ struct DatePickerExample01 { ...@@ -82,7 +81,8 @@ struct DatePickerExample01 {
### Date Picker Sample Code (No Lunar Calendar) ### Date Picker Sample Code (No Lunar Calendar)
``` ```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct DatePickerExample02 { struct DatePickerExample02 {
...@@ -104,4 +104,4 @@ struct DatePickerExample02 { ...@@ -104,4 +104,4 @@ struct DatePickerExample02 {
} }
``` ```
![en-us_image_0000001251092975](figures/en-us_image_0000001251092975.png)
# Divider # Divider
The **\<Divider>** component is used to separate content blocks and elements.
> **NOTE** > **NOTE**
> >
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
The **\<Divider>** component is used to separate content blocks and content elements.
## Required Permissions
None
## Child Components ## Child Components
...@@ -23,25 +16,25 @@ Not supported ...@@ -23,25 +16,25 @@ Not supported
Divider() Divider()
## Attributes ## Attributes
| Name | Type | Default Value | Description | In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported.
| -------- | -------- | -------- | -------- |
| vertical | boolean | false | Whether a vertical divider is used. The value **true** means that a vertical divider is used, and **false** means that a horizontal divider is used. | | Name | Type | Description |
| color | Color | - | Color of the divider. | | ----------- | ---------- | ------------------ |
| strokeWidth | Length | 1 | Width of the divider. | | vertical | boolean | Whether a vertical divider is used. **false**: A horizontal divider is used.<br>**true**: A vertical divider is used.<br>Default value: **false**|
| lineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle-enums) | LineCapStyle.Butt | Cap style of the divider. | | color | [ResourceColor](ts-types.md#resourcecolor) | Color of the divider.|
| strokeWidth | number \| string | Width of the divider.<br>Default value: **1**|
| lineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | Cap style of the divider.<br>Default value: **LineCapStyle.Butt**|
## Events ## Events
Universal events are not supported. The universal events are not supported.
## Example ## Example
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
......
# Gauge # Gauge
The **\<Gauge>** component is used to display data in a ring chart. The **\<Gauge>** component is used to display data in a ring chart.
> **NOTE** > **NOTE**
> >
> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. > This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
None
## Child Components ## Child Components
Not supported Not supported
...@@ -22,23 +17,25 @@ Not supported ...@@ -22,23 +17,25 @@ Not supported
Gauge(options:{value: number, min?: number, max?: number}) Gauge(options:{value: number, min?: number, max?: number})
- Parameters **Parameters**
| Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- |
| value | number | Yes| - | Current data value.|
| min | number | No| 0 | Minimum value of the current data segment.|
| max | number | No| 100 | Maximum value of the current data segment.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| value | number | Yes| Current data value.|
| min | number | No| Minimum value of the current data segment.<br>Default value: **0**|
| max | number | No| Maximum value of the current data segment.<br>Default value: **100**|
## Attributes ## Attributes
| Name| Type| Default Value| Description| In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported.
| -------- | -------- | -------- | -------- |
| value | number | 0 | Value of the chart.| | Name| Type| Description|
| startAngle | number | -150 | Start angle of the chart. The value 0 indicates 0 degrees, and a positive value indicates the clockwise direction.| | -------- | -------- | -------- |
| endAngle | number | 150 | End angle of the chart. The value 0 indicates 0 degrees, and a positive value indicates the clockwise direction.| | value | number | Value of the chart.<br>Default value: **0**|
| colors | Array&lt;ColorStop&gt; | - | Colors of the chart. Colors can be set for individual segments.| | startAngle | number | Start angle of the chart. The value 0 indicates 0 degrees, and a positive value indicates the clockwise direction.<br>Default value: **-150**|
| strokeWidth | Length | - | Stroke width of the chart.| | endAngle | number | End angle of the chart. The value 0 indicates 0 degrees, and a positive value indicates the clockwise direction.<br>Default value: **150**|
| colors | Array&lt;ColorStop&gt; | Colors of the chart. Colors can be set for individual segments.|
| strokeWidth | Length | Stroke width of the chart.|
## ColorStop ## ColorStop
...@@ -46,7 +43,7 @@ Describes a gradient stop. ...@@ -46,7 +43,7 @@ Describes a gradient stop.
| Name | Type | Description | | Name | Type | Description |
| --------- | -------------------- | ------------------------------------------------------------ | | --------- | -------------------- | ------------------------------------------------------------ |
| ColorStop | [[ResourceColor](../../ui/ts-types.md#resourcecolor8), number] | Type of the gradient stop. The first parameter specifies the color, and the second parameter specifies the offset, which ranges from 0 to 1.| | ColorStop | [[ResourceColor](ts-types.md#resourcecolor), number] | Type of the gradient stop. The first parameter specifies the color, and the second parameter specifies the offset, which ranges from 0 to 1.|
## Example ## Example
......
...@@ -9,17 +9,7 @@ The **\<Image>** component is used to render and display local and online images ...@@ -9,17 +9,7 @@ The **\<Image>** component is used to render and display local and online images
## Required Permissions ## Required Permissions
To use online images, you need to add the **ohos.permission.INTERNET** permission to the corresponding abilities in the **config.json** (for the FA model) or **module.json5** file (for the stage model). To use online images, the application must have the **ohos.permission.INTERNET** permission. For details about how to apply for a permission, see [Declaring Permissions](../../security/accesstoken-guidelines.md).
```
"abilities": [
{
...
"permissions": ["ohos.permission.INTERNET"],
...
}
]
```
## Child Components ## Child Components
...@@ -35,35 +25,33 @@ Obtains an image from the specified source for subsequent rendering and display. ...@@ -35,35 +25,33 @@ Obtains an image from the specified source for subsequent rendering and display.
**Parameters** **Parameters**
| Name | Type | Mandatory | Default Value | Description | | Name| Type | Mandatory| Description |
| ---- | ---------------------------------------- | ---- | ---- | ---------------------------------------- | | ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| src | string \| [PixelMap](../apis/js-apis-image.md#pixelmap7) \| [Resource](../../ui/ts-types.md#resource-type) | Yes | - | Image source. Both local and online images are supported.<br>When using resources referenced using a relative path, for example, `Image("common/test.jpg")`, the **\<Image>** component cannot be called across bundles or modules. Therefore, you are advised to use `$r` to reference image resources that need to be used globally.<br>- The following image formats are supported: PNG, JPG, BMP, SVG, GIF.<br>\- Base64 strings are supported. \ The value format is `data:image/[png\|jpeg\|bmp\|webp];base64,[base64 data]`, where `[base64 data]` is a Base64 string.<br/>\- The value can also be a path starting with `dataability://`, which is used to access the image path provided by a Data ability.| | src | string\| [PixelMap](../apis/js-apis-image.md#pixelmap7) \| [Resource](ts-types.md#resource) | Yes | Image source. Both local and online images are supported.<br>When using an image referenced using a relative path, for example, `Image("common/test.jpg")`, the **\<Image>** component cannot be called across bundles or modules. Therefore, you are advised to use `$r` to reference image resources that need to be used globally.<br>- The following image formats are supported: PNG, JPG, BMP, SVG, GIF.<br>\- Base64 strings are supported. \ The value format is `data:image/[png\|jpeg\|bmp\|webp];base64,[base64 data]`, where `[base64 data]` is a Base64 string.<br/>\- The value can also be a path starting with `dataability://`, which is used to access the image path provided by a Data ability.|
## Attributes ## Attributes
In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported.
| Name | Type | Default Value | Description | | Name | Type | Description |
| --------------------- | ------------------------------------------------------- | ------------------------ | ------------------------------------------------------------ | | --------------------- | ------------------------------------------------------- | ------------------------------------------------------------ |
| alt | string \| [Resource](../../ui/ts-types.md#resource-type) | - | Placeholder image displayed during loading. Both local and Internet URIs are supported. | | alt | string \| [Resource](ts-types.md#resource)| Placeholder image displayed during loading. Both local and Internet URIs are supported. |
| objectFit | ImageFit | ImageFit.Cover | Image scale type. | | objectFit | [ImageFit](ts-appendix-enums.md#imagefit) | Image scale mode.<br>Default value: **ImageFit.Cover** |
| objectRepeat | [ImageRepeat](ts-appendix-enums.md#imagerepeat) | NoRepeat | Whether the image is repeated.<br>**NOTE**<br>This attribute is not applicable to SVG images. | | objectRepeat | [ImageRepeat](ts-appendix-enums.md#imagerepeat) | Whether the image is repeated.<br>Default value: **NoRepeat**<br>**NOTE**<br>This attribute is not applicable to SVG images.|
| interpolation | [ImageInterpolation](#imageinterpolation) | ImageInterpolation.None | Interpolation effect of the image. This attribute is intended to alleviate aliasing that occurs when a low-definition image is zoomed in.<br>**NOTE**<br>> This attribute is not applicable to SVG images.<br>> This attribute is not applicable to **PixelMap** objects. | | interpolation | [ImageInterpolation](#imageinterpolation) | Interpolation effect of the image. This attribute is intended to alleviate aliasing that occurs when a low-definition image is zoomed in.<br>Default value: **ImageInterpolation.None**<br>**NOTE**<br>This attribute is not applicable to SVG images.<br>This attribute is not applicable to **PixelMap** objects.|
| renderMode | [ImageRenderMode](#imagerendermode) | ImageRenderMode.Original | Rendering mode of the image.<br>**NOTE**<br>This attribute is not applicable to SVG images. | | renderMode | [ImageRenderMode](#imagerendermode) | Rendering mode of the image.<br>Default value: **ImageRenderMode.Original**<br>**NOTE**<br>This attribute is not applicable to SVG images.|
| sourceSize | {<br>width: number,<br>height: number<br>} | - | Decoding size of the image. The original image is decoded into an image of the specified size, in px.<br>**NOTE**<br>This attribute is not applicable to **PixelMap** objects. | | sourceSize | {<br>width: number,<br>height: number<br>} | Size of the decoded image. The original image is decoded into a **pixelMap** of the specified size, in px.<br>**NOTE**<br>This attribute is not applicable to **PixelMap** objects.|
| syncLoad<sup>8+</sup> | boolean | false | Whether to load images synchronously. By default, images are loaded asynchronously. During synchronous loading, the UI thread is blocked and the placeholder diagram is not displayed. | | matchTextDirection | boolean | Whether to display the image in the system language direction. When this parameter is set to true, the image is horizontally flipped in the right-to-left (RTL) language context.<br>Default value: **false** |
| copyOption<sup>9+</sup> | [CopyOptions](#copyoptions) | CopyOptions.None | Whether the image can be copied. (SVG images cannot be copied.)| | fitOriginalSize | boolean | Whether to fit the component to the original size of the image source when the component size is not set.<br>Default value: **true** |
| colorFilter<sup>9+</sup> | [ColorFilter](../../ui/ts-types.md) | - | Color filter of the image. | | fillColor | [ResourceColor](ts-types.md#resourcecolor) | Fill color of the image. This attribute only applies to an SVG image. Once set, the fill color will replace that of the SVG image.|
| autoResize | boolean | Whether to resize the image source used for drawing based on the size of the display area during image decoding. This resizing can help reduce the memory usage.<br>Default value: **true**|
### ImageFit | syncLoad<sup>8+</sup> | boolean | Whether to load the image synchronously. By default, the image is loaded asynchronously. During synchronous loading, the UI thread is blocked and the placeholder diagram is not displayed.<br>Default value: **false**|
| copyOption<sup>9+</sup> | [CopyOptions](ts-appendix-enums.md#copyoptions9) | Whether the image can be copied. (SVG images cannot be copied.)<br>When **copyOption** is set to a value other than **CopyOptions.None**, the image can be copied in various manners, such as long pressing, right-clicking, or pressing Ctrl+C.<br>Default value: **CopyOptions.None**|
| Name | Description | | colorFilter<sup>9+</sup> | [ColorFilter](ts-types.md#colorfilter9) | Color filter of the image.|
| --------- | ------------------------------------------------------------ |
| Cover | The image is scaled with its aspect ratio retained for both sides to be greater than or equal to the display boundaries.| > **NOTE**
| Contain | The image is scaled with its aspect ratio retained for the content to be completely displayed within the display boundaries. | >
| Fill | The image is scaled to fill the display area, and its aspect ratio is not retained. | > To use the shortcut keys to copy an **\<Image>** component, first set the **focusable** and **focusOnTouch** attributes of the component to **true** so that it can have focus.
| None | The image is displayed in its original size. |
| ScaleDown | The image is displayed with its aspect ratio retained, in a size smaller than or equal to the original size. |
### ImageInterpolation ### ImageInterpolation
...@@ -81,30 +69,21 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the ...@@ -81,30 +69,21 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| Original | The image is rendered based on the original image, including the color. | | Original | The image is rendered based on the original image, including the color. |
| Template | The image is rendered as a template image, and its color is ignored.| | Template | The image is rendered as a template image, and its color is ignored.|
### CopyOptions<sup>9+</sup>
| Name| Description|
| -------- | -------- |
| None | Copy and paste is not allowed.|
| InApp | Intra-application copy and paste is allowed.|
| LocalDevice | Intra-device copy and paste is allowed.|
| CrossDevice | Cross-device copy and paste is allowed.|
## Events ## Events
In addition to the universal events (ts-universal-events-click.md), the following events are supported. In addition to the [universal events](ts-universal-events-click.md), the following events are supported.
| Name | Description | | Name | Description |
| ------------------------------------------------------------ | ------------------------------------------------------------ | | ---------------------------------------- | ---------------------------------------- |
| onComplete(callback: (event?: { width: number, height: number, componentWidth: number,<br> componentHeight: number, loadingStatus: number }) =&gt; void) | Triggered when an image is successfully loaded. The size of the loaded image is returned.<br>- **width**: width of the image, in pixels.<br>- **height**: height of the image, in pixels.<br>- **componentWidth**: width of the container component, in pixels.<br>- **componentHeight**: height of the container component, in pixels.<br>- **loadingStatus**: image loading status.<br> | | onComplete(callback: (event?: { width: number, height: number, componentWidth: number,<br> componentHeight: number, loadingStatus: number }) =&gt; void) | Triggered when an image is successfully loaded. The size of the loaded image is returned.<br>- **width**: width of the image, in pixels.<br>- **height**: height of the image, in pixels.<br>- **componentWidth**: width of the container component, in pixels.<br>- **componentHeight**: height of the container component, in pixels.<br>- **loadingStatus**: image loading status.<br>|
| onError(callback: (event?: { componentWidth: number, componentHeight: number }) =&gt; void) | Triggered when an exception occurs during image loading.<br>- **componentWidth**: width of the container component, in pixels.<br>- **componentHeight**: height of the container component, in pixels. | | onError(callback: (event?: { componentWidth: number, componentHeight: number , message<sup>9+</sup>: string }) =&gt; void) | Triggered when an exception occurs during image loading.<br>- **componentWidth**: width of the container component, in pixels.<br>- **componentHeight**: height of the container component, in pixels.<br>|
| onFinish(callback: () =&gt; void) | Triggered when the animation playback in the loaded SVG image is complete. If the animation is an infinite loop, this callback is not triggered. | | onFinish(event: () =&gt; void) | Triggered when the animation playback in the loaded SVG image is complete. If the animation is an infinite loop, this callback is not triggered.|
## Example ## Example
### Loading Images ### Loading Images
Load and display different types of images and set the scale type of the images. Load and display different types of images and set the scale mode of the images.
```ts ```ts
@Entry @Entry
...@@ -172,6 +151,72 @@ struct ImageExample1 { ...@@ -172,6 +151,72 @@ struct ImageExample1 {
![en-us_image_0000001211898484](figures/en-us_image_0000001211898484.gif) ![en-us_image_0000001211898484](figures/en-us_image_0000001211898484.gif)
### Loading Online Images
The default network timeout period is 5 minutes for loading online images. When using an online image, you are advised to use **alt** to configure the placeholder image displayed during loading. If more flexible network configuration is required, use the [HTTP](../../connectivity/http-request.md) module in the SDK to send a network request, and then decode the returned data into a `PixelMap` in the **\<Image>** component. For details about image development, see [Image Development](../../media/image.md). The code snippet is as follows:
```tsx
// @ts-nocheck
import http from '@ohos.net.http';
import ResponseCode from '@ohos.net.http';
import image from '@ohos.multimedia.image'
@Entry
@Component
struct Index {
// Create a PixelMap state variable to receive online images.
@State image: PixelMap = undefined
build() {
Column({space: 10}) {
Button ("Get Online Image")
.onClick(() => {
this.httpRequest();
})
Image(this.image).height(100).width(100)
}
.width('100%')
.height('100%')
.padding(10)
}
// Request an online image.
private httpRequest() {
let httpRequest = http.createHttp();
httpRequest.request(
"https://www.example.com/xxx.png", // Enter a specific URL of the online image.
(error, data) => {
if(error) {
console.log("error code: " + error.code + ", msg: " + error.message)
} else {
let code = data.responseCode
if(ResponseCode.ResponseCode.OK == code) {
let imageSource = image.createImageSource(data.result)
let options = {alphaType: 0, // Transparency
editable: false, // Whether the image is editable
pixelFormat: 3, // Pixel format
scaleMode: 1, // Scale mode
size: {height: 100, width: 100}} // Image size
imageSource.createPixelMap(options).then((pixelMap) => {
this.image = pixelMap
})
} else {
console.log("response code: " + code);
}
}
}
)
}
}
```
**NOTE**<br>For details about the request mode, timeout, and additional request parameters for loading online images, see [`request()`](../../reference/apis/js-apis-http.md) in the HTTP module.
### Setting Attributes ### Setting Attributes
```ts ```ts
......
# ImageAnimator # ImageAnimator
> **NOTE**
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
The **\<ImageAnimator>** component enables images to be played frame by frame. The list of images to be played can be configured, and the duration of each image can be configured. The **\<ImageAnimator>** component enables images to be played frame by frame. The list of images to be played can be configured, and the duration of each image can be configured.
> **NOTE**
>
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
None
## Child Components ## Child Components
...@@ -24,37 +20,38 @@ ImageAnimator() ...@@ -24,37 +20,38 @@ ImageAnimator()
## Attributes ## Attributes
| Name| Type| Default Value| Mandatory| Description| | Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- | -------- | | ---------- | ----------------------- | -------- | -------- |
| images | Array&lt;ImageFrameInfo&gt; | [] | Yes| Image frame information. The information of each frame includes the image path, image size, image position, and image playback duration. For details, see **ImageFrameInfo**.| | images | Array&lt;ImageFrameInfo&gt; | No | Image frame information. The information of each frame includes the image path, image size, image position, and image playback duration. For details, see **ImageFrameInfo**.<br>Default value: **[]** |
| state | [AnimationStatus](ts-appendix-enums.md#animationstatus) | Initial | No| Playback status of the animation. The default status is **Initial**.| | state | [AnimationStatus](ts-appendix-enums.md#animationstatus) | No | Playback status of the animation. The default status is **Initial**.<br>Default value: **AnimationStatus.Initial**|
| duration | number | 1000 | No| Playback duration, in ms. The default duration is 1000 ms. When the duration is **0**, no image is played. The value change takes effect only at the beginning of the next cycle. When a separate duration is set in **images**, the setting of this attribute is invalid.| | duration | number | No | Playback duration, in ms. The default duration is 1000 ms. When the duration is **0**, no image is played. The value change takes effect only at the beginning of the next cycle. When a separate duration is set in **images**, the setting of this attribute is invalid.<br>Default value: **1000**|
| reverse | boolean | false | No| Playback sequence. The value **false** indicates that images are played from the first one to the last one, and **true** indicates that images are played from the last one to the first one.| | reverse | boolean | No | Playback sequence. The value **false** indicates that images are played from the first one to the last one, and **true** indicates that images are played from the last one to the first one.<br>Default value: **false**|
| fixedSize | boolean | true | No| Whether the image size is the same as the component size.<br> **true**: The image size is the same as the component size. In this case, the width, height, top, and left attributes of the image are invalid.<br> **false**: The width, height, top, and left attributes of each image must be set separately.| | fixedSize | boolean | No | Whether the image size is the same as the component size.<br> **true**: The image size is the same as the component size. In this case, the width, height, top, and left attributes of the image are invalid.<br> **false**: The width, height, top, and left attributes of each image must be set separately.<br>Default value: **true**|
| preDecode | number | 0 | No| Whether to enable pre-decoding. The default value **0** indicates that pre-decoding is disabled. The value **2** indicates that two images following the currently playing frame will be cached in advance to improve performance.| | preDecode | number | No | Whether to enable pre-decoding. The default value **0** indicates that pre-decoding is disabled. The value **2** indicates that two images following the currently playing frame will be cached in advance to improve performance.<br>Default value: **0**|
| fillMode | [FillMode](ts-appendix-enums.md#fillmode) | Forwards | No| Status before and after the animation starts. For details about the options, see **FillMode**.| | fillMode | [FillMode](ts-appendix-enums.md#fillmode) | No | Status before and after the animation starts. For details about the options, see **FillMode**.<br>Default value: **FillMode.Forwards**|
| iterations | number | 1 | No| Number of times that the animation is played. By default, the animation is played once. The value **-1** indicates that the animation is played for an unlimited number of times.| | iterations | number | No | Number of times that the animation is played. By default, the animation is played once. The value **-1** indicates that the animation is played for an unlimited number of times.<br>Default value: **1**|
- ImageFrameInfo - ImageFrameInfo
| Name| Type| Default Value| Mandatory| Description|
| -------- | -------- | -------- | -------- | -------- | | Name | Type | Mandatory| Description|
| src | string \| [Resource](.../ui/ts-types.md#resource-type)<sup>9+</sup>| "" | Yes| Image path. The image format can be .svg, .png, or .jpg.| | -------- | -------------- | -------- | -------- |
| width | [Length](.../ui/ts-types.md#length-type)| 0 | No| Image width.| | src | string \| [Resource](ts-types.md#resource)<sup>9+</sup> | Yes | Image path. The image format can be .svg, .png, or .jpg. Since API version 9, this attribute accepts paths of the [Resource](ts-types.md#resource) type.|
| height | [Length](.../ui/ts-types.md#length-type)| 0 | No| Image height.| | width | [Length](ts-types.md#length) | No | Image width.<br>Default value: **0** |
| top | [Length](.../ui/ts-types.md#length-type)| 0 | No| Vertical coordinate of the image relative to the upper left corner of the component.| | height | [Length](ts-types.md#length) | No | Image height.<br>Default value: **0** |
| left | [Length](.../ui/ts-types.md#length-type)| 0 | No| Horizontal coordinate of the image relative to the upper left corner of the component.| | top | [Length](ts-types.md#length) | No | Vertical coordinate of the image relative to the upper left corner of the widget<br>Default value: **0** |
| duration | number | 0 | No| Playback duration of each image frame, in milliseconds.| | left | [Length](ts-types.md#length) | No | Horizontal coordinate of the image relative to the upper left corner of the widget<br>Default value: **0** |
| duration | number | No | Playback duration of each image frame, in milliseconds.<br>Default value: **0** |
## Events ## Events
| Name| Description| | Name| Description|
| -------- | -------- | | -------- | -------- |
| onStart(event: () =&gt; void) | Triggered when the animation starts to play.| | onStart(event:&nbsp;()&nbsp;=&gt;&nbsp;void) | Triggered when the animation starts to play.|
| onPause(event: () =&gt; void) | Triggered when the animation playback is paused.| | onPause(event:&nbsp;()&nbsp;=&gt;&nbsp;void) | Triggered when the animation playback is paused.|
| onRepeat(event: () =&gt; void) | Triggered when the animation playback is repeated.| | onRepeat(event:&nbsp;()&nbsp;=&gt;&nbsp;void) | Triggered when the animation playback is repeated.|
| onCancel(event: () =&gt; void) | Triggered when the animation playback is canceled.| | onCancel(event:&nbsp;()&nbsp;=&gt;&nbsp;void) | Triggered when the animation playback is canceled.|
| onFinish(event: () =&gt; void) | Triggered when the animation playback is complete.| | onFinish(event:&nbsp;()&nbsp;=&gt;&nbsp;void) | Triggered when the animation playback is complete.|
## Example ## Example
......
...@@ -3,35 +3,25 @@ ...@@ -3,35 +3,25 @@
The **\<LoadingProgress>** component is used to create a loading animation. The **\<LoadingProgress>** component is used to create a loading animation.
> **NOTE** > **NOTE**
> > This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
None
## Child Components ## Child Components
None Not supported
## APIs ## APIs
LoadingProgress() LoadingProgress()
Creates a **LoadingProgress** instance. Creates a **\<LoadingProgress>** component.
## Attributes ## Attributes
| Name| Type| Default Value| Description| | Name| Type| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- |
| color | [ResourceColor](../../ui/ts-types.md) | - | Foreground color of the loading progress bar.| | color | [ResourceColor](ts-types.md#resourcecolor) | Foreground color of the **\<LoadingProgress>** component.|
## Example ## Example
......
# Marquee # Marquee
The **\<Marquee>** component is used to display a scrolling piece of text. The text is scrolled only when its width exceeds the width of the **\<Marquee>** component.
> **NOTE** > **NOTE**
> >
> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. > This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
The **\<Marquee>** component is used to display a scrolling piece of text. The text is scrolled only when its width exceeds the width of the **\<Marquee>** component.
## Required Permissions
None
## Child Components ## Child Components
Not supported Not supported
...@@ -23,23 +17,29 @@ Not supported ...@@ -23,23 +17,29 @@ Not supported
Marquee(value: { start: boolean, step?: number, loop?: number, fromStart?: boolean, src: string }) Marquee(value: { start: boolean, step?: number, loop?: number, fromStart?: boolean, src: string })
- Parameters **Parameters**
| Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- | | Name| Type| Mandatory| Description|
| start | boolean | Yes| - | Whether to start scrolling.| | -------- | -------- | -------- | -------- |
| step | number | No| 6 | Scrolling step.| | start | boolean | Yes| Whether to start scrolling.|
| loop | number | No| -1 | Number of times the marquee will scroll. If the value is less than or equal to **0**, the marquee will scroll continuously.| | step | number | No| Scrolling step.<br>Default value: **6**, in vp|
| fromStart | boolean | No| true | Whether the text scrolls from the start.| | loop | number | No| Number of times the marquee will scroll. If the value is less than or equal to **0**, the marquee will scroll continuously.<br>Default value: **-1**|
| src | string | Yes| - | Text to scroll.| | fromStart | boolean | No| Whether the text scrolls from the start.<br>Default value: **true**|
| src | string | Yes| Text to scroll.|
## Attributes
| Name | Type| Description |
| ---------- | -------- | ------------------------------------ |
| allowScale | boolean | Whether to allow text to scale.<br>Default value: **false**|
## Events ## Events
| Name| Description| | Name| Description|
| -------- | -------- | | -------- | -------- |
| onStart(callback:&nbsp;()&nbsp;=&gt;&nbsp;void) | Triggered when the marquee starts scrolling.| | onStart(event: () =&gt; void) | Triggered when the marquee starts scrolling.|
| onBounce(callback:&nbsp;()&nbsp;=&gt;&nbsp;void) | Triggered when the marquee has reached the end.| | onBounce(event: () =&gt; void) | Triggered when the marquee has reached the end. This event will be triggered for multiple times if the **loop** attribute is not set to **1**.|
| onFinish(callback:&nbsp;()&nbsp;=&gt;&nbsp;void) | Triggered when the marquee has finished scrolling.| | onFinish(event: () =&gt; void) | Triggered when the marquee has finished the number of scrolling times set by the **loop** attribute.|
## Example ## Example
...@@ -84,7 +84,7 @@ struct MarqueeExample { ...@@ -84,7 +84,7 @@ struct MarqueeExample {
Button('start') Button('start')
.onClick(() => { .onClick(() => {
this.start = true this.start = true
}) })
.width(200) .width(200)
.height(60) .height(60)
.margin({bottom:20}) .margin({bottom:20})
......
...@@ -2,17 +2,11 @@ ...@@ -2,17 +2,11 @@
The **\<Navigation>** component typically functions as the root container of a page and displays the page title, toolbar, and menu based on the attribute settings. The **\<Navigation>** component typically functions as the root container of a page and displays the page title, toolbar, and menu based on the attribute settings.
> **NOTE** > **NOTE**
> >
> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. > This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
None
## Child Components ## Child Components
Supported Supported
...@@ -24,56 +18,59 @@ Navigation() ...@@ -24,56 +18,59 @@ Navigation()
Creates a component that can automatically display the navigation bar, title, and toolbar based on the attribute settings. Creates a component that can automatically display the navigation bar, title, and toolbar based on the attribute settings.
## Attributes ## Attributes
| Name | Type | Default Value | Description | In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported.
| -------- | -------- | -------- | -------- |
| title | string \| [CustomBuilder](../../ui/ts-types.md) | - | Page title. | | Name | Type | Description |
| subTitle | string | - | Subtitle of the page. | | -------------- | ---------------------------------------- | ---------------------------------------- |
| menus | Array&lt;NavigationMenuItem&gt; \| [CustomBuilder](../../ui/ts-types.md) | - | Menu in the upper right corner of the page. | | title | string \| [CustomBuilder](ts-types.md#custombuilder8)<sup>8+</sup> | Page title. |
| titleMode | NavigationTitleMode | NavigationTitleMode.Free | Display mode of the page title bar. | | subTitle | string | Subtitle of the page. |
| toolBar | {<br/>items:[<br/>Object<br/>] }<br/>\| [CustomBuilder](../../ui/ts-types.md) | - | Content of the toolbar.<br/>**items**: all items on the toolbar. | | menus | Array<NavigationMenuItem&gt; \| [CustomBuilder](ts-types.md#custombuilder8)<sup>8+</sup> | Menu in the upper right corner of the page. |
| hideToolBar | boolean | false | Whether to hide the toolbar.<br/>**true**: Hide the toolbar.<br/>**false**: Show the toolbar. | | titleMode | NavigationTitleMode | Display mode of the page title bar.<br>Default value: **NavigationTitleMode.Free**|
| hideTitleBar | boolean | false | Whether to hide the title bar. | | toolBar | object \| [CustomBuilder](ts-types.md#custombuilder8)<sup>8+</sup> | Content of the toolbar.<br>**items**: all items on the toolbar. |
| hideBackButton | boolean | false | Whether to hide the back button. | | hideToolBar | boolean | Whether to hide the toolbar.<br>Default value: **false**<br>**true**: Hide the toolbar.<br>**false**: Show the toolbar.|
| hideTitleBar | boolean | Whether to hide the title bar.<br>Default value: **false** |
- NavigationMenuItem attributes | hideBackButton | boolean | Whether to hide the back button.<br>Default value: **false** |
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- | ## NavigationMenuItem
| value | string | Yes | - | Text of an option on the menu bar. |
| icon | string | No | - | Icon path of an option on the menu bar. | | Name | Type | Mandatory| Description |
| action | () =&gt; void | No | - | Callback invoked when an option is selected. | | ------ | ----------------------- | ---- | ------------------------------ |
| value | string | Yes | Text of a menu item. |
- Object attributes | icon | string | No | Icon path of a menu item.|
| Name | Type | Mandatory | Default Value | Description | | action | () =&gt; void | No | Callback invoked when a menu item is selected. |
| -------- | -------- | -------- | -------- | -------- |
| value | string | Yes | - | Text of an option on the toolbar. | ## object
| icon | string | No | - | Icon path of an option on the toolbar. |
| action | () =&gt; void | No | - | Callback invoked when an option is selected. | | Name | Type | Mandatory| Description |
| ------ | ----------------------- | ---- | ------------------------------ |
- NavigationTitleMode enums | value | string | Yes | Text of an option on the toolbar. |
| Name | Description | | icon | string | No | Icon path of an option on the toolbar.|
| -------- | -------- | | action | () =&gt; void | No | Callback invoked when an option is selected. |
| Free | When the content is a scrollable component, the title shrinks as the content scrolls up (the subtitle fades out with its size remaining unchanged) and restores as the content scrolls down. |
| Mini | The mode is fixed at mini mode (icon + main title and subtitle). | ## NavigationTitleMode
| Full | The mode is fixed at full mode (main title and subtitle). |
| Name | Description |
> **NOTE** | ---- | ---------------------------------------- |
> | Free | When the content is a scrollable component, the main title shrinks as the content scrolls down (the subtitle fades out with its size remaining unchanged) and restores when the content scrolls up to the top.|
> Currently, only the scrollable component **&lt;List&gt;** is supported. | Mini | The icon, main title, and subtitle are in mini mode. |
| Full | The main title and subtitle are in full mode. |
> **NOTE**
>
> Currently, the scrollable component can only be **\<List>**.
## Events ## Events
| Name | Description | | Name | Description |
| -------- | -------- | | ---------------------------------------- | ---------------------------------------- |
| onTitleModeChange(callback:&nbsp;(titleMode:&nbsp;NavigationTitleMode)&nbsp;=&gt;&nbsp;void) | Triggered when **titleMode** is set to **NavigationTitleMode.Free** and the title bar mode changes as content scrolls. | | onTitleModeChange(callback: (titleMode: NavigationTitleMode) =&gt; void) | Triggered when **titleMode** is set to **NavigationTitleMode.Free** and the title bar mode changes as content scrolls.|
## Example ## Example
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
......
...@@ -2,14 +2,9 @@ ...@@ -2,14 +2,9 @@
The **\<PatternLock>** component allows users to use a pattern password for authentication. It enters the input state once being touched, and exits the input state and sends the entered password to the application once the finger leaves the screen. The **\<PatternLock>** component allows users to use a pattern password for authentication. It enters the input state once being touched, and exits the input state and sends the entered password to the application once the finger leaves the screen.
> **NOTE** > **NOTE**
> >
> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. > This component is supported since API version 9. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
None
## Child Components ## Child Components
...@@ -19,36 +14,38 @@ Not supported ...@@ -19,36 +14,38 @@ Not supported
PatternLock(controller?: PatternLockController) PatternLock(controller?: PatternLockController)
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory| Description |
| ---- | ---- | ---- | ------ | ----------------------- | | ---------- | ----------------------------------------------- | ---- | ------------------------------------------------------------ |
| controller | [PatternLockController](#patternlockcontroller) | No | null | Controller of a component to reset the component status. | | controller | [PatternLockController](#patternlockcontroller) | No | Controller of a component to reset the component status.<br>Default value: **null**|
## Attributes ## Attributes
Except for **backgroundColor**, universal attributes are not supported. Except for **backgroundColor**, universal attributes are not supported.
| Name | Type | Default Value | Description | | Name | Type | Description |
| ---- | ---- | ------------- | ----------- | | --------------- | ------------------------------------- | ------------------------------------------------------------ |
| sideLength | Length | 300vp | Width and height (same value) of the component. The minimum value is **0**. | | sideLength | [Length](ts-types.md#length) | Width and height (same value) of the component. The minimum value is **0**.<br>Default value: **300vp**|
| circleRadius | Length | 14vp | Radius of a grid dot. | | circleRadius | [Length](ts-types.md#length) | Radius of the grid dot.<br>Default value: **14vp** |
| regularColor | [ResourceColor](../../ui/ts-types.md) | Color.Black | Fill color of the grid dot in unselected state. | | regularColor | [ResourceColor](ts-types.md#resourcecolor) | Fill color of the grid dot in unselected state.<br>Default value: **Color.Black**|
| selectedColor | [ResourceColor](../../ui/ts-types.md) | Color.Black | Fill color of the grid dot in selected state. | | selectedColor | [ResourceColor](ts-types.md#resourcecolor) | Fill color of the grid dot in selected state.<br>Default value: **Color.Black**|
| activeColor | [ResourceColor](../../ui/ts-types.md) | Color.Black | Fill color of the grid dot in active state. | | activeColor | [ResourceColor](ts-types.md#resourcecolor) | Fill color of the grid dot in active state.<br>Default value: **Color.Black**|
| pathColor | [ResourceColor](../../ui/ts-types.md) | Color.Blue | Path color. | | pathColor | [ResourceColor](ts-types.md#resourcecolor) | Path color.<br>Default value: **Color.Blue** |
| pathStrokeWidth | Length | 34vp | Width of the path stroke. The minimum value is **0**. | | pathStrokeWidth | number \| string | Width of the path stroke. The minimum value is **0**.<br>Default value: **34vp** |
| autoReset| boolean | true | Whether to allow the user to reset the component status (that is, clear the input) by touching the component again after the input is complete. The value **true** means that the user can reset the component status by touching the component again after the input is complete, and **false** means the opposite. | | autoReset | boolean | Whether to allow the user to reset the component status (that is, clear the input) by touching the component again after the input is complete. The value **true** means that the user can reset the component status by touching the component again after the input is complete, and **false** means the opposite.<br>Default value: **true**|
## Events ## Events
| Name | Description | In addition to the [universal events](ts-universal-events-click.md), the following events are supported.
| ---- | ----------- |
| onPatternComplete(callback: (input: Array\<number\>) => void) | Invoked when the pattern password input is complete.<br>**input** is an array of digits that represent the connected dots in the pattern (0 to 8) and are arranged in the same sequence as the dots are connected. | | Name | Description |
| ---------------------------------------- | ---------------------------------------- |
| onPatternComplete(callback: (input: Array\<number\>) => void) | Invoked when the pattern password input is complete.<br>**input** is an array of digits that represent the connected dots in the pattern (0 to 8) and are arranged in the same sequence as the dots are connected.|
## PatternLockController ## PatternLockController
Controller bound to the **\<PatternLock>** component for resetting the component status. Implements the controller bound to the **\<PatternLock>** component for resetting the component status.
### Objects to Import ### Objects to Import
......
# PluginComponent # PluginComponent
**\<PluginComponent>** allows the UI provided by an external application to be displayed in the application. The **\<PluginComponent>** allows the UI provided by an external application to be displayed in the application.
> **NOTE**
> **NOTE**
>
> - This component is supported since API version 9. Updates will be marked with a superscript to indicate their earliest API version. > - This component is supported since API version 9. Updates will be marked with a superscript to indicate their earliest API version.
> >
> - The APIs provided by this component are system APIs. > - The APIs provided by this component are system APIs.
## Required Permissions
None
## Child Components ## Child Components
Not supported Not supported
...@@ -20,33 +17,35 @@ Not supported ...@@ -20,33 +17,35 @@ Not supported
## APIs ## APIs
PluginComponent(value: { template: PluginComponentTemplate, data: any }) PluginComponent(value: { template: PluginComponentTemplate, data: KVObject})
Creates a **PluginComponent** to display the UI provided by an external application. Creates a **PluginComponent** to display the UI provided by an external application.
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| value | {<br/>template: PluginComponentTemplate,<br/>data: KVObject<br/>} | Yes | - | **template**: template of the **PluginComponent**, which is bound to the component defined by the provider.<br/>**data**: data passed to the **PluginComponent** provider. |
- PluginComponentTemplate | Name| Type | Mandatory| Description |
| Name | Type | Description | | ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| -------- | -------- | -------- | | value | {<br>template: PluginComponentTemplate,<br>data: KVObject<br>} | Yes | **template**: template of the **PluginComponent**, which is bound to the component defined by the provider.<br>**data**: data passed to the **PluginComponent** provider.|
| source | string | Component template name. |
| ability | string | Name of the provider ability. | ## PluginComponentTemplate
| Name | Type | Description |
| ------- | ------ | ----------------------- |
| source | string | Component template name. |
| ability | string | Name of the provider ability.|
## Events ## Events
| Name | Description | | Name | Description |
| -------- | -------- | | ---------------------------------------- | ---------------------------------------- |
| onComplete(callback: () =&gt; void) | Triggered when the component loading is complete. | | onComplete(callback: () =&gt; void) | Triggered when the component loading is complete. |
| onError(callback: (info: { errcode: number, msg: string }) =&gt; void) | Triggered when an error occurs during component loading.<br/>**errcode**: error code.<br/>**msg**: error information. | | onError(callback: (info: { errcode: number, msg: string }) =&gt; void) | Triggered when an error occurs during component loading.<br>**errcode**: error code.<br>**msg**: error information.|
## PluginComponentManager ## PluginComponentManager
Provides APIs for the **PluginComponent** user to request the component and data and for the **PluginComponent** provider to push component templates and data. Provides APIs for the **PluginComponent**. You can use these APIs to request components and data and send component templates and data.
## Modules to Import ## Modules to Import
...@@ -61,63 +60,67 @@ import pluginComponentManager from '@ohos.plugincomponent' ...@@ -61,63 +60,67 @@ import pluginComponentManager from '@ohos.plugincomponent'
push(param: PushParameters, callback: AsyncCallback&lt;void&gt;): void push(param: PushParameters, callback: AsyncCallback&lt;void&gt;): void
Used by the component provider to push a component and data to the component user. Pushes the component and data to the component user.
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ------------------------- | ---- | -------------------------------- |
| param | PushParameters | Yes | Information about the component user. For details, see **PushParameters**.|
| callback | AsyncCallback&lt;void&gt; | Yes | Asynchronous callback used to return the result. |
- Parameters **PushParameters**
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| param | PushParameters | Yes | Information about the component user. For details, see **PushParameters**. |
| callback | AsyncCallback&lt;void&gt; | Yes | Asynchronous callback used to return the result. |
- PushParameters | Name | Type | Mandatory | Description |
| Name | Type | Mandatory | Description | | --------- | -------- | ---- | --------------- |
| -------- | -------- | -------- | -------- | | want | Want | Yes | Ability information of the component user.|
| want | Want | Yes | Ability information of the component user. | | name | string | Yes | Component name. |
| name | string | Yes | Component name. | | data | KVObject | No | Component data value. |
| data | KVObject | No | Component data value. | | extraData | KVObject | No | Additional data value. |
| extraData | KVObject | No | Additional data value. |
- Example **Example**
See [PluginComponent Provider](#plugincomponent-provider) For details, see [PluginComponent Provider](#plugincomponent-provider).
## request ## request
request(param: RequestParameters, callback: AsyncCallback&lt;RequestCallbackParameters&gt;): void request(param: RequestParameters, callback: AsyncCallback&lt;RequestCallbackParameters&gt;): void
Used by the component user to request a component from the component provider. Requests the component from the component provider.
- Parameters **Parameters**
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| param | RequestParameters | Yes | Information about the component request. For details, see  **RequestParameters**. |
| callback | AsyncCallback<RequestCallbackParameters \| void&gt; | | Asynchronous callback used to return the requested data. |
- RequestParameters | Name | Type | Mandatory | Description |
| Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | ------------------------------------ |
| -------- | -------- | -------- | -------- | | param | RequestParameters | Yes | Information about the component request. For details, see **RequestParameters**.|
| want | Want | Yes | Ability information of the component provider. | | callback | AsyncCallback<RequestCallbackParameters \| void&gt; | Yes | Asynchronous callback used to return the requested data. |
| name | string | Yes | Name of the requested component. |
| data | KVObject | Yes | Additional data. |
- RequestCallbackParameters **RequestParameters**
| Name | Type | Description |
| -------- | -------- | -------- |
| componentTemplate | PluginComponentTemplate | Component template. |
| data | KVObject | Component data. |
| extraData | KVObject | Additional data. |
- KVObject | Name | Type | Mandatory | Description |
| Name | Type | Description | | ---- | -------- | ---- | --------------- |
| -------- | -------- | -------- | | want | Want | Yes | Ability information of the component provider.|
| key | number \| string \| boolean \| Array \| KVObject | **KVObject** uses **key** and **value** to store data. **key** is of the string type, and **value** can be of the number, string, boolean, array type or another **KVObject**. | | name | string | Yes | Name of the requested component. |
| data | KVObject | Yes | Additional data. |
**RequestCallbackParameters**
- Example | Name | Type | Description |
| ----------------- | ----------------------- | ----- |
| componentTemplate | PluginComponentTemplate | Component template.|
| data | KVObject | Component data.|
| extraData | KVObject | Additional data.|
See [PluginComponent User](#plugincomponent-user). **KVObject**
| Name | Type | Description |
| ---- | ---------------------------------------- | ---------------------------------------- |
| key | number \| string \| boolean \| Array \| KVObject | Key of the **KVObject**. **KVObject** uses **key** and **value** to store data. If **key** is of the string type, **value** can be of the number, string, boolean, array type or another **KVObject**.|
**Example**
For details, see [PluginComponent User](#plugincomponent-user).
## on ## on
...@@ -126,28 +129,32 @@ on(eventType: string, callback: OnPushEventCallback | OnRequestEventCallback): v ...@@ -126,28 +129,32 @@ on(eventType: string, callback: OnPushEventCallback | OnRequestEventCallback): v
Listens for events of the request type and returns the requested data, or listens for events of the push type and receives the data pushed by the provider. Listens for events of the request type and returns the requested data, or listens for events of the push type and receives the data pushed by the provider.
- Parameters **Parameters**
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- | | Name | Type | Mandatory | Description |
| eventType | string | Yes | Type of the event to listen for. The options are **"push"** and **"request"**.<br/>**"push"**: The component provider pushes data to the component user.<br/>**"request"**: The component user proactively requests data from the component provider. | | --------- | ---------------------------------------- | ---- | ---------------------------------------- |
| callback | OnPushEventCallback \| OnRequestEventCallback | Yes | Callback used to return the result. For details, see description of callback. | | eventType | string | Yes | Type of the event to listen for The options are as follows:<br>**"push"**: The component provider pushes data to the component user.<br>**"request"**: The component user proactively requests data from the component provider.|
| callback | OnPushEventCallback \| OnRequestEventCallback | Yes | Callback used to return the result. For details, see **callback**. |
**callback**
| Name | Type | Description |
| ---------------------- | ---------------------------------------- | ---------------------------------------- |
| OnRequestEventCallback | (source: Want,<br>name: string,<br>data: KVObject ) =>RequestEventResult | Callback for the data request event.<br>**source**: ability information of the component requester.<br>**name**: name of the requested component.<br>**data**: additional data.<br>Return value: request data and result.|
| OnPushEventCallback | (source: Want,<br>template: PluginComponentTemplate,<br>data: KVObject,<br>extraData: KVObject<br>) =&gt; void | Callback used to receive the data pushed by the component provider.<br>**source**: ability information of the component provider.<br>**template**: component template.<br>**data**: component update data.<br>**extraData**: additional data.|
**RequestEventResult**
- callback | Name | Type | Description |
| Name | Type | Description | | --------- | -------- | ---------- |
| -------- | -------- | -------- | | template | string | Component name.|
| OnRequestEventCallback | (source: Want,<br/>name: string,<br/>data: KVObject ) =>RequestEventResult | Callback for the data request event.<br/>**source**: ability information of the component requester.<br/>**name**: name of the requested component.<br/>**data**: additional data.<br/>Return value: request data and result. | | data | KVObject | Component data.|
| OnPushEventCallback | (source: Want,<br/>template: PluginComponentTemplate,<br/>data: KVObject,<br/>extraData: KVObject<br/>) =&gt; void | Callback used to receive the data pushed by the component provider.<br/>**source**: ability information of the component provider.<br/>**template**: component template.<br/>**data**: component update data.<br/>**extraData**: additional data. | | extraData | KVObject | Additional data.|
- RequestEventResult **Example**
| Name | Type | Description |
| -------- | -------- | -------- |
| template | string | Component name. |
| data | KVObject | Component data. |
| extraData | KVObject | Additional data. |
- Example For details, see [PluginComponent Tools](#plugincomponent-tools).
See [PluginComponent Tools](#plugincomponent-tools).
## Example ## Example
...@@ -287,7 +294,7 @@ export default { ...@@ -287,7 +294,7 @@ export default {
pluginComponentManager.on("request", onRequestListener) pluginComponentManager.on("request", onRequestListener)
}, },
Push() { Push() {
// The component provider pushes data. // The component provider proactively sends data.
pluginComponentManager.push( pluginComponentManager.push(
{ {
want: { want: {
......
# Progress # Progress
The **\<Progress>** component is used to provide a progress bar that displays the progress of content loading or an operation. The **\<Progress>** component is used to provide a progress indicator that displays the progress of content loading or an operation.
> **NOTE** > **NOTE**
> >
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
None
## Child Components ## Child Components
Not supported Not supported
...@@ -19,35 +14,46 @@ Not supported ...@@ -19,35 +14,46 @@ Not supported
## APIs ## APIs
Progress(value: {value: number, total?: number, type?: ProgressType}) Progress(options: {value: number, total?: number, type?: ProgressType})
Creates a progress bar.
- Parameters Creates a progress indicator.
| Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- |
| value | number | Yes| - | Current progress.|
| total | number | No| 100 | Total progress.|
| type | ProgressType | No| ProgressType.Linear | Type of the progress bar.|
**Parameters**
- ProgressType | Name| Type| Mandatory| Description|
| Name| Description| | -------- | -------- | -------- | -------- |
| -------- | -------- | | value | number | Yes| Current progress.|
| Linear<sup>8+</sup> | Linear type.| | total | number | No| Total progress.<br>Default value: **100**|
| Ring<sup>8+</sup> | Ring type without scale. The ring fills up as the progress increases.| | type<sup>8+</sup> | ProgressType | No| Type of the progress indicator.<br>Default value: **ProgressType.Linear**|
| Eclipse<sup>8+</sup> | Eclipse type, which visualizes the progress in a way similar to the moon waxing from new to full.| | style<sup>deprecated</sup> | ProgressStyle | No| Style the progress indicator.<br>This parameter is deprecated since API version 8. You are advised to use **type** instead.<br>Default value: **ProgressStyle.Linear**|
| ScaleRing<sup>8+</sup> | Ring type with scale, which is similar to the clock scale.|
| Capsule<sup>8+</sup> | Capsule type. At both ends, the progress bar changes from an arc to a straight line and from a straight line to an arc. In the middle part of the capsule, the progress bar moves to the right.| ## ProgressType
| Name| Description|
| -------- | -------- |
| Linear | Linear type.|
| Ring<sup>8+</sup> | Indeterminate ring type. The ring fills up as the progress increases.|
| Eclipse<sup>8+</sup> | Eclipse type, which visualizes the progress in a way similar to the moon waxing from new to full.|
| ScaleRing<sup>8+</sup> | Determinate ring type, which is similar to the clock scale.|
| Capsule<sup>8+</sup> | Capsule type. At both ends, the progress indicator works in a same manner as the eclipse type. In the middle part of the capsule, the progress indicator works in a same manner as the linear type.|
## ProgressStyle
| Name | Description |
| --------- | ------------------------------------------------------------ |
| Linear | Linear type. |
| Ring | Indeterminate ring type. The ring fills up as the progress increases. |
| Eclipse | Eclipse type, which visualizes the progress in a way similar to the moon waxing from new to full.|
| ScaleRing | Determinate ring type, which is similar to the clock scale. |
| Capsule | Capsule type. At both ends, the progress indicator works in a same manner as the eclipse type. In the middle part of the capsule, the progress indicator works in a same manner as the linear type.|
## Attributes ## Attributes
| Name| Type| Default Value| Description| | Name| Type| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- |
| value | number | - | Current progress.| | value | number | Current progress.|
| color | [ResourceColor](../../ui/ts-types.md) | - | Background color of the progress bar.| | color | [ResourceColor](ts-types.md#resourcecolor) | Background color of the progress indicator.|
| style<sup>8+</sup> | {<br>strokeWidth?: Length,<br>scaleCount?: number,<br>scaleWidth?: Length<br>} | - | Component style.<br>**strokeWidth**: width of the progress bar.<br>**scaleCount**: scale count of the circular progress bar.<br>**scaleWidth**: scale width of the circular progress bar.<br>If the scale width is greater than the width of the progress bar, the default scale width is used.| | style<sup>8+</sup> | {<br>strokeWidth?: [Length](ts-types.md#length),<br>scaleCount?: number,<br>scaleWidth?: [Length](ts-types.md#length)<br>} | Component style.<br>- **strokeWidth**: stroke width of the progress indicator.<br>- **scaleCount**: number of divisions on the determinate ring-type process indicator.<br>- **scaleWidth**: scale bar width of the determinate ring-type process indicator. If it is greater than the progress indicator width, the default value is used instead.|
## Example ## Example
......
...@@ -2,14 +2,9 @@ ...@@ -2,14 +2,9 @@
The **\<QRCode>** component is used to display a QR code. The **\<QRCode>** component is used to display a QR code.
> **NOTE** > **NOTE**
> >
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
None
## Child Components ## Child Components
...@@ -21,23 +16,25 @@ Not supported ...@@ -21,23 +16,25 @@ Not supported
QRCode(value: string) QRCode(value: string)
- Parameters **Parameters**
| Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- |
| value | string | Yes| - | Content of the QR code.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| value | string | Yes| Content of the QR code.|
## Attributes ## Attributes
| Name| Type| Default Value| Description| In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported.
| -------- | -------- | -------- | -------- |
| color | [ResourceColor](../../ui/ts-types.md) | Black | Color of the QR code.| | Name| Type| Description|
| backgroundColor | [ResourceColor](../../ui/ts-types.md) | - | Background color of the QR code.| | -------- | -------- | -------- |
| color | [ResourceColor](ts-types.md#resourcecolor) | Color of the QR code.<br>Default value: **Color.Black**|
| backgroundColor | [ResourceColor](ts-types.md#resourcecolor) | Background color of the QR code.<br>Default value: **Color.White**|
## Events ## Events
Among all the universal events, only the click event is supported. Among all the universal events, only the [click event](ts-universal-events-click.md) is supported.
## Example ## Example
......
# Radio # Radio
> **NOTE**<br>
> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
The **\<Radio>** component allows users to select from a set of mutually exclusive options. The **\<Radio>** component allows users to select from a set of mutually exclusive options.
> **NOTE**
## Required Permissions >
> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
None
## Child Components ## Child Components
...@@ -21,30 +16,34 @@ None ...@@ -21,30 +16,34 @@ None
Radio(options: {value: string, group: string}) Radio(options: {value: string, group: string})
- Parameters **Parameters**
| Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- |
| value | string | Yes | - | Value of the current radio button. |
| group | string | Yes | - | Name of the group to which the radio button belongs. Only one radio button in a given group can be selected at a time. |
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| value | string | Yes| Value of the current radio button.|
| group | string | Yes| Name of the group to which the radio button belongs. Only one radio button in a given group can be selected at a time.|
## Attributes ## Attributes
| Name | Type | Default Value | Description | In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported.
| -------- | -------- | -------- | -------- |
| checked | boolean | false | Whether the radio button is selected. |
| Name| Type| Description|
| -------- | -------- | -------- |
| checked | boolean | Whether the radio button is selected.<br>Default value: **false**|
## Events ## Events
| Name | Description | In addition to the [universal events](ts-universal-events-click.md), the following events are supported.
| Name| Description|
| -------- | -------- | | -------- | -------- |
| onChange(callback: (value: boolean) => void) | Triggered when the selected state of the radio button changes.<br> -The value **true** means that the radio button is selected.<br> -The value **false** means that the radio button is not selected. | | onChange(callback: (isChecked: boolean) => void) | Triggered when the selected state of the radio button changes.<br> - If **isChecked** is **true**, the radio button is selected.<br> - If **isChecked** is **false**, the radio button is not selected.|
## Example ## Example
``` ```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct RadioExample { struct RadioExample {
...@@ -55,8 +54,8 @@ struct RadioExample { ...@@ -55,8 +54,8 @@ struct RadioExample {
Radio({ value: 'Radio1', group: 'radioGroup' }).checked(true) Radio({ value: 'Radio1', group: 'radioGroup' }).checked(true)
.height(50) .height(50)
.width(50) .width(50)
.onChange((value: boolean) => { .onChange((isChecked: boolean) => {
console.log('Radio1 status is ' + value) console.log('Radio1 status is ' + isChecked)
}) })
} }
Column() { Column() {
...@@ -64,8 +63,8 @@ struct RadioExample { ...@@ -64,8 +63,8 @@ struct RadioExample {
Radio({ value: 'Radio2', group: 'radioGroup' }).checked(false) Radio({ value: 'Radio2', group: 'radioGroup' }).checked(false)
.height(50) .height(50)
.width(50) .width(50)
.onChange((value: boolean) => { .onChange((isChecked: boolean) => {
console.log('Radio2 status is ' + value) console.log('Radio2 status is ' + isChecked)
}) })
} }
Column() { Column() {
...@@ -73,8 +72,8 @@ struct RadioExample { ...@@ -73,8 +72,8 @@ struct RadioExample {
Radio({ value: 'Radio3', group: 'radioGroup' }).checked(false) Radio({ value: 'Radio3', group: 'radioGroup' }).checked(false)
.height(50) .height(50)
.width(50) .width(50)
.onChange((value: boolean) => { .onChange((isChecked: boolean) => {
console.log('Radio3 status is ' + value) console.log('Radio3 status is ' + isChecked)
}) })
} }
}.padding({ top: 30 }) }.padding({ top: 30 })
......
# Rating # Rating
The **\<Rating>** component provides a rating bar.
> **NOTE**<br> > **NOTE**
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. >
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
The **&lt;Rating&gt;** component provides a rating bar.
## Required Permissions
None
## Child Components ## Child Components
None Not supported
## APIs ## APIs
Rating(options?: { rating: number, indicator?: boolean }) Rating(options?: { rating: number, indicator?: boolean })
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- | | Name| Type| Mandatory| Description|
| rating | number | Yes | 0 | Value to rate. | | -------- | -------- | -------- | -------- |
| indicator | boolean | No | false | Used only as an indicator and cannot be operated. | | rating | number | Yes| Value to rate.<br>Default value: **0**|
| indicator | boolean | No| Used only as an indicator and cannot be operated.<br>Default value: **false**|
## Attributes ## Attributes
| Name | Type | Default Value | Description | | Name| Type| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- |
| stars | number | 5 | Total number of stars. | | stars | number | Total number of stars.<br>Default value: **5**|
| stepSize | number | 0.5 | Step of an operation. | | stepSize | number | Step of an operation.<br>Default value: **0.5**|
| starStyle | {<br/>backgroundUri: string,<br/>foregroundUri: string,<br/>secondaryUri?: string<br/>} | - | **backgroundSrc**: image link of the unselected star. You can customize the image or use the default image. Only local images are supported.<br/>**foregroundSrc**: image path of the selected star. You can customize the image or use the default image. Only local images are supported.<br/>**secondarySrc**: image path of the partially selected star. You can customize the image or use the default image. Only local images are supported. | | starStyle | {<br>backgroundUri: string,<br>foregroundUri: string,<br>secondaryUri?: string<br>} | **backgroundUri**: image link of the unselected star. You can use the default image or a custom local image.<br>**foregroundUri**: image path of the selected star. You can use the default image or a custom local image.<br>**secondaryUir**: image path of the partially selected star. You can use the default image or a custom local image.|
## Events ## Events
| Name | Description | | Name| Description|
| -------- | -------- | | -------- | -------- |
| onChange(callback:(value: number) =&gt; void) | Triggered when the rating value changes. | | onChange(callback:(value: number) =&gt; void) | Triggered when the rating value changes.|
## Example ## Example
```ts
``` // xxx.ets
@Entry @Entry
@Component @Component
struct RatingExample { struct RatingExample {
......
...@@ -6,7 +6,7 @@ ...@@ -6,7 +6,7 @@
> >
> This component is supported since API version 9. Updates will be marked with a superscript to indicate their earliest API version. > This component is supported since API version 9. Updates will be marked with a superscript to indicate their earliest API version.
> >
> This component is a system API. > The APIs provided by this component are system APIs.
## Child Components ## Child Components
...@@ -31,7 +31,7 @@ Implements a target window, which is used to remotely control the animation. ...@@ -31,7 +31,7 @@ Implements a target window, which is used to remotely control the animation.
| bundleName | string | Process corresponding to the animation window.| | bundleName | string | Process corresponding to the animation window.|
| abilityName | string | Ability corresponding to the animation window.| | abilityName | string | Ability corresponding to the animation window.|
| windowBounds | [RRect](#rrect) | Actual size of the animation window.| | windowBounds | [RRect](#rrect) | Actual size of the animation window.|
| missionId | number | Mission ID. | | missionId | number | Mission ID.|
## RRect ## RRect
Implements a rounded rectangle. Implements a rounded rectangle.
......
# RichText # RichText
> **NOTE**<br>
> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
The **\<RichText>** component parses and displays HTML text. The **\<RichText>** component parses and displays HTML text.
> **NOTE**
>
> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions ## Required Permissions
None None
...@@ -15,40 +16,39 @@ None ...@@ -15,40 +16,39 @@ None
## APIs ## APIs
RichText\(content:string\) RichText(content:string)
- Parameters **Parameters**
| Name| Type | Mandatory | Default Value | Description | | Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| content | string | Yes| - | Text string in HTML format. | | content | string | Yes| - | String in HTML format.|
## Events ## Events
| Name | Description| | Name| Description|
| -------- | -------- | | -------- | -------- |
| onStart() => void | Triggered when web page loading starts. | | onStart(callback: () => void) | Triggered when web page loading starts. |
| onComplete() => void | Triggered when web page loading is completed. | | onComplete(callback: () => void) | Triggered when web page loading is completed.|
## Supported Tags ## Supported Tags
| Name | Description | Example | | Name| Description| Example|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| \<h1>--\<h6> | Defines six levels of headings in the HTML document. \<h1> defines the most important heading, and \<h6> defines the least important heading. | \<h1>This is an H1 heading\</h1> \<h2>This is an H2 heading\</h2> | | \<h1>--\<h6> | Defines six levels of headings in the HTML document. \<h1> defines the most important heading, and \<h6> defines the least important heading.| \<h1>This is an H1 heading\</h1> \<h2>This is an H2 heading\</h2>|
| \<p>\</p> | Defines a paragraph. | \<p>This is a paragraph\</p> | | \<p>\</p> | Defines a paragraph.| \<p>This is a paragraph\</p>|
| \<br/> | Inserts a newline character. | \<p>This is a paragraph\<br/>This is a new paragraph\</p>| | \<br/> | Inserts a newline character.| \<p>This is a paragraph\<br/>This is a new paragraph\</p>|
| \<hr/> | Defines a thematic break (such as a shift of topic) on an HTML page and creates a horizontal line. | \<p>This is a paragraph\</p>\<hr/>\<p>This is a paragraph\</p> | | \<hr/> | Defines a thematic break (such as a shift of topic) on an HTML page and creates a horizontal line.| \<p>This is a paragraph\</p>\<hr/>\<p>This is a paragraph\</p> |
| \<div>\</div> | Defines a generic container that is generally used to group block-level elements. It allows you to apply CSS styles to multiple elements at the same time. | \<div style='color:#0000FF'>\<h3>This is the heading in a div element\</h3>\</div> | | \<div>\</div> | Defines a generic container that is generally used to group block-level elements. It allows you to apply CSS styles to multiple elements at the same time.| \<div style='color:#0000FF'>\<h3>This is the heading in a div element\</h3>\</div> |
| \<i>\</i> | Displays text in italic style. | \<i>This is in italic style\</i> | | \<i>\</i> | Displays text in italic style.| \<i>This is in italic style\</i>|
| \<u>\</u> | Defines text that should be styled differently or have a non-textual annotation, such as misspelt words or a proper name in Chinese text. It is recommended that you avoid using the \<u> tag where it could be confused with a hyperlink. | \<p>\<u>This is an underlined paragraph\<u>\<p> | | \<u>\</u> | Defines text that should be styled differently or have a non-textual annotation, such as misspelt words or a proper name in Chinese text. It is recommended that you avoid using the \<u> tag where it could be confused with a hyperlink.| \<p>\<u>This is an underlined paragraph\</u>\</p> |
| \<style>\</style> | Used to embed CSS within an HTML document. | \<style>h1{color:red;}p{color:blue;}\</style> | | \<style>\</style> | Used to embed CSS within an HTML document.| \<style>h1{color:red;}p{color:blue;}\</style> |
| style | Defines the inline style of an element and is placed inside the tag. Use quotation marks (') to separate the styling text and use semicolons (;) to separate styles, for example, **style='width: 500px;height: 500px;border: 1px solid;margin: 0 auto;'**. | \<h1 style='color:blue;text-align:center'>This is a heading\</h1>\<p style='color:green'>This is a paragraph\</p> | | style | Defines the inline style of an element and is placed inside the tag. Use quotation marks (') to separate the styling text and use semicolons (;) to separate styles, for example, **style='width: 500px;height: 500px;border: 1px solid;margin: 0 auto;'**.| \<h1 style='color:blue;text-align:center'>This is a heading\</h1>\<p style='color:green'>This is a paragraph\</p> |
| \<script>\</script> | Used to embed or reference a client-side script, such as JavaScript. | \<script>document.write("Hello World!")\</script> | | \<script>\</script> | Used to embed or reference a client-side script, such as JavaScript.| \<script>document.write("Hello World!")\</script> |
## Example ## Example
You can preview how this component looks on a real device. The preview is not yet available in the DevEco Studio Previewer. You can preview how this component looks on a real device. The preview is not yet available in the DevEco Studio Previewer.
```ts ```ts
// xxx.ets // xxx.ets
......
# ScrollBar # ScrollBar
> **NOTE**
> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
The **\<ScrollBar>** is used together with scrollable components, such as **\<List>**, **\<Grid>**, and **\<Scroll>**. The **\<ScrollBar>** is used together with scrollable components, such as **\<List>**, **\<Grid>**, and **\<Scroll>**.
> **NOTE**
## Required Permissions >
> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
None
## Child Components ## Child Components
...@@ -21,23 +16,26 @@ This component can contain a single child component. ...@@ -21,23 +16,26 @@ This component can contain a single child component.
ScrollBar(value: { scroller: Scroller, direction?: ScrollBarDirection, state?: BarState }) ScrollBar(value: { scroller: Scroller, direction?: ScrollBarDirection, state?: BarState })
- ScrollBarOptions **Parameters**
| Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- | | Name| Type| Mandatory| Description|
| scroller | [Scroller](ts-container-scroll.md#scroller) | Yes| - | Scroller, which can be bound to scrollable components.| | -------- | -------- | -------- | -------- |
| direction | ScrollBarDirection | No| ScrollBarDirection.Vertical | Scrollbar direction in which scrollable components scroll.| | scroller | [Scroller](ts-container-scroll.md#scroller) | Yes| Scroller, which can be bound to scrollable components.|
| state | [BarState](ts-appendix-enums.md#barstate) | No| BarState.Auto | Scrollbar state.| | direction | ScrollBarDirection | No| Scrollbar direction in which scrollable components scroll.<br>Default value: **ScrollBarDirection.Vertical**|
| state | [BarState](ts-appendix-enums.md#barstate) | No| Scrollbar state.<br>Default value: **BarState.Auto**|
> **NOTE**
> The **<\ScrollBar>** component defines the behavior style of the scrollable area, and its subnodes define the behavior style of the scrollbar. > **NOTE**
> >
> This component is bound to a scrollable component through **scroller**, and can be used to scroll the scrollable component only when their directions are the same. The **\<ScrollBar>** component can be bound to only one scrollable component, and vice versa. > The **\<ScrollBar>** component defines the behavior style of the scrollable area, and its subnodes define the behavior style of the scrollbar.
>
- ScrollBarDirection enums > This component is bound to a scrollable component through **scroller**, and can be used to scroll the scrollable component only when their directions are the same. The **\<ScrollBar>** component can be bound to only one scrollable component, and vice versa.
| Name| Description|
| -------- | -------- | ## ScrollBarDirection
| Vertical | Vertical scrollbar.|
| Horizontal | Horizontal scrollbar.| | Name| Description|
| -------- | -------- |
| Vertical | Vertical scrollbar.|
| Horizontal | Horizontal scrollbar.|
## Example ## Example
......
...@@ -6,10 +6,6 @@ The **\<Search>** component provides an input area for users to search. ...@@ -6,10 +6,6 @@ The **\<Search>** component provides an input area for users to search.
> >
> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. > This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
None
## Child Components ## Child Components
Not supported Not supported
...@@ -18,25 +14,27 @@ Not supported ...@@ -18,25 +14,27 @@ Not supported
Search(options?: { value?: string; placeholder?: string; icon?: string; controller?: SearchController }) Search(options?: { value?: string; placeholder?: string; icon?: string; controller?: SearchController })
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ----------- | ---------------- | ---- | ---- | ---------------------------------------- |
| value | string | No | - | Text input in the search text box. |
| placeholder | string | No | - | Text displayed when there is no input. |
| icon | string | No | - | Path to the search icon. By default, the system search icon is used. The supported icon formats are .svg, .jpg, and .png.|
| controller | SearchController | No | - | Controller. |
| Name | Type | Mandatory| Description |
| ----------- | ---------------- | ---- | ------------------------------------------------------------ |
| value | string | No | Text input in the search text box. |
| placeholder | string | No | Text displayed when there is no input. |
| icon | string | No | Path to the search icon. By default, the system search icon is used. The supported icon formats are .svg, .jpg, and .png.|
| controller | SearchController | No | Controller. |
## Attributes ## Attributes
| Name | Type | Default Value | Description | In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported.
| ----------------------- | ---------------------------------------- | ---- | --------------------- |
| searchButton | string | – | Text on the search button located next to the search text box. By default, there is no search button.| | Name | Type | Description |
| placeholderColor | [ResourceColor](../../ui/ts-types.md) | - | Placeholder text color. | | ----------------------- | ------------------------------------------------ | ---------------------------------------------- |
| placeholderFont | [Font](../../ui/ts-types.md) | - | Placeholder text style. | | searchButton | string | Text on the search button located next to the search text box. By default, there is no search button. |
| textFont | [Font](../../ui/ts-types.md) | - | Text font for the search text box. | | placeholderColor | [ResourceColor](ts-types.md#resourcecolor) | Placeholder text color. |
| copyOption<sup>9+</sup> | [CopyOptions](ts-basic-components-text.md) | CopyOptions.CrossDevice | Whether copy and paste is allowed.| | placeholderFont | [Font](ts-types.md#font) | Placeholder text style. |
| textFont | [Font](ts-types.md#font) | Text font for the search text box. |
| copyOption<sup>9+</sup> | [CopyOptions](ts-appendix-enums.md#copyoptions9) | Whether copy and paste is allowed. |
| textAlign | [TextAlign](ts-appendix-enums.md#textalign) | Text alignment mode.<br>Default value: **TextAlign.Start**|
## Events ## Events
...@@ -62,13 +60,11 @@ caretPosition(value: number): void ...@@ -62,13 +60,11 @@ caretPosition(value: number): void
Sets the position of the caret. Sets the position of the caret.
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ----- | ------ | ---- | ---- | ----------------- |
| value | number | Yes | - | Length from the start of the character string to the position where the caret is located.|
| Name| Type| Mandatory| Description |
| ------ | -------- | ---- | ---------------------------------- |
| value | number | Yes | Length from the start of the character string to the position where the caret is located.|
## Example ## Example
......
...@@ -2,13 +2,9 @@ ...@@ -2,13 +2,9 @@
The **<Select\>** component provides a drop-down list box that allows users to select among multiple options. The **<Select\>** component provides a drop-down list box that allows users to select among multiple options.
> **NOTE** > **NOTE**
> >
> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. > This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
None
## Child Components ## Child Components
...@@ -16,35 +12,35 @@ Not supported ...@@ -16,35 +12,35 @@ Not supported
## APIs ## APIs
Select(options: Array\<SelectOption>\) Select(options: Array\<SelectOption\>)
- SelectOption parameters **SelectOption**
| Name| Type| Mandatory| Default Value| Description| | Name| Type | Mandatory| Description |
| ------ | ----------------------------------------------- | ---- | ------ | -------------- | | ------ | ----------------------------------- | ---- | -------------- |
| value | [ResourceStr](../../ui/ts-types.md) | Yes | - | Value of an option in the drop-down list box. | | value | [ResourceStr](ts-types.md#resourcestr) | Yes | Value of an option in the drop-down list box.|
| icon | [ResourceStr](../../ui/ts-types.md) | No | - | Icon of an option in the drop-down list box. | | icon | [ResourceStr](ts-types.md#resourcestr) | No | Icon of an option in the drop-down list box.|
## Attributes ## Attributes
| Name| Type| Default Value| Description| | Name | Type | Description |
| ----------------------- | --------------------------------------------------- | ------ | ----------------------------------------------- | | ----------------------- | ------------------------------------- | --------------------------------------------- |
| selected | number | - | Index of the initial selected option in the drop-down list box. The index of the first option is **0**. | | selected | number | Index of the initial selected option in the drop-down list box. The index of the first option is **0**.|
| value | string | - | Text of the drop-down button. | | value | string | Text of the drop-down button. |
| font | [Font](../../ui/ts-types.md) | - | Text font of the drop-down button. | | font | [Font](ts-types.md#font) | Text font of the drop-down button. |
| fontColor | [ResourceColor](../../ui/ts-types.md) | - | Text color of the drop-down button. | | fontColor | [ResourceColor](ts-types.md#resourcecolor) | Text color of the drop-down button. |
| selectedOptionBgColor | [ResourceColor](../../ui/ts-types.md) | - | Background color of the selected option in the drop-down list box. | | selectedOptionBgColor | [ResourceColor](ts-types.md#resourcecolor) | Background color of the selected option in the drop-down list box. |
| selectedOptionFont | [Font](../../ui/ts-types.md) | - | Text font of the selected option in the drop-down list box. | | selectedOptionFont | [Font](ts-types.md#font) | Text font of the selected option in the drop-down list box. |
| selectedOptionFontColor | [ResourceColor](../../ui/ts-types.md) | - | Text color of the selected option in the drop-down list box. | | selectedOptionFontColor | [ResourceColor](ts-types.md#resourcecolor) | Text color of the selected option in the drop-down list box. |
| optionBgColor | [ResourceColor](../../ui/ts-types.md) | - | Background color of an option in the drop-down list box. | | optionBgColor | [ResourceColor](ts-types.md#resourcecolor) | Background color of an option in the drop-down list box. |
| optionFont | [Font](../../ui/ts-types.md) | - | Text font of an option in the drop-down list box. | | optionFont | [Font](ts-types.md#font) | Text font of an option in the drop-down list box. |
| optionFontColor | [ResourceColor](../../ui/ts-types.md) | - | Text color of an option in the drop-down list box. | | optionFontColor | [ResourceColor](ts-types.md#resourcecolor) | Text color of an option in the drop-down list box. |
## Events ## Events
| Name| Description| | Name | Description |
| ------------------------------------------------------------ | ------------------------------------------------------------ | | ---------------------------------------------------------- | ------------------------------------------------------------ |
| onSelect(callback: (index: number, value?:string) => void) | Invoked when an option in the drop-down list box is selected. **index** indicates the index of the selected option. **value** indicates the value of the selected option. | | onSelect(callback: (index: number, value?:string) => void) | Invoked when an option in the drop-down list box is selected.<br>**index**: index of the selected option.<br/>**value**: value of the selected option. |
## Example ## Example
......
# Slider # Slider
The **\<Slider>** component is used to quickly adjust settings, such as the volume and brightness.
> **NOTE** > **NOTE**
> >
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
The *\<Slider>** component is used to quickly adjust settings, such as the volume and brightness.
## Required Permissions
None
## Child Components ## Child Components
...@@ -21,57 +14,61 @@ Not supported ...@@ -21,57 +14,61 @@ Not supported
## APIs ## APIs
Slider(value:{value?: number, min?: number, max?: number, step?: number, style?: SliderStyle, direction?: Axis}) Slider(options?: {value?: number, min?: number, max?: number, step?: number, style?: SliderStyle, direction?: Axis, reverse?: boolean})
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ---------------------- | --------------------------------------- | --------- | ------------------ | ---------------------------------------- |
| value | number | No | 0 | Current progress. |
| min | number | No | 0 | Minimum value. |
| max | number | No | 100 | Maximum value. |
| step | number | No | 1 | Step of the slider. When the corresponding step is set, the slider slides intermittently. |
| style | SliderStyle | No | SliderStyle.OutSet | Style of the slider. |
| direction<sup>8+</sup> | [Axis](ts-appendix-enums.md#axis-enums) | No | Axis.Horizontal | Whether the slider moves horizontally or vertically. |
| reverse<sup>8+</sup> | boolean | No | false | Whether the slider values are reversed. |
- SliderStyle enums | Name| Type| Mandatory| Description|
| Name | Description | | -------- | -------- | -------- | -------- |
| ------ | --------------------------------- | | value | number | No| Current progress.<br>Default value: **0**|
| OutSet | The slider is on the slider rail. | | min | number | No| Minimum value.<br>Default value: **0**|
| InSet | The slider is in the slider rail. | | max | number | No| Maximum value.<br>Default value: **100**|
| step | number | No| Step of the slider. When the corresponding step is set, the slider slides intermittently.<br>Default value: **1**|
| style | SliderStyle | No| Style of the slider.<br>Default value: **SliderStyle.OutSet**|
| direction<sup>8+</sup> | [Axis](ts-appendix-enums.md#axis) | No| Whether the slider moves horizontally or vertically.<br>Default value: **Axis.Horizontal**|
| reverse<sup>8+</sup> | boolean | No| Whether the slider values are reversed.<br>Default value: **false**|
## SliderStyle
| Name| Description|
| -------- | -------- |
| OutSet | The slider is on the slider rail.|
| InSet | The slider is in the slider rail.|
## Attributes ## Attributes
Touch target configuration is not supported. Touch target configuration is not supported.
| Name | Type | Default Value | Description | | Name| Type| Description|
| ------------- | ------- | ------------- | ---------------------------------------- | | -------- | -------- | -------- |
| blockColor | Color | - | Color of the slider. | | blockColor | [ResourceColor](ts-types.md#resourcecolor) | Color of the slider.|
| trackColor | Color | - | Background color of the slider. | | trackColor | [ResourceColor](ts-types.md#resourcecolor) | Background color of the slider.|
| selectedColor | Color | - | Color of the slider rail that has been slid. | | selectedColor | [ResourceColor](ts-types.md#resourcecolor) | Color of the slider rail that has been slid.|
| showSteps | boolean | false | Whether to display the current step. | | showSteps | boolean | Whether to display the current step.<br>Default value: **false**|
| showTips | boolean | false | Whether to display a bubble to indicate the percentage when sliding. | | showTips | boolean | Whether to display a bubble to indicate the percentage when sliding.<br>Default value: **false**|
| trackThickness | [Length](ts-types.md#length) | Track thickness of the slider.|
## Events ## Events
Among all the universal events, only **OnAppear** and **OnDisAppear** are supported. In addition to the **OnAppear** and **OnDisAppear** universal events, the following events are supported.
| Name | Description | | Name| Description|
| ---------------------------------------- | ---------------------------------------- | | -------- | -------- |
| onChange(callback: (value: number, mode: SliderChangeMode) =&gt; void) | Callback invoked when the slider slides.<br/>**value**: current progress.<br/>**mode**: dragging state. | | onChange(callback: (value: number, mode: SliderChangeMode) =&gt; void) | Invoked when the slider slides.<br>**value**: current progress.<br>**mode**: dragging state.|
- SliderChangeMode enums ## SliderChangeMode
| Name | Value | Description |
| ------ | ----- | ----------------------------------- |
| Begin | 0 | The user starts to drag the slider. |
| Moving | 1 | The user is dragging the slider. |
| End | 2 | The user stops dragging the slider. |
| Name| Value| Description|
| -------- | -------- | -------- |
| Begin | 0 | The user starts to drag the slider.|
| Moving | 1 | The user is dragging the slider.|
| End | 2 | The user stops dragging the slider.|
| Click | 3 | The user moves the slider by touching the slider rail.|
## Example
## Example
```ts ```ts
// xxx.ets // xxx.ets
......
# Span # Span
The **\<Span>** component is used to display inline text in the **\<Text>** component.
> **NOTE**<br> > **NOTE**
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. >
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
The **&lt;Span&gt;** component is used to display a paragraph of textual information. It can be used only as a child component in the **&lt;Text&gt;** component.
## Required Permissions
None
## Child Components ## Child Components
None Not supported
## APIs ## APIs
Span(content: string) Span(value: string | Resource)
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| value | string \| [Resource](ts-types.md#resource) | Yes| Plain text.|
- Parameters
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| content | string | Yes | - | Text content. |
## Attributes ## Attributes
In addition to the text style attributes, the attributes below are supported. In addition to the [universal text style](ts-universal-attributes-text-style.md) attributes, the following attributes are supported.
| Name | Type | Default Value | Description | | Name| Type| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- |
| decoration | {<br/>type: [TextDecorationType](ts-appendix-enums.md#textdecorationtype-enums),<br/>color?: Color<br/>} | {<br/>type: TextDecorationType.None<br/>} | Style and color of the text decorative line. | | decoration | {<br>type: [TextDecorationType](ts-appendix-enums.md#textdecorationtype),<br>color?: [ResourceColor](ts-types.md#resourcecolor)<br>} | Style and color of the text decorative line.<br>Default value: {<br>type: TextDecorationType.None<br>color: Color.Black<br>} |
| textCase | [TextCase](ts-appendix-enums.md#textcase-enums) | Normal | Text case. | | letterSpacing | number \| string | Letter spacing. |
| textCase | [TextCase](ts-appendix-enums.md#textcase) | Text case.<br>Default value: **TextCase.Normal**|
## Events ## Events
Among all the universal events, only the click event is supported. Among all the [universal events](ts-universal-attributes-click.md), only the click event is supported.
> **NOTE**<br> > **NOTE**
> As the **&lt;Span&gt;** component does not have size information, the **target** attribute of the **ClickEvent** object returned by the click event is invalid. >
> As the **\<Span>** component does not include size information, the **target** attribute of the **ClickEvent** object returned by the click event is invalid.
## Example ## Example
```ts
``` // xxx.ets
@Entry @Entry
@Component @Component
struct SpanExample { struct SpanExample {
......
...@@ -2,16 +2,10 @@ ...@@ -2,16 +2,10 @@
The **\<Stepper>** component provides a step navigator. The **\<Stepper>** component provides a step navigator.
> **NOTE**
>
> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
None > **NOTE**
>
> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
## Child Components ## Child Components
...@@ -23,11 +17,10 @@ Only the child component **\<[StepperItem](ts-basic-components-stepperitem.md)>* ...@@ -23,11 +17,10 @@ Only the child component **\<[StepperItem](ts-basic-components-stepperitem.md)>*
Stepper(value?: { index?: number }) Stepper(value?: { index?: number })
**Parameters**
- Parameters | Name| Type| Mandatory| Description|
| Name | Type | Mandatory | Default Value | Description | | -------- | -------- | -------- | -------- |
| -------- | -------- | -------- | -------- | -------- | | index | number | No| Index of the **\<StepperItem>** that is currently displayed.<br>Default value: **0** |
| index | number | No | 0 | Index of the **\<StepperItem>** that is currently displayed. |
## Attributes ## Attributes
...@@ -37,16 +30,17 @@ None ...@@ -37,16 +30,17 @@ None
## Events ## Events
| Name | Description | | Name| Description|
| -------- | -------- | | -------- | -------- |
| onFinish(callback: () =&gt; void) | Invoked when the **nextLabel** of the last **\<StepperItem>** in the **\<Stepper>** is clicked. | | onFinish(callback: () =&gt; void) | Invoked when the **nextLabel** of the last **\<StepperItem>** in the **\<Stepper>** is clicked. |
| onSkip(callback: () =&gt; void) | Invoked when the current **\<StepperItem>** is **ItemState.Skip** and the **nextLabel** is clicked. | | onSkip(callback: () =&gt; void) | Invoked when the current **\<StepperItem>** is **ItemState.Skip** and the **nextLabel** is clicked. |
| onChange(callback: (prevIndex?: number, index?: number) =&gt; void) | Invoked when the text button on the left or right is clicked to switch between steps.<br/>- **prevIndex**: index of the step page before the switching.<br/>- **index**: index of the step page after the switching, that is, index of the previous or next page. | | onChange(callback: (prevIndex?: number, index?: number) =&gt; void) | Invoked when the text button on the left or right is clicked to switch between steps.<br>- **prevIndex**: index of the step page before the switching.<br>- **index**: index of the step page after the switching, that is, index of the previous or next page. |
| onNext(callback: (index?: number, pendingIndex?: number) =&gt; void) | Invoked when a user switches to the next step.<br>- **index**: index of the current step page.<br>- **pendingIndex**: index of the next page. |
| onPrevious(callback: (index?: number, pendingIndex?: number) =&gt; void) | Invoked when a user switches to the previous step.<br>- **index**: index of the current step page.<br>- **pendingIndex**: index of the previous page. |
## Example ## Example
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
...@@ -128,4 +122,3 @@ struct StepperExample { ...@@ -128,4 +122,3 @@ struct StepperExample {
![en-us_image_0000001250678457](figures/en-us_image_0000001250678457.gif) ![en-us_image_0000001250678457](figures/en-us_image_0000001250678457.gif)
# StepperItem # StepperItem
The **\<StepperItem>** component provides an element for the **\<Stepper>** component.
> **NOTE**<br>
> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
> **NOTE**
The **&lt;StepperItem&gt;** component provides an element for the **&lt;Stepper&gt;** component. >
> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
None
## Child Components ## Child Components
...@@ -25,22 +20,22 @@ StepperItem() ...@@ -25,22 +20,22 @@ StepperItem()
## Attributes ## Attributes
| Name | Type | Default Value | Description | | Name| Type| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- |
| prevLabel | string | - | When the **&lt;Stepper&gt;** contains more than one page, the default value for all pages except the first page is **Back**. | | prevLabel | string | When the **\<Stepper>** contains more than one page, the default value for all pages except the first page is **Back**.|
| nextLabel | string | - | When the stepper contains more than one page, the default value for the last page is **Start**, and the default value for other pages is **Next**. | | nextLabel | string | When the stepper contains more than one page, the default value for the last page is **Start**, and the default value for other pages is **Next**.|
| status | ItemState | ItemState.Normal | Status of the **&lt;StepperItem&gt;**. | | status | ItemState | Status of the **\<StepperItem>**.<br>Default value: **ItemState.Normal**|
## ItemState
- ItemState enums | Name| Description|
| Name | Description | | -------- | -------- |
| -------- | -------- | | Normal | The right button is clickable and can navigate users to the next **\<StepperItem>** when it is clicked.|
| Normal | The right button is clickable and can navigate users to the next **&lt;StepperItem&gt;** when it is clicked. | | Disabled | The right button is grayed out and unavailable.|
| Disabled | The right button is grayed out and unavailable. | | Waiting | The right button is not displayed, and a progress bar is displayed instead.|
| Waiting | The right button is not displayed, and a progress bar is displayed instead. | | Skip | The current **\<StepperItem>** is skipped, and the next **\<StepperItem>** is displayed.|
| Skip | The current **&lt;StepperItem&gt;** is skipped, and the next **&lt;StepperItem&gt;** is displayed. |
## Example ## Example
See [Stepper](ts-basic-components-stepper.md). See [Stepper](ts-basic-components-stepper.md).
...@@ -7,11 +7,6 @@ The **\<Text>** component is used to display a piece of textual information. ...@@ -7,11 +7,6 @@ The **\<Text>** component is used to display a piece of textual information.
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
None
## Child Components ## Child Components
This component can contain the [\<Span>](ts-basic-components-span.md) child component. This component can contain the [\<Span>](ts-basic-components-span.md) child component.
...@@ -19,31 +14,31 @@ This component can contain the [\<Span>](ts-basic-components-span.md) child comp ...@@ -19,31 +14,31 @@ This component can contain the [\<Span>](ts-basic-components-span.md) child comp
## APIs ## APIs
Text(content?: ResourceStr) Text(content?: string | Resource)
- Parameters **Parameters**
| Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- |
| content | [ResourceStr](../../ui/ts-types.md#resourcestr8) | No| '' | Text content. The content and style set for the **\<Text>** component do not take effect when it contains the **\<Span>** child component.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| content | string \| [Resource](ts-types.md#resource) | No| Text content. The content and style set for the **\<Text>** component do not take effect when it contains the **\<Span>** child component.<br>Default value: **' '**|
## Attributes ## Attributes
In addition to the following attributes, the attributes in [Text Style](ts-universal-attributes-text-style.md) are supported. In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported.
| Name| Type| Default Value| Description| | Name| Type| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- |
| textAlign | [TextAlign](ts-appendix-enums.md#textalign) | TextAlign.Start | Text alignment mode of multiple lines of text.| | textAlign | [TextAlign](ts-appendix-enums.md#textalign) | Text alignment mode of multiple lines of text.<br>Default value: **TextAlign.Start**|
| textOverflow | {overflow: [TextOverflow](ts-appendix-enums.md#textoverflow)} | {overflow: TextOverflow.Clip} | Display mode when the text is too long.<br>**NOTE**<br/>Text is truncated at the transition between words. To truncate text in the middle of a word, add **\u200B** between characters.<br>This attribute must be used with `maxLines` to take effect. | | textOverflow | {overflow: [TextOverflow](ts-appendix-enums.md#textoverflow)} | Display mode when the text is too long.<br>Default value: **{overflow: TextOverflow.Clip}**<br>**NOTE**<br/>Text is truncated at the transition between words. To truncate text in the middle of a word, add **\u200B** between characters.<br>This attribute must be used with `maxLines` to take effect. |
| maxLines | number | Infinity | Maximum number of lines in the text.<br>**NOTE**<br/>By default, text is automatically folded. If this parameter is specified, the text does not exceed the specified number of lines. If there is extra text, you can use `textOverflow` to specify the truncation mode. | | maxLines | number | Maximum number of lines in the text.<br>Default value: **Infinity**<br>**NOTE**<br/>By default, text is automatically folded. If this attribute is specified, the text will not exceed the specified number of lines. If there is extra text, you can use `textOverflow` to specify the truncation mode. |
| lineHeight | string \| number \| [Resource](../../ui/ts-types.md) | - | Text line height. If the value is less than or equal to **0**, the line height is not limited and the font size is adaptive. If the value of the number type, the unit fp is used.| | lineHeight | string \| number \| [Resource](ts-types.md#resource) | Text line height. If the value is less than or equal to **0**, the line height is not limited and the font size is adaptive. If the value of the number type, the unit fp is used.|
| decoration | {<br>type: TextDecorationType,<br>color?: [ResourceColor](../../ui/ts-types.md)<br>} | {<br>type: TextDecorationType.None,<br>color: Color.Black<br>} | Style and color of the text decorative line. | | decoration | {<br>type: TextDecorationType,<br>color?: [ResourceColor](ts-types.md#resourcecolor)<br>} | Style and color of the text decorative line.<br>Default value: {<br>type: TextDecorationType.None,<br>color: Color.Black<br>} |
| baselineOffset | number \| string | - | Offset of the text baseline. | | baselineOffset | number \| string | Offset of the text baseline. |
| letterSpacing | [Length](../../ui/ts-types.md) | - | Letter spacing. | | letterSpacing | number \| string | Letter spacing. |
| minFontSize | number \| string \| [Resource](../../ui/ts-types.md) | - | Minimum font size. | | minFontSize | number \| string \| [Resource](ts-types.md#resource) | Minimum font size. |
| maxFontSize | number \| string \| [Resource](../../ui/ts-types.md) | - | Maximum font size. | | maxFontSize | number \| string \| [Resource](ts-types.md#resource) | Maximum font size. |
| textCase | [TextCase](ts-appendix-enums.md#textcase) | TextCase.Normal | Text case.| | textCase | [TextCase](ts-appendix-enums.md#textcase) | Text case.<br>Default value: **TextCase.Normal**|
| copyOption<sup>9+</sup> | [CopyOptions](ts-appendix-enums.md#copyoptions9) | CopyOptions.None | Whether copy and paste is allowed.| | copyOption<sup>9+</sup> | [CopyOptions](ts-appendix-enums.md#copyoptions9) | Whether copy and paste is allowed.<br>Default value: **CopyOptions.None**|
> **NOTE** > **NOTE**
> >
......
...@@ -4,12 +4,7 @@ The **\<TextArea>** component provides multi-line text input and responds to cer ...@@ -4,12 +4,7 @@ The **\<TextArea>** component provides multi-line text input and responds to cer
> **NOTE** > **NOTE**
> >
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
None
## Child Components ## Child Components
...@@ -21,36 +16,38 @@ Not supported ...@@ -21,36 +16,38 @@ Not supported
TextArea(value?:{placeholder?: ResourceStr, text?: ResourceStr, controller?: TextAreaController}) TextArea(value?:{placeholder?: ResourceStr, text?: ResourceStr, controller?: TextAreaController})
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ----------------------- | ---------------------------------------- | ---- | ---- | -------------- |
| placeholder | [ResourceStr](../../ui/ts-types.md) | No | - | Text displayed when there is no input. |
| text | [ResourceStr](../../ui/ts-types.md) | No | - | Current text input. |
| controller<sup>8+</sup> | [TextAreaController](#textareacontroller8) | No | - | Text area controller.|
| Name | Type | Mandatory | Description |
| ----------------------- | ---------------------------------------- | ---- | -------------- |
| placeholder | [ResourceStr](ts-types.md#resourcestr) | No | Text displayed when there is no input. |
| text | [ResourceStr](ts-types.md#resourcestr) | No | Current text input. |
| controller<sup>8+</sup> | [TextAreaController](#textareacontroller8) | No | Text area controller.|
## Attributes
In addition to universal attributes, the following attributes are supported. ## Attributes
| Name | Type | Default Value | Description | In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported.
| ------------------------ | ---------------------------------------- | ----- | ---------------------------------------- |
| placeholderColor | Color | - | Placeholder text color. |
| placeholderFont | {<br>size?: number,<br>weight?:number \| [FontWeight](ts-universal-attributes-text-style.md),<br>family?:&nbsp;string,<br>style?:&nbsp;[FontStyle](ts-universal-attributes-text-style.md)<br>} | - | Placeholder text style.<br>- **size**: font size. If the value is of the number type, the unit is fp.<br>- **weight**: font weight. For the number type, the value ranges from 100 to 900, at an interval of 100. The default value is **400**. A larger value indicates a larger font weight.<br>- **family**: font family. Use commas (,) to separate multiple fonts, for example, **'Arial, sans-serif'**. The priority of the fonts is the sequence in which they are placed.<br>- **style**: font style.|
| textAlign | [TextAlign](ts-appendix-enums.md#textalign) | Start | Horizontal alignment of the text. |
| caretColor | Color | - | Color of the caret in the text box. |
| inputFilter<sup>8+</sup> | {<br>value: [ResourceStr](../../ui/ts-types.md)<sup>8+</sup>,<br>error?:&nbsp;(value:&nbsp;string)<br>} | - | Regular expression for input filtering. Only inputs that comply with the regular expression can be displayed. Other inputs are ignored. The specified regular expression can match single characters, but not strings. Example: ^(?=.\*\d)(?=.\*[a-z])(?=.\*[A-Z]).{8,10}$. Strong passwords containing 8 to 10 characters cannot be filtered.<br>- **value**: regular expression to set.<br>- **error**: ignored content to return when regular expression matching fails.|
| copyOption<sup>9+</sup> | [CopyOptions](ts-basic-components-text.md) | CopyOptions.CrossDevice | Whether copy and paste is allowed.|
| Name | Type | Description |
| ------------------------ | ---------------------------------------- | ---------------------------------------- |
| placeholderColor | [ResourceColor](ts-types.md#resourcecolor) | Placeholder text color. |
| placeholderFont | [Font](ts-types.md#font) | Placeholder text style. |
| textAlign | [TextAlign](ts-appendix-enums.md#textalign) | Horizontal alignment of the text.<br>Default value: **TextAlign.Start**|
| caretColor | [ResourceColor](ts-types.md#resourcecolor) | Color of the caret in the text box. |
| inputFilter<sup>8+</sup> | {<br>value: [ResourceStr](ts-types.md#resourcestr),<br>error?: (value: string) => void<br>} | Regular expression for input filtering. Only inputs that comply with the regular expression can be displayed. Other inputs are ignored. The specified regular expression can match single characters, but not strings. Example: ^(?=.\*\d)(?=.\*[a-z])(?=.\*[A-Z]).{8,10}$. Strong passwords containing 8 to 10 characters cannot be filtered.<br>- **value**: regular expression to set.<br>- **error**: ignored content to return when regular expression matching fails.|
| copyOption<sup>9+</sup> | [CopyOptions](ts-appendix-enums.md#copyoptions9) | Whether copy and paste is allowed.|
## Events ## Events
| Name | Description | In addition to the [universal events](ts-universal-events-click.md), the following events are supported.
| ---------------------------------------- | ---------------------------------------- |
| onChange(callback: (value: string) =&gt; void) | Triggered when the input changes. | | Name | Description |
| onCopy<sup>8+</sup>(callback:(value: string) =&gt; void) | Triggered when the copy button on the pasteboard, which displays when the text box is long pressed, is clicked.<br>**value**: text to be copied.| | ------------------------------------------------------------ | ------------------------------------------------------------ |
| onCut<sup>8+</sup>(callback:(value: string) =&gt; void) | Triggered when the cut button on the pasteboard, which displays when the text box is long pressed, is clicked.<br>**value**: text to be cut.| | onChange(callback: (value: string) =&gt; void) | Triggered when the input changes. |
| onPaste<sup>8+</sup>(callback:(value: string) =&gt; void) | Triggered when the paste button on the pasteboard, which displays when the text box is long pressed, is clicked.<br>**value**: text to be pasted.| | onCopy<sup>8+</sup>(callback:(value: string) =&gt; void) | Triggered when the copy button on the pasteboard, which displays when the text box is long pressed, is clicked.<br>- **value**: text to be copied.|
| onCut<sup>8+</sup>(callback:(value: string) =&gt; void) | Triggered when the cut button on the pasteboard, which displays when the text box is long pressed, is clicked.<br>- **value**: text to be cut.|
| onPaste<sup>8+</sup>(callback:(value: string) =&gt; void) | Triggered when the paste button on the pasteboard, which displays when the text box is long pressed, is clicked.<br>- **value**: text to be pasted.|
## TextAreaController<sup>8+</sup> ## TextAreaController<sup>8+</sup>
...@@ -60,7 +57,6 @@ Defines the controller for controlling the **\<TextArea>** component. ...@@ -60,7 +57,6 @@ Defines the controller for controlling the **\<TextArea>** component.
``` ```
controller: TextAreaController = new TextAreaController() controller: TextAreaController = new TextAreaController()
``` ```
### caretPosition<sup>8+</sup> ### caretPosition<sup>8+</sup>
...@@ -69,10 +65,11 @@ caretPosition(value: number): void ...@@ -69,10 +65,11 @@ caretPosition(value: number): void
Sets the position of the caret. Sets the position of the caret.
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ----- | ------ | ---- | ---- | ------------------- | | Name| Type| Mandatory| Description |
| value | number | Yes | - | Length from the start of the string to the position where the caret is located.| | ------ | -------- | ---- | -------------------------------------- |
| value | number | Yes | Length from the start of the string to the position where the caret is located.|
## Example ## Example
......
...@@ -6,10 +6,6 @@ The **<TextClock\>** component displays the current system time in text format f ...@@ -6,10 +6,6 @@ The **<TextClock\>** component displays the current system time in text format f
> >
>This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. >This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
None
## Child Components ## Child Components
Not supported Not supported
...@@ -20,30 +16,30 @@ TextClock(options?: { timeZoneOffset?: number, controller?: TextClockController ...@@ -20,30 +16,30 @@ TextClock(options?: { timeZoneOffset?: number, controller?: TextClockController
**Parameters** **Parameters**
| Name | Type| Mandatory| Default Value | Description | | Name | Type | Mandatory | Description |
| -------- | -------- | ---- | ------------------ | ------------------------------------------------------------ | | -------------- | -------- | ------ | --------------------------------------------------------------------------- |
| timeZoneOffset | number | No | Time zone offset of the current system| Time zone offset.<br>The value range is [-14, 12], indicating UTC+12 to UTC-12. A negative value indicates Eastern Standard Time, and a positive value indicates Western Standard Time. For example, **-8** indicates UTC+8.<br>For countries or regions crossing the International Date Line, use -13 (UTC+13) and -14 (UTC+14) to ensure consistent time within the entire country or region. If the set value is not within the valid range, the time zone offset of the current system will be used.| | timeZoneOffset | number | No | Time zone offset.<br>The value range is [-14, 12], indicating UTC+12 to UTC-12. A negative value indicates Eastern Standard Time, and a positive value indicates Western Standard Time. For example, **-8** indicates UTC+8.<br>For countries or regions crossing the International Date Line, use -13 (UTC+13) and -14 (UTC+14) to ensure consistent time within the entire country or region. If the set value is not within the valid range, the time zone offset of the current system will be used.<br>Default value: time zone offset of the current system|
| contorller | [TextClockContorller](#textclockcontroller) | No| null | Binds a controller to control the status of the **<TextClock\>** component.| | controller | [TextClockController](#textclockcontroller) | No | Binds a controller to control the status of the **<TextClock\>** component.|
## Attributes ## Attributes
In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported.
| Name | Type| Default Value | Description | | Name | Type | Description |
| ------ | -------- | -------- | ------------------------------------------------------------ | | ------ | --------------- | ------------------------------------------------------------ |
| format | string | 'hms' | Time format.<br>The date separator is a slash (/), and the time separator is a colon (:).<br>For example, yyyyMMdd and yyyy-MM-dd are displayed as yyyy/MM/dd,<br>and hhmmss is displayed as hh:mm:ss.<br>Only one digit is required for the time format. This means that hhmmss is equivalent to hms.<br>Supported time format strings:<br>- YYYY/yyyy: four-digit year<br>- YY/yy: last two digits of year<br>- M: one-digit month (MM for two-digit month, for example, 01)<br>- d: one-digit day (dd for two-digit day, for example, 01)<br>- D: number of days that have elapsed in the year<br>- H: 24-hour format<br>- h: 12-hour format<br>- m: minute<br>- s: second<br>- SSS: millisecond| | format | string | Time format.<br>The date separator is a slash (/), and the time separator is a colon (:).<br>For example, yyyyMMdd and yyyy-MM-dd are displayed as yyyy/MM/dd,<br>and hhmmss is displayed as hh:mm:ss.<br>Only one digit is required for the time format. This means that hhmmss is equivalent to hms.<br>Supported time format strings:<br>- YYYY/yyyy: four-digit year<br>- YY/yy: last two digits of year<br>- M: one-digit month (MM for two-digit month, for example, 01)<br>- d: one-digit day (dd for two-digit day, for example, 01)<br>- D: number of days that have elapsed in the year<br>- H: 24-hour format<br>- h: 12-hour format<br>- m: minute<br>- s: second<br>- SSS: millisecond<br>Default value: **'hms'**|
## Events ## Events
In addition to the universal events (ts-universal-events-click.md), the following events are supported. In addition to the universal events (ts-universal-events-click.md), the following events are supported.
| Name | Description | | Name | Description |
| -------------------------------------------- | ------------------------------------------------------------ | | -------------------------------------------- | ------------------------------------------------------------ |
| onDateChange(event: (value: number) => void) | Called when the time changes in seconds at minimum.<br>**value**: Unix time stamp, which is the number of milliseconds that have elapsed since the Unix epoch. | | onDateChange(event: (value: number) => void) | Called when the time changes in seconds at minimum.<br> - **value**: Unix time stamp, which is the number of milliseconds that have elapsed since the Unix epoch.|
## TextClockController ## TextClockController
Implements a controller of the **<TextClock\>** component, which can be bound to the component for status control. Defines the controller of the **<TextClock\>** component, which can be bound to the component for status control. A **\<TextClock>** component can be bound to only one controller.
### Objects to Import ### Objects to Import
......
...@@ -2,14 +2,9 @@ ...@@ -2,14 +2,9 @@
The **\<TextInput>** component provides single-line text input and is able to respond to input events. The **\<TextInput>** component provides single-line text input and is able to respond to input events.
> **NOTE** > **NOTE**
> >
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
None
## Child Components ## Child Components
...@@ -19,92 +14,93 @@ Not supported ...@@ -19,92 +14,93 @@ Not supported
## APIs ## APIs
TextInput(value?:{placeholder?: string | Resource, text?: string | Resource, controller?: TextInputController}) TextInput(value?:{placeholder?: ResourceStr, text?: ResourceStr, controller?: TextInputController})
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- | | Name | Type | Mandatory | Description |
| placeholder | string \|&nbsp;[Resource](../../ui/ts-types.md#resource-type) | No | - | Hint text displayed when there is no input. | | ----------------------- | ---------------------------------------- | ---- | --------------- |
| text | string \| [Resource](../../ui/ts-types.md#resource-type) | No | - | Current text input. | | placeholder | [ResourceStr](ts-types.md#resourcestr) | No | Text displayed when there is no input. |
| controller<sup>8+</sup> | [TextInputController](#textinputcontroller8) | No | - | Text input controller. | | text | [ResourceStr](ts-types.md#resourcestr) | No | Current text input. |
| controller<sup>8+</sup> | [TextInputController](#textinputcontroller8) | No | Text input controller.|
## Attributes ## Attributes
In addition to the universal attributes, the following attributes are supported. In addition to the universal attributes and [text style](ts-universal-attributes-text-style.md) attributes, the following attributes are supported.
| Name | Type | Default Value | Description | | Name | Type | Description |
| -------- | -------- | -------- | -------- | | ------------------------ | ---------------------------------------- | ---------------------------------------- |
| type | InputType | InputType.Normal | Input box type. | | type | InputType | Input box type.<br>Default value: **InputType.Normal** |
| placeholderColor | Color | - | Placeholder text color. | | placeholderColor | [ResourceColor](ts-types.md#resourcecolor) | Placeholder text color.|
| placeholderFont | {<br/>size?: Length,<br/>weight?: number\|[FontWeight](ts-universal-attributes-text-style.md),<br/>family?: string,<br/>style?: [FontStyle](ts-universal-attributes-text-style.md)<br/>} | - | Placeholder text style.<br/>- **size**: font size. If the value is of the number type, the unit fp is used.<br/>- **weight**: font weight. For the number type, the value ranges from 100 to 900, at an interval of 100. The default value is **400**. A larger value indicates a larger font weight.<br/>- **family**: font family. Use commas (,) to separate multiple fonts, for example, **'Arial, sans-serif'**. The priority of the fonts is the sequence in which they are placed.<br/>- **style**: font style. | | placeholderFont | [Font](ts-types.md#font) | Placeholder text style.|
| enterKeyType | EnterKeyType | EnterKeyType.Done | How the Enter key is labeled. | | enterKeyType | EnterKeyType | How the Enter key is labeled.<br>Default value: **EnterKeyType.Done** |
| caretColor | Color | - | Color of the caret (also known as the text insertion cursor). | | caretColor | [ResourceColor](ts-types.md#resourcecolor) | Color of the caret in the text box. |
| maxLength | number | - | Maximum number of characters in the text input. | | maxLength | number | Maximum number of characters in the text input. |
| inputFilter<sup>8+</sup> | {<br/>value: [ResourceStr](../../ui/ts-types.md)<sup>8+</sup>,<br/>error?: (value: string)<br/>} | - | Regular expression for input filtering. Only inputs that comply with the regular expression can be displayed. Other inputs are ignored. The specified regular expression can match single characters, but not strings. Example: ^(? =.\*\d)(? =.\*[a-z])(? =.\*[A-Z]).{8,10}$. Strong passwords containing 8 to 10 characters cannot be filtered.<br>- **value**: regular expression to set.<br>- **error**: error message containing the ignored content returned when regular expression matching fails. | | inputFilter<sup>8+</sup> | {<br>value: [ResourceStr](ts-types.md#resourcestr),<br>error?: (value: string) =&gt; void<br>} | Regular expression for input filtering. Only inputs that comply with the regular expression can be displayed. Other inputs are ignored. The specified regular expression can match single characters, but not strings. Example: ^(?=.\*\d)(?=.\*[a-z])(?=.\*[A-Z]).{8,10}$. Strong passwords containing 8 to 10 characters cannot be filtered.<br>- **value**: regular expression to set.<br>- **error**: ignored content to return when regular expression matching fails.|
| copyOption<sup>9+</sup> | [CopyOptions](ts-basic-components-text.md) | CopyOptions.CrossDevice | Whether copy and paste is allowed. | | copyOption<sup>9+</sup> | [CopyOptions](ts-appendix-enums.md#copyoptions9) | Whether copy and paste is allowed.|
| showPasswordIcon<sup>9+</sup> | boolean | true | Whether to display the show password icon at the end of the password text box.| | showPasswordIcon<sup>9+</sup> | boolean | Whether to display the show password icon at the end of the password text box.<br>Default value: **true**|
| style<sup>9+</sup> | TextInputStyle | Default | Text input style.| | style<sup>9+</sup> | TextInputStyle | Text input style.<br>Default value: **TextInputStyle.Default**|
| textAlign<sup>9+</sup> | [TextAlign](ts-appendix-enums.md#textalign) | Horizontal alignment mode of the text.<br>Default value: **TextAlign.Start** |
- EnterKeyType enums
| Name | Description | ## EnterKeyType
| -------- | -------- |
| EnterKeyType.Go | The Enter key is labeled **Go**. | | Name | Description |
| EnterKeyType.Search | The Enter key is labeled **Search**. | | ------------------- | --------- |
| EnterKeyType.Send | The Enter key is labeled **Send**. | | Go | The Enter key is labeled "Go." |
| EnterKeyType.Next | The Enter key is labeled **Next**. | | Search | The Enter key is labeled "Search." |
| EnterKeyType.Done | The Enter key is labeled **Done**. | | Send | The Enter key is labeled "Send." |
| Next | The Enter key is labeled "Next."|
- InputType enums | Done | The Enter key is labeled "Done." |
| Name | Description |
| -------- | -------- | ## InputType enums
| InputType.Normal | Normal input mode. |
| InputType.Password | Password input mode. | | Name | Description |
| InputType.Email | Email address input mode. | | ------------------ | ------------- |
| InputType.Number | Digit input mode. | | Normal | Normal input mode.<br>The value can contain digits, letters, underscores (_), spaces, and special characters.|
| Password | Password input mode. |
- TextInputStyle | Email | Email address input mode.|
| Name | Description | | Number | Digit input mode. |
| ------------------ | ------------- | | PhoneNumber<sup>9+</sup> | Phone number input mode.<br>The value can contain digits, plus signs (+), hyphens (-), asterisks (*), and number signs (#). The length is not limited.|
| Default | Default style. The caret width is fixed at 1.5 vp, and the caret height increases with the font size. |
| Inline | Inline input style. When text is selected, its background height is the same as the height of the text box. | ## SwipeEdgeEffect<sup>9+</sup>
## Events | Name | Description |
| ------------------ | ------------- |
| Name | Description | | Default | Default style. The caret width is fixed at 1.5 vp, and the caret height increases with the font size. |
| -------- | -------- | | Inline | Inline input style. When text is selected, its background height is the same as the height of the text box. |
| onChange(value: string) =&gt; void | Triggered when the input changes. |
| onSubmit(callback: (enterKey: EnterKeyType) =&gt; void) | Triggered when the Enter key on the physical or soft keyboard is pressed. | ## Event
| onEditChanged(callback:&nbsp;(isEditing:&nbsp;boolean)&nbsp;=&gt;&nbsp;void)<sup>(deprecated) </sup> | Triggered when the input status changes. |
| onEditChange(callback:&nbsp;(isEditing:&nbsp;boolean)&nbsp;=&gt;&nbsp;void) <sup>8+</sup> | Triggered when the input status changes. | | Name | Description |
| onCopy<sup>8+</sup>(callback:(value: string) =&gt; void) | Triggered when the copy button on the pasteboard, which displays when the text box is long pressed, is clicked.<br>**value**: text to be copied. | | ---------------------------------------- | ---------------------------------------- |
| onCut<sup>8+</sup>(callback:(value: string) =&gt; void) | Triggered when the cut button on the pasteboard, which displays when the text box is long pressed, is clicked.<br>**value**: text to be cut. | | onChange(callback: (value: string) =&gt; void) | Triggered when the input changes. |
| onPaste<sup>8+</sup>(callback:(value: string) =&gt; void) | Triggered when the paste button on the pasteboard, which displays when the text box is long pressed, is clicked.<br>**value**: text to be pasted. | | onSubmit(callback: (enterKey: EnterKeyType) =&gt; void) | Triggered when the Enter key on the physical or soft keyboard is pressed. |
| onEditChanged(callback: (isEditing: boolean) =&gt; void)<sup>(deprecated) </sup> | Triggered when the input status changes. |
### TextInputController<sup>8+</sup> | onEditChange(callback: (isEditing: boolean) =&gt; void) <sup>8+</sup> | Triggered when the input status changes. |
| onCopy<sup>8+</sup>(callback:(value: string) =&gt; void) | Triggered when the copy button on the pasteboard, which displays when the text box is long pressed, is clicked.<br>**value**: text to be copied.|
| onCut<sup>8+</sup>(callback:(value: string) =&gt; void) | Triggered when the cut button on the pasteboard, which displays when the text box is long pressed, is clicked.<br>**value**: text to be cut.|
| onPaste<sup>8+</sup>(callback:(value: string) =&gt; void) | Triggered when the paste button on the pasteboard, which displays when the text box is long pressed, is clicked.<br>**value**: text to be pasted.|
## TextInputController<sup>8+</sup>
Implements the controller of the **\<TextInput>** component. Implements the controller of the **\<TextInput>** component.
### Objects to Import
#### Objects to Import
``` ```
controller: TextInputController = new TextInputController() controller: TextInputController = new TextInputController()
``` ```
### caretPosition
#### caretPosition
caretPosition(value: number): void caretPosition(value: number): void
Sets the position of the caret. Sets the position of the caret.
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| value | number | Yes | - | Length from the start of the text string to the position where the caret is located. |
| Name| Type| Mandatory| Description |
| ------ | -------- | ---- | -------------------------------------- |
| value | number | Yes | Length from the start of the string to the position where the caret is located.|
## Example ## Example
......
...@@ -7,11 +7,6 @@ The **TextPicker** component allows users to scroll to select text. ...@@ -7,11 +7,6 @@ The **TextPicker** component allows users to scroll to select text.
> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. > This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
None
## Child Components ## Child Components
Not supported Not supported
...@@ -19,27 +14,28 @@ Not supported ...@@ -19,27 +14,28 @@ Not supported
## APIs ## APIs
TextPicker(options: {range: string[]|Resource, selected?: number, value?: string}) TextPicker(options?: {range: string[]|Resource, selected?: number, value?: string})
Creates a text picker based on the selection range specified by **range**. Creates a text picker based on the selection range specified by **range**.
- Parameters **Parameters**
| Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- |
| range | string[] \| [Resource](../../ui/ts-types.md#resource-type)| Yes| - | Data selection range of the picker.|
| selected | number | No| 0 | Index of the selected item in the range. |
| value | string | No| Value of the first item| Value of the selected item. The priority of this parameter is lower than that of **selected**.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| range | string[] \| [Resource](ts-types.md#resource)| Yes| Data selection range of the picker.|
| selected | number | No| Index of the selected item in the range.<br>Default value: **0**|
| value | string | No| Value of the selected item. The priority of this parameter is lower than that of **selected**.<br>Default value: value of the first item|
## Attributes ## Attributes
| Name| Type| Default Value| Description| | Name| Type| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- |
| defaultPickerItemHeight | Length | - | Default height of an item in the picker.| | defaultPickerItemHeight | number \| string | Default height of an item in the picker.|
## Events ## Events
In addition to the [universal events](ts-universal-events-click.md), the following events are supported.
| Name| Description| | Name| Description|
| -------- | -------- | | -------- | -------- |
| onChange(callback: (value: string, index: number) =&gt; void) | Triggered when an item in the picker is selected.<br>- **value**: value of the selected item.<br>- **index**: index of the selected item.| | onChange(callback: (value: string, index: number) =&gt; void) | Triggered when an item in the picker is selected.<br>- **value**: value of the selected item.<br>- **index**: index of the selected item.|
......
# TextTimer # TextTimer
The **\<TextTimer>** component displays timing information and is controlled in text format.
> **NOTE**<br> > **NOTE**
> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. >
> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
The **&lt;TextTimer&gt;** component supports custom time formats.
## Required Permissions
None
## Child Components ## Child Components
None Not supported
## APIs ## APIs
TextTimer(options: { isCountDown?: boolean, count?: number, controller?: TextTimerController }) TextTimer(options?: { isCountDown?: boolean, count?: number, controller?: TextTimerController })
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- | | Name| Type| Mandatory| Description|
| isCountDown | boolean | No | false | Whether to count down. | | -------- | -------- | -------- | -------- |
| count | number | No | 60000 | Countdown time, in milliseconds. This parameter is valid only when **isCountDown** is set to **true**.<br/>- If the specified value is less than or equal to 0, the default value is used.<br/>- If the specified value is greater than 0, the value is used. | | isCountDown | boolean | No| Whether to count down.<br/>Default value: **false** |
| controller | [TextTimerController](#texttimercontroller) | No | null | **&lt;TextTimer&gt;** controller. | | count | number | No| Countdown time, in milliseconds. This parameter is valid only when **isCountDown** is set to **true**.<br>If the value of **count** is less than or equal to 0, the default value is used.<br>If the value of **count** is greater than 0, it is used.<br/>Default value: **60000** |
| controller | [TextTimerController](#texttimercontroller) | No| **\<TextTimer>** controller.|
## Attributes ## Attributes
| Name | Type | Default Value | Description | | Name| Type| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- |
| format | string | 'hh:mm:ss.ms' | Custom format. The value must contain at least one of the following keywords: **hh**, **mm**, **ss**, and **ms**. | | format | string | Custom format. The value must contain at least one of the following keywords: **hh**, **mm**, **ss**, and **ms**.<br>Default value: **'hh:mm:ss.ms'** |
## Events ## Events
| Name | Description | | Name| Description|
| -------- | -------- | | -------- | -------- |
| onTimer(callback: (utc: number, elapsedTime: number) =&gt; void) | Triggered when the time text changes.<br/>**utc**: currently displayed time, in milliseconds.<br/>**elapsedTime**: elapsed time of the timer, in milliseconds. | | onTimer(event: (utc: number, elapsedTime: number) =&gt; void) | Triggered when the time text changes.<br>**utc**: currently displayed time, in milliseconds.<br>**elapsedTime**: elapsed time of the timer, in milliseconds.|
## TextTimerController ## TextTimerController
Defines the controller for controlling the **&lt;TextTimer&gt;** component. Defines the controller for controlling the **\<TextTimer>** component. A **\<TextTimer>** component can be bound to only one controller.
### Objects to Import ### Objects to Import
...@@ -64,7 +59,7 @@ Starts the timer. ...@@ -64,7 +59,7 @@ Starts the timer.
pause() pause()
Pauses the timer. Pauses the timer.
### reset ### reset
...@@ -75,8 +70,8 @@ Resets the timer. ...@@ -75,8 +70,8 @@ Resets the timer.
## Example ## Example
```ts
``` // xxx.ets
@Entry @Entry
@Component @Component
struct TextTimerExample { struct TextTimerExample {
...@@ -88,9 +83,9 @@ struct TextTimerExample { ...@@ -88,9 +83,9 @@ struct TextTimerExample {
TextTimer({controller: this.textTimerController}) TextTimer({controller: this.textTimerController})
.format(this.format) .format(this.format)
.fontColor(Color.Black) .fontColor(Color.Black)
.fontSize(this.textSize) .fontSize(50)
.onTimer((utc: number, elapsedTime: number) => { .onTimer((utc: number, elapsedTime: number) => {
console.info('textTimer notCountDown utc is:' + utc + ', elapsedTime: ' + elapsedTime) console.info('textTimer notCountDown utc is: ' + utc + ', elapsedTime: ' + elapsedTime)
}) })
Row() { Row() {
Button("start").onClick(() => { Button("start").onClick(() => {
......
# TimePicker # TimePicker
The **\<TimePicker>** component allows users to select a time from the given range. The **\<TimePicker>** component allows users to select a time from the given range.
> **NOTE**<br> > **NOTE**
> >
> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. > This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
No
## Child Components ## Child Components
...@@ -20,40 +14,41 @@ Not supported ...@@ -20,40 +14,41 @@ Not supported
## APIs ## APIs
TimePicker(options?: TimePickerOptions) TimePicker(options?: {selected?: Date})
Creates a time picker whose default time range is from 00:00 to 23:59. Creates a time picker whose default time range is from 00:00 to 23:59.
- options parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| -------- | ---- | --------- | ------------------- | -------------------------- | | Name| Type| Mandatory| Description|
| selected | Date | No | Current system time | Time of the selected item. | | -------- | -------- | -------- | -------- |
| selected | Date | No| Time of the selected item.<br>Default value: current system time|
## Attributes ## Attributes
| Name | Type | Default Value | Description | | Name| Type| Description|
| --------------- | ------- | ------------- | ---------------------------------------- | | -------- | -------- | -------- |
| useMilitaryTime | boolean | false | Whether to display time in 24-hour format. The value cannot be modified dynamically. | | useMilitaryTime | boolean | Whether to display time in 24-hour format. The value cannot be modified dynamically.<br>Default value: **false**|
## Events ## Events
| Name | Description | | Name | Description |
| ---------------------------------------- | ---------------------------------- | | ---------------------------------------- | ----------- |
| onChange(callback:&nbsp;(value:&nbsp;TimePickerResult )&nbsp;=&gt;&nbsp;void) | Triggered when a time is selected. | | onChange(callback: (value: TimePickerResult ) =&gt; void) | Triggered when a time is selected.|
### TimePickerResult ### TimePickerResult
| Name | Type | Description | | Name | Type | Description |
| ------ | ------ | ------------------------------------ | | ------ | ------ | ------- |
| hour | number | Hour portion of the selected time. | | hour | number | Hour portion of the selected time.|
| minute | number | Minute portion of the selected time. | | minute | number | Minute portion of the selected time.|
## Example ## Example
### Time Picker ### Time Selector
```ts ```ts
// xxx.ets // xxx.ets
......
# Toggle # Toggle
> **NOTE**<br> The **\<Toggle>** component provides a clickable element in the check box, button, or switch type.
> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
> **NOTE**
>
> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions ## Required Permissions
...@@ -11,7 +14,7 @@ None ...@@ -11,7 +14,7 @@ None
## Child Components ## Child Components
N/A This component can contain child components only when **ToggleType** is set to **Button**.
## APIs ## APIs
...@@ -19,33 +22,33 @@ N/A ...@@ -19,33 +22,33 @@ N/A
Toggle(options: { type: ToggleType, isOn?: boolean }) Toggle(options: { type: ToggleType, isOn?: boolean })
- Parameters - Parameters
| Name| Type| Mandatory| Default Value| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | ToggleType | Yes| - | Type of the toggle.| | type | ToggleType | Yes| Type of the toggle.|
| isOn | boolean | No| false | Whether the toggle is turned on. The value **true** means that the toggle is turned on, and **false** means the opposite.| | isOn | boolean | No| Whether the toggle is turned on. The value **true** means that the toggle is turned on, and **false** means the opposite.<br/>Default value: **false** |
- ToggleType enums - ToggleType enums
| Name| Description| | Name| Description|
| -------- | -------- | | -------- | -------- |
| Checkbox | A checkbox is provided, where the **\<Text>** settings can take effect only when it is placed with the current component in a layout component.<br>> **NOTE**<br><br>> The default value of the universal attribute [padding](ts-universal-attributes-size.md) is as follows:<br>{<br>&nbsp;top: 14 vp,<br>&nbsp;right: 6 vp,<br>&nbsp;bottom: 14 vp,<br>&nbsp;left: 6 vp<br> } | | Checkbox | Check box type.<br>> **NOTE**<br>> The default value of the universal attribute [padding](ts-universal-attributes-size.md) is as follows:<br>{<br> top: 14 vp,<br> right: 6 vp,<br> bottom: 14 vp,<br> left: 6 vp<br> } |
| Button | A button is provided. The set text string, if any, will be displayed inside the button.| | Button | Button type. The set string, if any, will be displayed inside the button. |
| Switch | A switch is provided, where the **\<Text>** settings can take effect only when it is placed with the current component in a layout component.<br>> **NOTE**<br><br>> The default value of the universal attribute [padding](ts-universal-attributes-size.md) is as follows:<br>{<br>&nbsp;top: 12 vp,<br>&nbsp;right: 12 vp,<br>&nbsp;bottom: 12 vp,<br>&nbsp;left: 12 vp<br> } | | Switch | Switch type.<br>> **NOTE**<br>> The default value of the universal attribute [padding](ts-universal-attributes-size.md) is as follows:<br>{<br> top: 12 vp,<br> right: 12 vp,<br> bottom: 12 vp,<br> left: 12 vp<br> } |
## Attributes ## Attributes
| Name| Parameter| Default Value| Description| | Name| Parameter| Default Value| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| selectedColor | Color | - | Background color of the component when it is turned on.| | selectedColor | [ResourceColor](ts-types.md#resourcecolor) | - | Background color of the component when it is turned on.|
| switchPointColor | Color | - | Color of the circular slider when the component is of the **Switch** type.<br>> **NOTE**<br>> This attribute is valid only when **type** is set to **ToggleType.Switch**. | | switchPointColor | [ResourceColor](ts-types.md#resourcecolor) | - | Color of the circular slider when the component is of the **Switch** type.<br>> **NOTE**<br>> This attribute is valid only when **type** is set to **ToggleType.Switch**.|
## Events ## Events
| Name| Description| | Name| Description|
| -------- | -------- | | -------- | -------- |
| onChange(callback:&nbsp;(isOn:&nbsp;boolean)&nbsp;=&gt;&nbsp;void) | Triggered when the toggle status changes.| | onChange(callback: (isOn: boolean) =&gt; void) | Triggered when the toggle status changes.|
## Example ## Example
......
# Web # Web
The **<Web\>** component can be used to display web pages.
> **NOTE** > **NOTE**
> >
> - This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. > - This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
> - You can preview how this component looks on a real device. The preview is not yet available in the DevEco Studio Previewer. > - You can preview how this component looks on a real device. The preview is not yet available in the DevEco Studio Previewer.
The **<Web\>** component can be used to display web pages.
## Required Permissions ## Required Permissions
ohos.permission.INTERNET, required only for accessing online web pages To use online resources, the application must have the **ohos.permission.INTERNET** permission. For details about how to apply for a permission, see [Declaring Permissions](../../security/accesstoken-guidelines.md).
## Child Components ## Child Components
...@@ -16,32 +16,60 @@ Not supported ...@@ -16,32 +16,60 @@ Not supported
## APIs ## APIs
Web(options: { src: string, controller?: WebController }) Web(options: { src: ResourceStr, controller: WebController })
> **NOTE**
>
> Transition animation is not supported.
**Parameters** **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ---------- | ------------------------------- | ---- | ---- | ------- | | Name | Type | Mandatory | Description |
| src | string | Yes | - | Address of a web page resource.| | ---------- | ------------------------------- | ---- | ------- |
| controller | [WebController](#webcontroller) | No | - | Controller. | | src | [ResourceStr](ts-types.md) | Yes | Address of a web page resource.|
| controller | [WebController](#webcontroller) | No | Controller. |
**Example** **Example**
Loading Online Web Pages
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller:WebController = new WebController(); controller: WebController = new WebController();
build() { build() {
Column() { Column() {
Web({ src:'www.example.com', controller:this.controller }) Web({ src: 'www.example.com', controller: this.controller })
} }
} }
} }
``` ```
> **NOTE**<br> Loading Local Web Pages
> ```ts
> Transition animation is not supported. // xxx.ets
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
build() {
Column() {
Web({ src: $rawfile("index.html"), controller: this.controller })
}
}
}
```
```html
<!-- index.html -->
<!DOCTYPE html>
<html>
<body>
<p>Hello World</p>
</body>
</html>
```
## Attributes ## Attributes
...@@ -54,21 +82,23 @@ domStorageAccess(domStorageAccess: boolean) ...@@ -54,21 +82,23 @@ domStorageAccess(domStorageAccess: boolean)
Sets whether to enable the DOM Storage API. By default, this feature is disabled. Sets whether to enable the DOM Storage API. By default, this feature is disabled.
**Parameters** **Parameters**
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| ---------------- | ------- | ---- | ---- | ------------------------------------ | | ---------------- | ------- | ---- | ---- | ------------------------------------ |
| domStorageAccess | boolean | Yes | false | Whether to enable the DOM Storage API.| | domStorageAccess | boolean | Yes | false | Whether to enable the DOM Storage API.|
**Example** **Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller:WebController = new WebController(); controller: WebController = new WebController();
build() { build() {
Column() { Column() {
Web({ src:'www.example.com', controller:this.controller }) Web({ src: 'www.example.com', controller: this.controller })
.domStorageAccess(true) .domStorageAccess(true)
} }
} }
} }
...@@ -81,21 +111,23 @@ fileAccess(fileAccess: boolean) ...@@ -81,21 +111,23 @@ fileAccess(fileAccess: boolean)
Sets whether to enable the access to the file system in the application. By default, this feature is disabled. Access to the files specified through [$rawfile(filepath/filename)](../../ui/ts-resource-access.md) are not affected by this attribute. Sets whether to enable the access to the file system in the application. By default, this feature is disabled. Access to the files specified through [$rawfile(filepath/filename)](../../ui/ts-resource-access.md) are not affected by this attribute.
**Parameters** **Parameters**
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| ---------- | ------- | ---- | ---- | ---------------------------------------- | | ---------- | ------- | ---- | ---- | ---------------------------------------- |
| fileAccess | boolean | Yes | true | Whether to enable the access to the file system in the application. | | fileAccess | boolean | Yes | true | Whether to enable the access to the file system in the application.|
**Example** **Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller:WebController = new WebController(); controller: WebController = new WebController();
build() { build() {
Column() { Column() {
Web({ src:'www.example.com', controller:this.controller }) Web({ src: 'www.example.com', controller: this.controller })
.fileAccess(true) .fileAccess(true)
} }
} }
} }
...@@ -108,21 +140,23 @@ fileFromUrlAccess(fileFromUrlAccess: boolean) ...@@ -108,21 +140,23 @@ fileFromUrlAccess(fileFromUrlAccess: boolean)
Sets whether to allow the use of JavaScript scripts on web pages for access to content in the application file system. By default, this feature is disabled. Access to the files specified through [$rawfile(filepath/filename)](../../ui/ts-resource-access.md) are not affected by this attribute. Sets whether to allow the use of JavaScript scripts on web pages for access to content in the application file system. By default, this feature is disabled. Access to the files specified through [$rawfile(filepath/filename)](../../ui/ts-resource-access.md) are not affected by this attribute.
**Parameters** **Parameters**
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| ----------------- | ------- | ---- | ----- | ---------------------------------------- | | ----------------- | ------- | ---- | ----- | ---------------------------------------- |
| fileFromUrlAccess | boolean | Yes | false | Whether to allow the use of JavaScript scripts on web pages for access to content in the application file system. | | fileFromUrlAccess | boolean | Yes | false | Whether to allow the use of JavaScript scripts on web pages for access to content in the application file system. By default, this feature is disabled.|
**Example** **Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller:WebController = new WebController(); controller: WebController = new WebController();
build() { build() {
Column() { Column() {
Web({ src:'www.example.com', controller:this.controller }) Web({ src: 'www.example.com', controller: this.controller })
.fileFromUrlAccess(true) .fileFromUrlAccess(true)
} }
} }
} }
...@@ -135,9 +169,10 @@ imageAccess(imageAccess: boolean) ...@@ -135,9 +169,10 @@ imageAccess(imageAccess: boolean)
Sets whether to enable automatic image loading. By default, this feature is enabled. Sets whether to enable automatic image loading. By default, this feature is enabled.
**Parameters** **Parameters**
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| ----------- | ------- | ---- | ---- | --------------- | | ----------- | ------- | ---- | ---- | --------------- |
| imageAccess | boolean | Yes | true | Whether to enable automatic image loading. | | imageAccess | boolean | Yes | true | Whether to enable automatic image loading. By default, this feature is enabled.|
**Example** **Example**
```ts ```ts
...@@ -145,11 +180,11 @@ Sets whether to enable automatic image loading. By default, this feature is enab ...@@ -145,11 +180,11 @@ Sets whether to enable automatic image loading. By default, this feature is enab
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller:WebController = new WebController(); controller: WebController = new WebController();
build() { build() {
Column() { Column() {
Web({ src:'www.example.com', controller:this.controller }) Web({ src: 'www.example.com', controller: this.controller })
.imageAccess(true) .imageAccess(true)
} }
} }
} }
...@@ -163,19 +198,22 @@ javaScriptProxy(javaScriptProxy: { object: object, name: string, methodList: Arr ...@@ -163,19 +198,22 @@ javaScriptProxy(javaScriptProxy: { object: object, name: string, methodList: Arr
Injects a JavaScript object into the window. Methods of this object can be invoked in the window. The parameters cannot be updated. Injects a JavaScript object into the window. Methods of this object can be invoked in the window. The parameters cannot be updated.
**Parameters** **Parameters**
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| ---------- | --------------- | ---- | ---- | ------------------------- | | ---------- | --------------- | ---- | ---- | ------------------------- |
| object | object | Yes | - | Object to be registered. Methods can be declared, but not attributes. | | object | object | Yes | - | Object to be registered. Methods can be declared, but not attributes. |
| name | string | Yes | - | Name of the object to be registered, which is the same as that invoked in the window.| | name | string | Yes | - | Name of the object to be registered, which is the same as that invoked in the window.|
| methodList | Array\<string\> | Yes | - | Methods of the JavaScript object to be registered at the application side. | | methodList | Array\<string\> | Yes | - | Methods of the JavaScript object to be registered at the application side. |
| controller | [WebController](#webcontroller) | No | - | Controller. |
**Example** **Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller:WebController = new WebController(); controller: WebController = new WebController();
testObj = { testObj = {
test: (data1, data2, data3) => { test: (data1, data2, data3) => {
console.log("data1:" + data1); console.log("data1:" + data1);
...@@ -189,13 +227,13 @@ Injects a JavaScript object into the window. Methods of this object can be invok ...@@ -189,13 +227,13 @@ Injects a JavaScript object into the window. Methods of this object can be invok
} }
build() { build() {
Column() { Column() {
Web({ src:'www.example.com', controller:this.controller }) Web({ src: 'www.example.com', controller: this.controller })
.javaScriptAccess(true) .javaScriptAccess(true)
.javaScriptProxy({ .javaScriptProxy({
object: this.testObj, object: this.testObj,
name: "objName", name: "objName",
methodList: ["test", "toString"], methodList: ["test", "toString"],
controller: this.controller, controller: this.controller,
}) })
} }
} }
...@@ -209,21 +247,23 @@ javaScriptAccess(javaScriptAccess: boolean) ...@@ -209,21 +247,23 @@ javaScriptAccess(javaScriptAccess: boolean)
Sets whether JavaScript scripts can be executed. By default, JavaScript scripts can be executed. Sets whether JavaScript scripts can be executed. By default, JavaScript scripts can be executed.
**Parameters** **Parameters**
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| ---------------- | ------- | ---- | ---- | ------------------- | | ---------------- | ------- | ---- | ---- | ------------------- |
| javaScriptAccess | boolean | Yes | true | Whether JavaScript scripts can be executed.| | javaScriptAccess | boolean | Yes | true | Whether JavaScript scripts can be executed.|
**Example** **Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller:WebController = new WebController(); controller: WebController = new WebController();
build() { build() {
Column() { Column() {
Web({ src:'www.example.com', controller:this.controller }) Web({ src: 'www.example.com', controller: this.controller })
.javaScriptAccess(true) .javaScriptAccess(true)
} }
} }
} }
...@@ -236,22 +276,24 @@ mixedMode(mixedMode: MixedMode) ...@@ -236,22 +276,24 @@ mixedMode(mixedMode: MixedMode)
Sets whether to enable loading of HTTP and HTTPS hybrid content can be loaded. By default, this feature is disabled. Sets whether to enable loading of HTTP and HTTPS hybrid content can be loaded. By default, this feature is disabled.
**Parameters** **Parameters**
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| --------- | --------------------------- | ---- | ---- | --------- | | --------- | --------------------------- | ---- | ---- | --------- |
| mixedMode | [MixedMode](#mixedmode)| Yes | - | Mixed content to load.| | mixedMode | [MixedMode](#mixedmode)| Yes | MixedMode.None | Mixed content to load.|
**Example** **Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller:WebController = new WebController(); controller: WebController = new WebController();
@State mode:MixedMode = MixedMode.All; @State mode: MixedMode = MixedMode.All;
build() { build() {
Column() { Column() {
Web({ src:'www.example.com', controller:this.controller }) Web({ src: 'www.example.com', controller: this.controller })
.mixedMode(this.mode) .mixedMode(this.mode)
} }
} }
} }
...@@ -264,21 +306,23 @@ onlineImageAccess(onlineImageAccess: boolean) ...@@ -264,21 +306,23 @@ onlineImageAccess(onlineImageAccess: boolean)
Sets whether to enable access to online images through HTTP and HTTPS. By default, this feature is enabled. Sets whether to enable access to online images through HTTP and HTTPS. By default, this feature is enabled.
**Parameters** **Parameters**
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| ----------------- | ------- | ---- | ---- | ---------------- | | ----------------- | ------- | ---- | ---- | ---------------- |
| onlineImageAccess | boolean | Yes | true | Whether to enable access to online images through HTTP and HTTPS.| | onlineImageAccess | boolean | Yes | true | Whether to enable access to online images through HTTP and HTTPS.|
**Example** **Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller:WebController = new WebController(); controller: WebController = new WebController();
build() { build() {
Column() { Column() {
Web({ src:'www.example.com', controller:this.controller }) Web({ src: 'www.example.com', controller: this.controller })
.onlineImageAccess(true) .onlineImageAccess(true)
} }
} }
} }
...@@ -291,21 +335,23 @@ zoomAccess(zoomAccess: boolean) ...@@ -291,21 +335,23 @@ zoomAccess(zoomAccess: boolean)
Sets whether to enable zoom gestures. By default, this feature is enabled. Sets whether to enable zoom gestures. By default, this feature is enabled.
**Parameters** **Parameters**
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| ---------- | ------- | ---- | ---- | ------------- | | ---------- | ------- | ---- | ---- | ------------- |
| zoomAccess | boolean | Yes | true | Whether to enable zoom gestures.| | zoomAccess | boolean | Yes | true | Whether to enable zoom gestures.|
**Example** **Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller:WebController = new WebController(); controller: WebController = new WebController();
build() { build() {
Column() { Column() {
Web({ src:'www.example.com', controller:this.controller }) Web({ src: 'www.example.com', controller: this.controller })
.zoomAccess(true) .zoomAccess(true)
} }
} }
} }
...@@ -318,21 +364,23 @@ overviewModeAccess(overviewModeAccess: boolean) ...@@ -318,21 +364,23 @@ overviewModeAccess(overviewModeAccess: boolean)
Sets whether to load web pages by using the overview mode. By default, this feature is enabled. Sets whether to load web pages by using the overview mode. By default, this feature is enabled.
**Parameters** **Parameters**
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| ------------------ | ------- | ---- | ---- | --------------- | | ------------------ | ------- | ---- | ---- | --------------- |
| overviewModeAccess | boolean | Yes | true | Whether to load web pages by using the overview mode| | overviewModeAccess | boolean | Yes | true | Whether to load web pages by using the overview mode.|
**Example** **Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller:WebController = new WebController(); controller: WebController = new WebController();
build() { build() {
Column() { Column() {
Web({ src:'www.example.com', controller:this.controller }) Web({ src: 'www.example.com', controller: this.controller })
.overviewModeAccess(true) .overviewModeAccess(true)
} }
} }
} }
...@@ -345,21 +393,23 @@ databaseAccess(databaseAccess: boolean) ...@@ -345,21 +393,23 @@ databaseAccess(databaseAccess: boolean)
Sets whether to enable database access. By default, this feature is disabled. Sets whether to enable database access. By default, this feature is disabled.
**Parameters** **Parameters**
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| -------------- | ------- | ---- | ---- | ----------------- | | -------------- | ------- | ---- | ---- | ----------------- |
| databaseAccess | boolean | Yes | false | Whether to enable database access. | | databaseAccess | boolean | Yes | false | Whether to enable database access.|
**Example** **Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller:WebController = new WebController(); controller: WebController = new WebController();
build() { build() {
Column() { Column() {
Web({ src:'www.example.com', controller:this.controller }) Web({ src: 'www.example.com', controller: this.controller })
.databaseAccess(true) .databaseAccess(true)
} }
} }
} }
...@@ -372,21 +422,53 @@ geolocationAccess(geolocationAccess: boolean) ...@@ -372,21 +422,53 @@ geolocationAccess(geolocationAccess: boolean)
Sets whether to enable geolocation access. By default, this feature is enabled. Sets whether to enable geolocation access. By default, this feature is enabled.
**Parameters** **Parameters**
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| -------------- | ------- | ---- | ---- | ----------------- | | -------------- | ------- | ---- | ---- | ----------------- |
| geolocationAccess | boolean | Yes | true | Whether to enable geolocation access. | | geolocationAccess | boolean | Yes | true | Whether to enable geolocation access.|
**Example** **Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller:WebController = new WebController(); controller: WebController = new WebController();
build() { build() {
Column() { Column() {
Web({ src:'www.example.com', controller:this.controller }) Web({ src: 'www.example.com', controller: this.controller })
.geolocationAccess(true) .geolocationAccess(true)
}
}
}
```
### mediaPlayGestureAccess
mediaPlayGestureAccess(access: boolean)
Sets whether a manual click is required for video playback.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| --------- | ------ | ---- | ---- | --------- |
| access | boolean | Yes | true | Whether a manual click is required for video playback.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
@State access: boolean = true;
build() {
Column() {
Web({ src: 'www.example.com', controller: this.controller })
.mediaPlayGestureAccess(this.access)
} }
} }
} }
...@@ -399,22 +481,24 @@ cacheMode(cacheMode: CacheMode) ...@@ -399,22 +481,24 @@ cacheMode(cacheMode: CacheMode)
Sets the cache mode. Sets the cache mode.
**Parameters** **Parameters**
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| --------- | --------------------------- | ---- | ---- | --------- | | --------- | --------------------------- | ---- | ---- | --------- |
| cacheMode | [CacheMode](#cachemode)| Yes | CacheMode.Default | Cache mode to set.| | cacheMode | [CacheMode](#cachemode)| Yes | CacheMode.Default | Cache mode to set.|
**Example** **Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller:WebController = new WebController(); controller: WebController = new WebController();
@State mode:CacheMode = CacheMode.None; @State mode: CacheMode = CacheMode.None;
build() { build() {
Column() { Column() {
Web({ src:'www.example.com', controller:this.controller }) Web({ src: 'www.example.com', controller: this.controller })
.cacheMode(this.mode) .cacheMode(this.mode)
} }
} }
} }
...@@ -427,22 +511,24 @@ textZoomRatio(textZoomRatio: number) ...@@ -427,22 +511,24 @@ textZoomRatio(textZoomRatio: number)
Sets the text zoom ratio of the page. The default value is **100**, which indicates 100%. Sets the text zoom ratio of the page. The default value is **100**, which indicates 100%.
**Parameters** **Parameters**
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| ------------ | ------ | ---- | ---- | --------------- | | ------------ | ------ | ---- | ---- | --------------- |
| textZoomRatio | number | Yes | 100 | Text zoom ratio to set.| | textZoomRatio | number | Yes | 100 | Text zoom ratio to set.|
**Example** **Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller:WebController = new WebController(); controller: WebController = new WebController();
@State atio:number = 150; @State atio: number = 150;
build() { build() {
Column() { Column() {
Web({ src:'www.example.com', controller:this.controller }) Web({ src: 'www.example.com', controller: this.controller })
.textZoomRatio(this.atio) .textZoomRatio(this.atio)
} }
} }
} }
...@@ -455,30 +541,32 @@ userAgent(userAgent: string) ...@@ -455,30 +541,32 @@ userAgent(userAgent: string)
Sets the user agent. Sets the user agent.
**Parameters** **Parameters**
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| --------- | ------ | ---- | ---- | --------- | | --------- | ------ | ---- | ---- | --------- |
| userAgent | string | Yes | - | User agent to set.| | userAgent | string | Yes | - | User agent to set.|
**Example** **Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller:WebController = new WebController(); controller: WebController = new WebController();
@State userAgent:string = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36'; @State userAgent:string = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36';
build() { build() {
Column() { Column() {
Web({ src:'www.example.com', controller:this.controller }) Web({ src: 'www.example.com', controller: this.controller })
.userAgent(this.userAgent) .userAgent(this.userAgent)
} }
} }
} }
``` ```
> **NOTE**<br> > **NOTE**
> >
> Only the following universal attributes are supported: [width](ts-universal-attributes-size.md#attributes), [height](ts-universal-attributes-size.md#attributes), [padding](ts-universal-attributes-size.md#attributes), [margin](ts-universal-attributes-size.md#attributes), and [border](ts-universal-attributes-border.md#attributes). > Only the following universal attributes are supported: [width](ts-universal-attributes-size.md#Attributes), [height](ts-universal-attributes-size.md#attributes), [padding](ts-universal-attributes-size.md#Attributes), [margin](ts-universal-attributes-size.md#attributes), and [border](ts-universal-attributes-border.md#attributes).
## Events ## Events
...@@ -491,6 +579,7 @@ onAlert(callback: (event?: { url: string; message: string; result: JsResult }) = ...@@ -491,6 +579,7 @@ onAlert(callback: (event?: { url: string; message: string; result: JsResult }) =
Triggered when **alert()** is invoked to display an alert dialog box on the web page. Triggered when **alert()** is invoked to display an alert dialog box on the web page.
**Parameters** **Parameters**
| Name | Type | Description | | Name | Type | Description |
| ------- | --------------------- | --------------- | | ------- | --------------------- | --------------- |
| url | string | URL of the web page where the dialog box is displayed.| | url | string | URL of the web page where the dialog box is displayed.|
...@@ -498,26 +587,34 @@ Triggered when **alert()** is invoked to display an alert dialog box on the web ...@@ -498,26 +587,34 @@ Triggered when **alert()** is invoked to display an alert dialog box on the web
| result | [JsResult](#jsresult) | The user's operation. | | result | [JsResult](#jsresult) | The user's operation. |
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------- | ---------------------------------------- | | ------- | ---------------------------------------- |
| boolean | If the callback returns **false**, the default dialog box is displayed. If the callback returns **true**, a system application can use the system dialog box (allows the confirm and cancel operations) and invoke the **JsResult** API to notify the **\<Web>** component of the user's operation.| | boolean | If the callback returns **false**, the default dialog box is displayed. If the callback returns **true**, a system application can use the system dialog box (allows the confirm and cancel operations) and invoke the **JsResult** API to notify the **\<Web>** component of the user's operation.|
**Example** **Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller:WebController = new WebController(); controller: WebController = new WebController();
build() { build() {
Column() { Column() {
Web({ src:'www.example.com', controller:this.controller }) Web({ src: 'www.example.com', controller: this.controller })
.onAlert((event) => { .onAlert((event) => {
AlertDialog.show({ AlertDialog.show({
title: 'title', title: 'onAlert',
message: 'text', message: 'text',
confirm: { primaryButton: {
value: 'onAlert', value: 'cancel',
action: () => {
event.result.handleCancel()
}
},
secondaryButton: {
value: 'ok',
action: () => { action: () => {
event.result.handleConfirm() event.result.handleConfirm()
} }
...@@ -537,9 +634,10 @@ Triggered when **alert()** is invoked to display an alert dialog box on the web ...@@ -537,9 +634,10 @@ Triggered when **alert()** is invoked to display an alert dialog box on the web
onBeforeUnload(callback: (event?: { url: string; message: string; result: JsResult }) => boolean) onBeforeUnload(callback: (event?: { url: string; message: string; result: JsResult }) => boolean)
Triggered when the current page is about to exit after the user refreshes or closes the page. Triggered when the current page is about to exit after the user refreshes or closes the page. If the user refreshes the page, this callback is triggered only when the page has obtained focus.
**Parameters** **Parameters**
| Name | Type | Description | | Name | Type | Description |
| ------- | --------------------- | --------------- | | ------- | --------------------- | --------------- |
| url | string | URL of the web page where the dialog box is displayed.| | url | string | URL of the web page where the dialog box is displayed.|
...@@ -547,11 +645,13 @@ Triggered when the current page is about to exit after the user refreshes or clo ...@@ -547,11 +645,13 @@ Triggered when the current page is about to exit after the user refreshes or clo
| result | [JsResult](#jsresult) | The user's operation. | | result | [JsResult](#jsresult) | The user's operation. |
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------- | ---------------------------------------- | | ------- | ---------------------------------------- |
| boolean | If the callback returns **false**, the default dialog box is displayed. If the callback returns **true**, a system application can use the system dialog box (allows the confirm and cancel operations) and invoke the **JsResult** API to notify the **\<Web>** component of the user's operation.| | boolean | If the callback returns **false**, the default dialog box is displayed. If the callback returns **true**, a system application can use the system dialog box (allows the confirm and cancel operations) and invoke the **JsResult** API to notify the **\<Web>** component of the user's operation.|
**Example** **Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
...@@ -565,8 +665,26 @@ Triggered when the current page is about to exit after the user refreshes or clo ...@@ -565,8 +665,26 @@ Triggered when the current page is about to exit after the user refreshes or clo
.onBeforeUnload((event) => { .onBeforeUnload((event) => {
console.log("event.url:" + event.url); console.log("event.url:" + event.url);
console.log("event.message:" + event.message); console.log("event.message:" + event.message);
console.log("event.result:" + event.result); AlertDialog.show({
return false; title: 'onBeforeUnload',
message: 'text',
primaryButton: {
value: 'cancel',
action: () => {
event.result.handleCancel()
}
},
secondaryButton: {
value: 'ok',
action: () => {
event.result.handleConfirm()
}
},
cancel: () => {
event.result.handleCancel()
}
})
return true;
}) })
} }
} }
...@@ -580,6 +698,7 @@ onConfirm(callback: (event?: { url: string; message: string; result: JsResult }) ...@@ -580,6 +698,7 @@ onConfirm(callback: (event?: { url: string; message: string; result: JsResult })
Triggered when **confirm()** is invoked by the web page. Triggered when **confirm()** is invoked by the web page.
**Parameters** **Parameters**
| Name | Type | Description | | Name | Type | Description |
| ------- | --------------------- | --------------- | | ------- | --------------------- | --------------- |
| url | string | URL of the web page where the dialog box is displayed.| | url | string | URL of the web page where the dialog box is displayed.|
...@@ -587,11 +706,13 @@ Triggered when **confirm()** is invoked by the web page. ...@@ -587,11 +706,13 @@ Triggered when **confirm()** is invoked by the web page.
| result | [JsResult](#jsresult) | The user's operation. | | result | [JsResult](#jsresult) | The user's operation. |
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------- | ---------------------------------------- | | ------- | ---------------------------------------- |
| boolean | If the callback returns **false**, the default dialog box is displayed. If the callback returns **true**, a system application can use the system dialog box (allows the confirm and cancel operations) and invoke the **JsResult** API to notify the **\<Web>** component of the user's operation.| | boolean | If the callback returns **false**, the default dialog box is displayed. If the callback returns **true**, a system application can use the system dialog box (allows the confirm and cancel operations) and invoke the **JsResult** API to notify the **\<Web>** component of the user's operation.|
**Example** **Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
...@@ -607,10 +728,16 @@ Triggered when **confirm()** is invoked by the web page. ...@@ -607,10 +728,16 @@ Triggered when **confirm()** is invoked by the web page.
console.log("event.message:" + event.message); console.log("event.message:" + event.message);
console.log("event.result:" + event.result); console.log("event.result:" + event.result);
AlertDialog.show({ AlertDialog.show({
title: 'title', title: 'onConfirm',
message: 'text', message: 'text',
confirm: { primaryButton: {
value: 'onConfirm', value: 'cancel',
action: () => {
event.result.handleCancel()
}
},
secondaryButton: {
value: 'ok',
action: () => { action: () => {
event.result.handleConfirm() event.result.handleConfirm()
} }
...@@ -631,6 +758,7 @@ Triggered when **confirm()** is invoked by the web page. ...@@ -631,6 +758,7 @@ Triggered when **confirm()** is invoked by the web page.
onPrompt(callback: (event?: { url: string; message: string; value: string; result: JsResult }) => boolean) onPrompt(callback: (event?: { url: string; message: string; value: string; result: JsResult }) => boolean)
**Parameters** **Parameters**
| Name | Type | Description | | Name | Type | Description |
| ------- | --------------------- | --------------- | | ------- | --------------------- | --------------- |
| url | string | URL of the web page where the dialog box is displayed.| | url | string | URL of the web page where the dialog box is displayed.|
...@@ -638,27 +766,49 @@ onPrompt(callback: (event?: { url: string; message: string; value: string; resul ...@@ -638,27 +766,49 @@ onPrompt(callback: (event?: { url: string; message: string; value: string; resul
| result | [JsResult](#jsresult) | The user's operation. | | result | [JsResult](#jsresult) | The user's operation. |
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------- | ---------------------------------------- | | ------- | ---------------------------------------- |
| boolean | If the callback returns **false**, the default dialog box is displayed. If the callback returns **true**, a system application can use the system dialog box (allows the confirm and cancel operations) and invoke the **JsResult** API to notify the **\<Web>** component of the user's operation.| | boolean | If the callback returns **false**, the default dialog box is displayed. If the callback returns **true**, a system application can use the system dialog box (allows the confirm and cancel operations) and invoke the **JsResult** API to notify the **\<Web>** component of the user's operation.|
**Example** **Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller:WebController = new WebController(); controller: WebController = new WebController();
build() { build() {
Column() { Column() {
Web({ src:'www.example.com', controller:this.controller }) Web({ src: 'www.example.com', controller: this.controller })
.onPrompt((event) => { .onPrompt((event) => {
console.log("url:" + event.url); console.log("url:" + event.url);
console.log("message:" + event.message); console.log("message:" + event.message);
console.log("value:" + event.value); console.log("value:" + event.value);
console.log("result:" + event.result); AlertDialog.show({
return true; title: 'onPrompt',
}) message: 'text',
primaryButton: {
value: 'cancel',
action: () => {
event.result.handleCancel()
}
},
secondaryButton: {
value: 'ok',
action: () => {
event.result.handleConfirm()
}
},
cancel: () => {
event.result.handleCancel()
}
})
return true;
})
}
} }
} }
``` ```
...@@ -670,16 +820,19 @@ onConsole(callback: (event?: { message: ConsoleMessage }) => boolean) ...@@ -670,16 +820,19 @@ onConsole(callback: (event?: { message: ConsoleMessage }) => boolean)
Triggered to notify the host application of a JavaScript console message. Triggered to notify the host application of a JavaScript console message.
**Parameters** **Parameters**
| Name | Type | Description | | Name | Type | Description |
| ------- | --------------------------------- | --------- | | ------- | --------------------------------- | --------- |
| message | [ConsoleMessage](#consolemessage) | Console message.| | message | [ConsoleMessage](#consolemessage) | Console message.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------- | ----------------------------------- | | ------- | ----------------------------------- |
| boolean | Returns **true** if the message will not be printed to the console; returns **false** otherwise.| | boolean | Returns **true** if the message will not be printed to the console; returns **false** otherwise.|
**Example** **Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
...@@ -707,6 +860,7 @@ Triggered to notify the host application of a JavaScript console message. ...@@ -707,6 +860,7 @@ Triggered to notify the host application of a JavaScript console message.
onDownloadStart(callback: (event?: { url: string, userAgent: string, contentDisposition: string, mimetype: string, contentLength: number }) => void) onDownloadStart(callback: (event?: { url: string, userAgent: string, contentDisposition: string, mimetype: string, contentLength: number }) => void)
**Parameters** **Parameters**
| Name | Type | Description | | Name | Type | Description |
| ------------------ | ------------- | ----------------------------------- | | ------------------ | ------------- | ----------------------------------- |
| url | string | URL for the download task. | | url | string | URL for the download task. |
...@@ -715,6 +869,7 @@ onDownloadStart(callback: (event?: { url: string, userAgent: string, contentDisp ...@@ -715,6 +869,7 @@ onDownloadStart(callback: (event?: { url: string, userAgent: string, contentDisp
| contentLength | contentLength | Length of the content returned by the server. | | contentLength | contentLength | Length of the content returned by the server. |
**Example** **Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
...@@ -744,12 +899,14 @@ onErrorReceive(callback: (event?: { request: WebResourceRequest, error: WebResou ...@@ -744,12 +899,14 @@ onErrorReceive(callback: (event?: { request: WebResourceRequest, error: WebResou
Triggered when an error occurs during web page loading. For better results, simplify the implementation logic in the callback. Triggered when an error occurs during web page loading. For better results, simplify the implementation logic in the callback.
**Parameters** **Parameters**
| Name | Type | Description | | Name | Type | Description |
| ------- | ---------------------------------------- | --------------- | | ------- | ---------------------------------------- | --------------- |
| request | [WebResourceRequest](#webresourcerequest) | Encapsulation of a web page request. | | request | [WebResourceRequest](#webresourcerequest) | Encapsulation of a web page request. |
| error | [WebResourceError](#webresourceerror) | Encapsulation of a web page resource loading error.| | error | [WebResourceError](#webresourceerror) | Encapsulation of a web page resource loading error.|
**Example** **Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
...@@ -786,12 +943,14 @@ onHttpErrorReceive(callback: (event?: { request: WebResourceRequest, response: W ...@@ -786,12 +943,14 @@ onHttpErrorReceive(callback: (event?: { request: WebResourceRequest, response: W
Triggered when an HTTP error (the response code is greater than or equal to 400) occurs during web page resource loading. Triggered when an HTTP error (the response code is greater than or equal to 400) occurs during web page resource loading.
**Parameters** **Parameters**
| Name | Type | Description | | Name | Type | Description |
| ------- | ---------------------------------------- | --------------- | | ------- | ---------------------------------------- | --------------- |
| request | [WebResourceRequest](#webresourcerequest) | Encapsulation of a web page request. | | request | [WebResourceRequest](#webresourcerequest) | Encapsulation of a web page request. |
| error | [WebResourceError](#webresourceerror) | Encapsulation of a web page resource loading error.| | error | [WebResourceError](#webresourceerror) | Encapsulation of a web page resource loading error.|
**Example** **Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
...@@ -836,11 +995,13 @@ onPageBegin(callback: (event?: { url: string }) => void) ...@@ -836,11 +995,13 @@ onPageBegin(callback: (event?: { url: string }) => void)
Triggered when the web page starts to be loaded. This API is triggered only for the main frame content, and not for the iframe or frameset content. Triggered when the web page starts to be loaded. This API is triggered only for the main frame content, and not for the iframe or frameset content.
**Parameters** **Parameters**
| Name | Type | Description | | Name | Type | Description |
| ---- | ------ | --------- | | ---- | ------ | --------- |
| url | string | URL of the page.| | url | string | URL of the page.|
**Example** **Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
...@@ -867,11 +1028,13 @@ onPageEnd(callback: (event?: { url: string }) => void) ...@@ -867,11 +1028,13 @@ onPageEnd(callback: (event?: { url: string }) => void)
Triggered when the web page loading is complete. This API is triggered only for the main frame content. Triggered when the web page loading is complete. This API is triggered only for the main frame content.
**Parameters** **Parameters**
| Name | Type | Description | | Name | Type | Description |
| ---- | ------ | --------- | | ---- | ------ | --------- |
| url | string | URL of the page.| | url | string | URL of the page.|
**Example** **Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
...@@ -897,11 +1060,13 @@ onProgressChange(callback: (event?: { newProgress: number }) => void) ...@@ -897,11 +1060,13 @@ onProgressChange(callback: (event?: { newProgress: number }) => void)
Triggered when the web page loading progress changes. Triggered when the web page loading progress changes.
**Parameters** **Parameters**
| Name | Type | Description | | Name | Type | Description |
| ----------- | ------ | --------------------- | | ----------- | ------ | --------------------- |
| newProgress | number | New loading progress. The value is an integer ranging from 0 to 100.| | newProgress | number | New loading progress. The value is an integer ranging from 0 to 100.|
**Example** **Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
...@@ -927,11 +1092,13 @@ onTitleReceive(callback: (event?: { title: string }) => void) ...@@ -927,11 +1092,13 @@ onTitleReceive(callback: (event?: { title: string }) => void)
Triggered when the document title of the web page is changed. Triggered when the document title of the web page is changed.
**Parameters** **Parameters**
| Name | Type | Description | | Name | Type | Description |
| ----- | ------ | ------------- | | ----- | ------ | ------------- |
| title | string | Document title.| | title | string | Document title.|
**Example** **Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
...@@ -957,12 +1124,14 @@ onRefreshAccessedHistory(callback: (event?: { url: string, isRefreshed: boolean ...@@ -957,12 +1124,14 @@ onRefreshAccessedHistory(callback: (event?: { url: string, isRefreshed: boolean
Triggered when loading of the web page is complete. This API is used by an application to update the historical link it accessed. Triggered when loading of the web page is complete. This API is used by an application to update the historical link it accessed.
**Parameters** **Parameters**
| Name | Type | Description | | Name | Type | Description |
| ----------- | ------- | --------------------------------- | | ----------- | ------- | --------------------------------- |
| url | string | URL to be accessed. | | url | string | URL to be accessed. |
| isRefreshed | boolean | Whether the page is reloaded. The value **true** means that the page is reloaded, and **false** means that the page is newly loaded.| | isRefreshed | boolean | Whether the page is reloaded. The value **true** means that the page is reloaded by invoking the [refresh](#refresh) API, and **false** means the opposite.|
**Example**
**Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
...@@ -974,7 +1143,7 @@ Triggered when loading of the web page is complete. This API is used by an appli ...@@ -974,7 +1143,7 @@ Triggered when loading of the web page is complete. This API is used by an appli
Column() { Column() {
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
.onRefreshAccessedHistory((event) => { .onRefreshAccessedHistory((event) => {
console.log('url:' + event.url + ' isReload:' + event.refreshed); console.log('url:' + event.url + ' isReload:' + event.isRefreshed);
}) })
} }
} }
...@@ -988,11 +1157,13 @@ onRenderExited(callback: (event?: { renderExitReason: RenderExitReason }) => voi ...@@ -988,11 +1157,13 @@ onRenderExited(callback: (event?: { renderExitReason: RenderExitReason }) => voi
Triggered when the rendering process exits abnormally. Triggered when the rendering process exits abnormally.
**Parameters** **Parameters**
| Name | Type | Description | | Name | Type | Description |
| ---------------- | ---------------------------------------- | ---------------- | | ---------------- | ---------------------------------------- | ---------------- |
| renderExitReason | [RenderExitReason](#renderexitreason)| Cause for the abnormal exit of the rendering process.| | renderExitReason | [RenderExitReason](#renderexitreason)| Cause for the abnormal exit of the rendering process.|
**Example** **Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
...@@ -1013,18 +1184,26 @@ Triggered when the rendering process exits abnormally. ...@@ -1013,18 +1184,26 @@ Triggered when the rendering process exits abnormally.
### onShowFileSelector<sup>9+</sup> ### onShowFileSelector<sup>9+</sup>
onShowFileSelector(callback: (event?: { result: FileSelectorResult, fileSelector: FileSelectorParam }) => void) onShowFileSelector(callback: (event?: { result: FileSelectorResult, fileSelector: FileSelectorParam }) => boolean)
Triggered to process an HTML form whose input type is **file**, in response to the tapping of the **Select File** button. Triggered to process an HTML form whose input type is **file**, in response to the tapping of the **Select File** button.
**Parameters** **Parameters**
| Name | Type | Description | | Name | Type | Description |
| ------------ | ---------------------------------------- | ----------------- | | ------------ | ---------------------------------------- | ----------------- |
| result | [FileSelectorResult](#fileselectorresult9) | File selection result to be sent to the **\<Web>** component.| | result | [FileSelectorResult](#fileselectorresult9) | File selection result to be sent to the **\<Web>** component.|
| fileSelector | [FileSelectorParam](#fileselectorparam9) | Information about the file selector. | | fileSelector | [FileSelectorParam](#fileselectorparam9) | Information about the file selector. |
**Example** **Return value**
```ts
| Type | Description |
| ------- | ----------------------------------- |
| boolean | The value **true** means that the pop-up window provided by the system is displayed. The value **true** means that the default web pop-up window is displayed.|
**Example**
```ts
// xxx.ets // xxx.ets
@Entry @Entry
@Component @Component
...@@ -1066,11 +1245,13 @@ onUrlLoadIntercept(callback: (event?: { data:string | WebResourceRequest }) => b ...@@ -1066,11 +1245,13 @@ onUrlLoadIntercept(callback: (event?: { data:string | WebResourceRequest }) => b
Triggered when the **\<Web>** component is about to access a URL. This API is used to determine whether to block the access. Triggered when the **\<Web>** component is about to access a URL. This API is used to determine whether to block the access.
**Parameters** **Parameters**
| Name | Type | Description | | Name | Type | Description |
| ---- | ---------------------------------------- | --------- | | ---- | ---------------------------------------- | --------- |
| data | string / [WebResourceRequest](#webresourcerequest) | URL information.| | data | string / [WebResourceRequest](#webresourcerequest) | URL information.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------- | ------------------------ | | ------- | ------------------------ |
| boolean | Returns **true** if the access is blocked; returns **false** otherwise.| | boolean | Returns **true** if the access is blocked; returns **false** otherwise.|
...@@ -1098,27 +1279,30 @@ Triggered when the **\<Web>** component is about to access a URL. This API is us ...@@ -1098,27 +1279,30 @@ Triggered when the **\<Web>** component is about to access a URL. This API is us
### onInterceptRequest<sup>9+</sup> ### onInterceptRequest<sup>9+</sup>
onInterceptRequest9+(callback: (event?: { request: WebResourceRequest}) => WebResourceResponse) onInterceptRequest(callback: (event?: { request: WebResourceRequest}) => WebResourceResponse)
Triggered when the **\<Web>** component is about to access a URL. This API is used to block the URL and return the response data. Triggered when the **\<Web>** component is about to access a URL. This API is used to block the URL and return the response data.
**Parameters** **Parameters**
| Name | Type | Description | | Name | Type | Description |
| ------- | ---------------------------------------- | ----------- | | ------- | ---------------------------------------- | ----------- |
| request | [WebResourceRequest](#webresourcerequest) | Information about the URL request.| | request | [WebResourceRequest](#webresourcerequest) | Information about the URL request.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| ---------------------------------------- | --------------------------- | | ---------------------------------------- | --------------------------- |
| [WebResourceResponse](#webresourceresponse) | Returns null if the original loading mode is used; returns the response data otherwise.| | [WebResourceResponse](#webresourceresponse) | If response data is returned, the data is loaded based on the response data. If no response data is returned, null is returned, indicating that the data is loaded in the original mode.|
**Example**
**Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller:WebController = new WebController(); controller: WebController = new WebController();
responseweb: WebResourceResponse = new WebResourceResponse(); responseweb: WebResourceResponse = new WebResourceResponse();
heads:Header[] = new Array(); heads:Header[] = new Array();
@State webdata: string = "<!DOCTYPE html>\n" + @State webdata: string = "<!DOCTYPE html>\n" +
...@@ -1132,7 +1316,7 @@ Triggered when the **\<Web>** component is about to access a URL. This API is us ...@@ -1132,7 +1316,7 @@ Triggered when the **\<Web>** component is about to access a URL. This API is us
"</html>" "</html>"
build() { build() {
Column() { Column() {
Web({ src:'www.example.com', controller:this.controller }) Web({ src: 'www.example.com', controller: this.controller })
.onInterceptRequest((event) => { .onInterceptRequest((event) => {
console.log('url:' + event.request.getRequestUrl()); console.log('url:' + event.request.getRequestUrl());
var head1:Header = { var head1:Header = {
...@@ -1165,6 +1349,7 @@ onHttpAuthRequest(callback: (event?: { handler: HttpAuthHandler, host: string, r ...@@ -1165,6 +1349,7 @@ onHttpAuthRequest(callback: (event?: { handler: HttpAuthHandler, host: string, r
Triggered when an HTTP authentication request is received. Triggered when an HTTP authentication request is received.
**Parameters** **Parameters**
| Name | Type | Description | | Name | Type | Description |
| ------- | ------------------------------------ | ---------------- | | ------- | ------------------------------------ | ---------------- |
| handler | [HttpAuthHandler](#httpauthhandler9) | The user's operation. | | handler | [HttpAuthHandler](#httpauthhandler9) | The user's operation. |
...@@ -1172,50 +1357,168 @@ Triggered when an HTTP authentication request is received. ...@@ -1172,50 +1357,168 @@ Triggered when an HTTP authentication request is received.
| realm | string | Realm to which HTTP authentication credentials apply. | | realm | string | Realm to which HTTP authentication credentials apply. |
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------- | --------------------- | | ------- | --------------------- |
| boolean | Returns **true** if the authentication is successful; returns **false** otherwise. | | boolean | Returns **true** if the authentication is successful; returns **false** otherwise.|
**Example** **Example**
```ts ```ts
// xxx.ets // xxx.ets
import web_webview from '@ohos.web.webview'
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller:WebController = new WebController(); controller: WebController = new WebController();
httpAuth:boolean = false; httpAuth: boolean = false;
build() { build() {
Column() { Column() {
Web({ src:'www.example.com', controller:this.controller }) Web({ src: 'www.example.com', controller: this.controller })
.onHttpAuthRequest((event) => { .onHttpAuthRequest((event) => {
AlertDialog.show({ AlertDialog.show({
title: 'title', title: 'onHttpAuthRequest',
message: 'text', message: 'text',
confirm: { primaryButton: {
value: 'onConfirm', value: 'cancel',
action: () => { action: () => {
this.httpAuth = event.handler.isHttpAuthInfoSaved();
if (this.httpAuth == false) {
web.WebDataBase.saveHttpAuthCredentials(
event.host,
event.realm,
"2222",
"2222"
)
event.handler.cancel(); event.handler.cancel();
} }
},
secondaryButton: {
value: 'ok',
action: () => {
this.httpAuth = event.handler.isHttpAuthInfoSaved();
if (this.httpAuth == false) {
web_webview.WebDataBase.saveHttpAuthCredentials(
event.host,
event.realm,
"2222",
"2222"
)
event.handler.cancel();
}
}
},
cancel: () => {
event.handler.cancel();
} }
}, })
cancel: () => { return true;
event.handler.cancel();
}
}) })
return true; }
}) }
}
```
### onSslErrorEventReceive<sup>9+</sup>
onSslErrorEventReceive(callback: (event: { handler: SslErrorHandler, error: SslError }) => void)
Invoked when an SSL error occurs during resource loading.
**Parameters**
| Name | Type | Description |
| ------- | ------------------------------------ | ---------------- |
| handler | [SslErrorHandler](#sslerrorhandler9) | The user's operation.|
| error | [SslError](#sslerror9) | Error code.|
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
build() {
Column() {
Web({ src: 'www.example.com', controller: this.controller })
.onSslErrorEventReceive((event) => {
AlertDialog.show({
title: 'onSslErrorEventReceive',
message: 'text',
primaryButton: {
value: 'confirm',
action: () => {
event.handler.handleConfirm();
}
},
secondaryButton: {
value: 'cancel',
action: () => {
event.handler.handleCancel();
}
},
cancel: () => {
event.handler.handleCancel();
}
})
return true;
})
}
}
}
```
### onClientAuthenticationRequest<sup>9+</sup>
onClientAuthenticationRequest(callback: (event: {handler : ClientAuthenticationHandler, host : string, port : number, keyTypes : Array<string>, issuers : Array<string>}) => void)
Invoked when an SSL client certificate request is received.
**Parameters**
| Name | Type | Description |
| ------- | ------------------------------------ | ---------------- |
| handler | [ClientAuthenticationHandler](#clientauthenticationhandler9) | The user's operation.|
| host | string | Host name of the server that requests a certificate.|
| port | number | Port number of the server that requests a certificate.|
| keyTypes| Array<string> | Acceptable asymmetric private key types.|
| issuers | Array<string> | Issuer of the certificate that matches the private key.|
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
build() {
Column() {
Web({ src: 'www.example.com', controller: this.controller })
.onClientAuthenticationRequest((event) => {
AlertDialog.show({
title: 'onClientAuthenticationRequest',
message: 'text',
primaryButton: {
value: 'confirm',
action: () => {
event.handler.confirm("/system/etc/user.pk8", "/system/etc/chain-user.pem");
}
},
secondaryButton: {
value: 'cancel',
action: () => {
event.handler.cancel();
}
},
cancel: () => {
event.handler.ignore();
}
})
return true;
})
}
} }
} }
``` ```
### onPermissionRequest<sup>9+</sup> ### onPermissionRequest<sup>9+</sup>
onPermissionRequest(callback: (event?: { request: PermissionRequest }) => void) onPermissionRequest(callback: (event?: { request: PermissionRequest }) => void)
...@@ -1223,10 +1526,134 @@ onPermissionRequest(callback: (event?: { request: PermissionRequest }) => void) ...@@ -1223,10 +1526,134 @@ onPermissionRequest(callback: (event?: { request: PermissionRequest }) => void)
Invoked when a permission request is received. Invoked when a permission request is received.
**Parameters** **Parameters**
| Name | Type | Description | | Name | Type | Description |
| ------- | ------------------------------------ | ---------------- | | ------- | ------------------------------------ | ---------------- |
| request | [PermissionRequest](#permissionrequest9) | The user's operation. | | request | [PermissionRequest](#permissionrequest9) | The user's operation. |
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
build() {
Column() {
Web({ src: 'www.example.com', controller: this.controller })
.onPermissionRequest((event) => {
AlertDialog.show({
title: 'title',
message: 'text',
primaryButton: {
value: 'deny',
action: () => {
event.request.deny();
}
},
secondaryButton: {
value: 'onConfirm',
action: () => {
event.request.grant(event.request.getAccessibleResource());
}
},
cancel: () => {
event.request.deny();
}
})
})
}
}
}
```
### onContextMenuShow<sup>9+</sup>
onContextMenuShow(callback: (event?: { param: WebContextMenuParam, result: WebContextMenuResult }) => boolean)
Invoked when a context menu is displayed upon a long press on a specific element (such as an image or link).
**Parameters**
| Name | Type | Description |
| ------- | ------------------------------------ | ---------------- |
| param | [WebContextMenuParam](#webcontextmenuparam9) | Parameters related to the context menu.|
| result | [WebContextMenuResult](#webcontextmenuresult9) | Result of the context menu.|
**Return value**
| Type | Description |
| ------ | -------------------- |
| boolean | The value **true** means a custom menu, and **false** means the default menu.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
build() {
Column() {
Web({ src: 'www.example.com', controller: this.controller })
.onContextMenuShow((event) => {
console.info("x coord = " + event.param.x());
console.info("link url = " + event.param.getLinkUrl());
return true;
})
}
}
}
```
### onScroll<sup>9+</sup>
onScroll(callback: (event: {xOffset: number, yOffset: number}) => void)
Invoked when the scrollbar of the page scrolls.
**Parameters**
| Name | Type | Description |
| ------- | ------------------------------------ | ---------------- |
| xOffset | number | Position of the scrollbar on the x-axis.|
| yOffset | number | Position of the scrollbar on the y-axis.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
build() {
Column() {
Web({ src: 'www.example.com', controller: this.controller })
.onScroll((event) => {
console.info("x = " + event.xOffset);
console.info("y = " + event.yOffset);
})
}
}
}
```
### onGeolocationShow
onGeolocationShow(callback: (event?: { origin: string, geolocation: JsGeolocation }) => void)
Invoked when a request to obtain the geolocation information is received.
**Parameters**
| Name | Type | Description |
| ----------- | ------------------------------- | ---------------- |
| origin | string | Index of the origin. |
| geolocation | [JsGeolocation](#jsgeolocation) | The user's operation.|
**Example** **Example**
```ts ```ts
...@@ -1238,21 +1665,23 @@ Invoked when a permission request is received. ...@@ -1238,21 +1665,23 @@ Invoked when a permission request is received.
build() { build() {
Column() { Column() {
Web({ src:'www.example.com', controller:this.controller }) Web({ src:'www.example.com', controller:this.controller })
.onPermissionRequest((event) => { .geolocationAccess(true)
.onGeolocationShow((event) => {
AlertDialog.show({ AlertDialog.show({
title: 'title', title: 'title',
message: 'text', message: 'text',
confirm: { confirm: {
value: 'onConfirm', value: 'onConfirm',
action: () => { action: () => {
event.request.grant(event.request.getAccessibleResource()); event.geolocation.invoke(event.origin, true, true);
} }
}, },
cancel: () => { cancel: () => {
event.request.deny(); event.geolocation.invoke(event.origin, false, true);
} }
}) })
}) })
}
} }
} }
``` ```
...@@ -1268,6 +1697,7 @@ getLineNumber(): number ...@@ -1268,6 +1697,7 @@ getLineNumber(): number
Obtains the number of rows in this console message. Obtains the number of rows in this console message.
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------ | -------------------- | | ------ | -------------------- |
| number | Number of rows in the console message.| | number | Number of rows in the console message.|
...@@ -1279,9 +1709,10 @@ getMessage(): string ...@@ -1279,9 +1709,10 @@ getMessage(): string
Obtains the log information of this console message. Obtains the log information of this console message.
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------ | ---------------------- | | ------ | ---------------------- |
| string | Log information about this console message.| | string | Log information of this console message.|
### getMessageLevel ### getMessageLevel
...@@ -1290,6 +1721,7 @@ getMessageLevel(): MessageLevel ...@@ -1290,6 +1721,7 @@ getMessageLevel(): MessageLevel
Obtains the level of this console message. Obtains the level of this console message.
**Return value** **Return value**
| Type | Description | | Type | Description |
| --------------------------------- | ---------------------- | | --------------------------------- | ---------------------- |
| [MessageLevel](#messagelevel)| Level of the console message.| | [MessageLevel](#messagelevel)| Level of the console message.|
...@@ -1301,6 +1733,7 @@ getSourceId(): string ...@@ -1301,6 +1733,7 @@ getSourceId(): string
Obtains the path and name of the web page source file. Obtains the path and name of the web page source file.
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------ | ------------- | | ------ | ------------- |
| string | Path and name of the web page source file.| | string | Path and name of the web page source file.|
...@@ -1328,6 +1761,7 @@ handlePromptConfirm(result: string): void ...@@ -1328,6 +1761,7 @@ handlePromptConfirm(result: string): void
Notifies the **\<Web>** component of the user's confirm operation in the dialog box as well as the dialog box content. Notifies the **\<Web>** component of the user's confirm operation in the dialog box as well as the dialog box content.
**Parameters** **Parameters**
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| ------ | ------ | ---- | ---- | ----------- | | ------ | ------ | ---- | ---- | ----------- |
| result | string | Yes | - | User input in the dialog box.| | result | string | Yes | - | User input in the dialog box.|
...@@ -1343,6 +1777,7 @@ getErrorCode(): number ...@@ -1343,6 +1777,7 @@ getErrorCode(): number
Obtains the error code for resource loading. Obtains the error code for resource loading.
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------ | ----------- | | ------ | ----------- |
| number | Error code for resource loading.| | number | Error code for resource loading.|
...@@ -1354,6 +1789,7 @@ getErrorInfo(): string ...@@ -1354,6 +1789,7 @@ getErrorInfo(): string
Obtains error information about resource loading. Obtains error information about resource loading.
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------ | ------------ | | ------ | ------------ |
| string | Error information about resource loading.| | string | Error information about resource loading.|
...@@ -1369,6 +1805,7 @@ getResponseHeader() : Array\<Header\> ...@@ -1369,6 +1805,7 @@ getResponseHeader() : Array\<Header\>
Obtains the information about the resource request header. Obtains the information about the resource request header.
**Return value** **Return value**
| Type | Description | | Type | Description |
| -------------------------- | ---------- | | -------------------------- | ---------- |
| Array\<[Header](#header)\> | Information about the resource request header.| | Array\<[Header](#header)\> | Information about the resource request header.|
...@@ -1380,6 +1817,7 @@ getRequestUrl(): string ...@@ -1380,6 +1817,7 @@ getRequestUrl(): string
Obtains the URL of the resource request. Obtains the URL of the resource request.
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------ | ------------- | | ------ | ------------- |
| string | URL of the resource request.| | string | URL of the resource request.|
...@@ -1391,6 +1829,7 @@ isMainFrame(): boolean ...@@ -1391,6 +1829,7 @@ isMainFrame(): boolean
Checks whether the resource request is in the main frame. Checks whether the resource request is in the main frame.
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------- | ---------------- | | ------- | ---------------- |
| boolean | Whether the resource request is in the main frame.| | boolean | Whether the resource request is in the main frame.|
...@@ -1402,9 +1841,10 @@ isRedirect(): boolean ...@@ -1402,9 +1841,10 @@ isRedirect(): boolean
Checks whether the resource request is redirected by the server. Checks whether the resource request is redirected by the server.
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------- | ---------------- | | ------- | ---------------- |
| boolean | Whether the resource request is redirected by the server. | | boolean | Whether the resource request is redirected by the server.|
### isRequestGesture ### isRequestGesture
...@@ -1413,9 +1853,10 @@ isRequestGesture(): boolean ...@@ -1413,9 +1853,10 @@ isRequestGesture(): boolean
Checks whether the resource request is associated with a gesture (for example, a tap). Checks whether the resource request is associated with a gesture (for example, a tap).
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------- | -------------------- | | ------- | -------------------- |
| boolean | Whether the resource request is associated with a gesture (for example, a tap). | | boolean | Whether the resource request is associated with a gesture (for example, a tap).|
## Header ## Header
...@@ -1438,6 +1879,7 @@ getReasonMessage(): string ...@@ -1438,6 +1879,7 @@ getReasonMessage(): string
Obtains the status code description of the resource response. Obtains the status code description of the resource response.
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------ | ------------- | | ------ | ------------- |
| string | Status code description of the resource response.| | string | Status code description of the resource response.|
...@@ -1449,6 +1891,7 @@ getResponseCode(): number ...@@ -1449,6 +1891,7 @@ getResponseCode(): number
Obtains the status code of the resource response. Obtains the status code of the resource response.
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------ | ----------- | | ------ | ----------- |
| number | Status code of the resource response.| | number | Status code of the resource response.|
...@@ -1460,6 +1903,7 @@ getResponseData(): string ...@@ -1460,6 +1903,7 @@ getResponseData(): string
Obtains the data in the resource response. Obtains the data in the resource response.
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------ | --------- | | ------ | --------- |
| string | Data in the resource response.| | string | Data in the resource response.|
...@@ -1471,6 +1915,7 @@ getResponseEncoding(): string ...@@ -1471,6 +1915,7 @@ getResponseEncoding(): string
Obtains the encoding string of the resource response. Obtains the encoding string of the resource response.
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------ | ---------- | | ------ | ---------- |
| string | Encoding string of the resource response.| | string | Encoding string of the resource response.|
...@@ -1482,6 +1927,7 @@ getResponseHeader() : Array\<Header\> ...@@ -1482,6 +1927,7 @@ getResponseHeader() : Array\<Header\>
Obtains the resource response header. Obtains the resource response header.
**Return value** **Return value**
| Type | Description | | Type | Description |
| -------------------------- | -------- | | -------------------------- | -------- |
| Array\<[Header](#header)\> | Resource response header.| | Array\<[Header](#header)\> | Resource response header.|
...@@ -1493,6 +1939,7 @@ getResponseMimeType(): string ...@@ -1493,6 +1939,7 @@ getResponseMimeType(): string
Obtains the MIME type of the resource response. Obtains the MIME type of the resource response.
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------ | ------------------ | | ------ | ------------------ |
| string | MIME type of the resource response.| | string | MIME type of the resource response.|
...@@ -1504,6 +1951,7 @@ setResponseData(data: string) ...@@ -1504,6 +1951,7 @@ setResponseData(data: string)
Sets the data in the resource response. Sets the data in the resource response.
**Parameters** **Parameters**
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| ---- | ------ | ---- | ---- | ----------- | | ---- | ------ | ---- | ---- | ----------- |
| data | string | Yes | - | Resource response data to set.| | data | string | Yes | - | Resource response data to set.|
...@@ -1515,6 +1963,7 @@ setResponseEncoding(encoding: string) ...@@ -1515,6 +1963,7 @@ setResponseEncoding(encoding: string)
Sets the encoding string of the resource response. Sets the encoding string of the resource response.
**Parameters** **Parameters**
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| -------- | ------ | ---- | ---- | ------------ | | -------- | ------ | ---- | ---- | ------------ |
| encoding | string | Yes | - | Encoding string to set.| | encoding | string | Yes | - | Encoding string to set.|
...@@ -1526,6 +1975,7 @@ setResponseMimeType(mimeType: string) ...@@ -1526,6 +1975,7 @@ setResponseMimeType(mimeType: string)
Sets the MIME type of the resource response. Sets the MIME type of the resource response.
**Parameters** **Parameters**
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| -------- | ------ | ---- | ---- | -------------------- | | -------- | ------ | ---- | ---- | -------------------- |
| mimeType | string | Yes | - | MIME type to set.| | mimeType | string | Yes | - | MIME type to set.|
...@@ -1537,6 +1987,7 @@ setReasonMessage(reason: string) ...@@ -1537,6 +1987,7 @@ setReasonMessage(reason: string)
Sets the status code description of the resource response. Sets the status code description of the resource response.
**Parameters** **Parameters**
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| ------ | ------ | ---- | ---- | --------------- | | ------ | ------ | ---- | ---- | --------------- |
| reason | string | Yes | - | Status code description to set.| | reason | string | Yes | - | Status code description to set.|
...@@ -1548,6 +1999,7 @@ setResponseHeader(header: Array\<Header\>) ...@@ -1548,6 +1999,7 @@ setResponseHeader(header: Array\<Header\>)
Sets the resource response header. Sets the resource response header.
**Parameters** **Parameters**
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| ------ | -------------------------- | ---- | ---- | ---------- | | ------ | -------------------------- | ---- | ---- | ---------- |
| header | Array\<[Header](#header)\> | Yes | - | Resource response header to set.| | header | Array\<[Header](#header)\> | Yes | - | Resource response header to set.|
...@@ -1559,6 +2011,7 @@ setResponseCode(code: number) ...@@ -1559,6 +2011,7 @@ setResponseCode(code: number)
Sets the status code of the resource response. Sets the status code of the resource response.
**Parameters** **Parameters**
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| ---- | ------ | ---- | ---- | ------------- | | ---- | ------ | ---- | ---- | ------------- |
| code | number | Yes | - | Status code to set.| | code | number | Yes | - | Status code to set.|
...@@ -1574,6 +2027,7 @@ handleFileList(fileList: Array\<string\>): void ...@@ -1574,6 +2027,7 @@ handleFileList(fileList: Array\<string\>): void
Instructs the **\<Web>** component to select a file. Instructs the **\<Web>** component to select a file.
**Parameters** **Parameters**
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| -------- | --------------- | ---- | ---- | ------------ | | -------- | --------------- | ---- | ---- | ------------ |
| fileList | Array\<string\> | Yes | - | List of files to operate.| | fileList | Array\<string\> | Yes | - | List of files to operate.|
...@@ -1589,6 +2043,7 @@ getTitle(): string ...@@ -1589,6 +2043,7 @@ getTitle(): string
Obtains the title of the file selector. Obtains the title of the file selector.
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------ | ---------- | | ------ | ---------- |
| string | Title of the file selector.| | string | Title of the file selector.|
...@@ -1600,6 +2055,7 @@ getMode(): FileSelectorMode ...@@ -1600,6 +2055,7 @@ getMode(): FileSelectorMode
Obtains the mode of the file selector. Obtains the mode of the file selector.
**Return value** **Return value**
| Type | Description | | Type | Description |
| ---------------------------------------- | ----------- | | ---------------------------------------- | ----------- |
| [FileSelectorMode](#fileselectormode)| Mode of the file selector.| | [FileSelectorMode](#fileselectormode)| Mode of the file selector.|
...@@ -1611,6 +2067,7 @@ getAcceptType(): Array\<string\> ...@@ -1611,6 +2067,7 @@ getAcceptType(): Array\<string\>
Obtains the file filtering type. Obtains the file filtering type.
**Return value** **Return value**
| Type | Description | | Type | Description |
| --------------- | --------- | | --------------- | --------- |
| Array\<string\> | File filtering type.| | Array\<string\> | File filtering type.|
...@@ -1622,6 +2079,7 @@ isCapture(): boolean ...@@ -1622,6 +2079,7 @@ isCapture(): boolean
Checks whether multimedia capabilities are invoked. Checks whether multimedia capabilities are invoked.
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------- | ------------ | | ------- | ------------ |
| boolean | Whether multimedia capabilities are invoked.| | boolean | Whether multimedia capabilities are invoked.|
...@@ -1650,6 +2108,7 @@ Performs HTTP authentication with the user name and password provided by the use ...@@ -1650,6 +2108,7 @@ Performs HTTP authentication with the user name and password provided by the use
| pwd | string | Yes | - | HTTP authentication password. | | pwd | string | Yes | - | HTTP authentication password. |
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------- | --------------------- | | ------- | --------------------- |
| boolean | Returns **true** if the authentication is successful; returns **false** otherwise.| | boolean | Returns **true** if the authentication is successful; returns **false** otherwise.|
...@@ -1661,25 +2120,71 @@ isHttpAuthInfoSaved(): boolean ...@@ -1661,25 +2120,71 @@ isHttpAuthInfoSaved(): boolean
Uses the password cached on the server for authentication. Uses the password cached on the server for authentication.
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------- | ------------------------- | | ------- | ------------------------- |
| boolean | Returns **true** if the authentication is successful; returns **false** otherwise.| | boolean | Returns **true** if the authentication is successful; returns **false** otherwise.|
## PermissionRequest<sup>9+</sup> ## SslErrorHandler<sup>9+</sup>
Implements the **PermissionRequest** object. For details about the sample code, see [onPermissionRequest](#onpermissionrequest9). Implements an **SslErrorHandler** object. For details about the sample code, see [onSslErrorEventReceive Event](#onsslerroreventreceive9).
### deny<sup>9+</sup> ### handleCancel<sup>9+</sup>
deny(): void handleCancel(): void
Denies the permission requested by the web page. Instructs the web component to cancel the request.
### getOrigin<sup>9+</sup> ### handleConfirm<sup>9+</sup>
getOrigin(): string handleConfirm(): void
Obtains the origin of this web page. Instructs the web component to continue using the SSL certificate.
## ClientAuthenticationHandler<sup>9+</sup>
Defines a **ClientAuthenticationHandler** object returned by the web component. For details about the sample code, see [onClientAuthenticationRequest](#onclientauthenticationrequest9).
### confirm<sup>9+</sup>
confirm(priKeyFile : string, certChainFile : string): void
Instructs the web component to use the specified private key and client certificate chain.
**Parameters**
| Name | Type| Mandatory | Description |
| -------- | ------ | ---- | ---------- |
| priKeyFile | string | Yes | File that stores the private key, including the directory and file name.|
| certChainFile | string | Yes | File that stores the certificate chain, including the directory and file name.|
### cancel<sup>9+</sup>
cancel(): void
Instructs the web component to cancel the client certificate request sent by the same host and port server. No additional event will be reported for requests from the same host and port server.
### ignore<sup>9+</sup>
ignore(): void
Instructs the web component to ignore this request.
## PermissionRequest<sup>9+</sup>
Implements the **PermissionRequest** object. For details about the sample code, see [onPermissionRequest](#onpermissionrequest9).
### deny<sup>9+</sup>
deny(): void
Denies the permission requested by the web page.
### getOrigin<sup>9+</sup>
getOrigin(): string
Obtains the origin of this web page.
**Return value** **Return value**
...@@ -1711,6 +2216,116 @@ Grants the permission for resources requested by the web page. ...@@ -1711,6 +2216,116 @@ Grants the permission for resources requested by the web page.
| --------- | --------------- | ---- | ----- | ---------------------- | | --------- | --------------- | ---- | ----- | ---------------------- |
| resources | Array\<string\> | Yes | - | List of accessible resources requested by the web page.| | resources | Array\<string\> | Yes | - | List of accessible resources requested by the web page.|
## WebContextMenuParam<sup>9+</sup>
Provides the information about the context menu that is displayed when a page element is long pressed. For details about the sample code, see [onContextMenuShow](#oncontextmenushow9).
### x<sup>9+</sup>
x(): number
X coordinate of the context menu.
**Return value**
| Type | Description |
| --------------- | ----------------------- |
| number | If the display is normal, a non-negative integer is returned. Otherwise, **-1** is returned.|
### y<sup>9+</sup>
y(): number
Y coordinate of the context menu.
**Return value**
| Type | Description |
| --------------- | ----------------------- |
| number | If the display is normal, a non-negative integer is returned. Otherwise, **-1** is returned.|
### getLinkUrl<sup>9+</sup>
getLinkUrl(): string
Obtains the URL of the destination link.
**Return value**
| Type | Description |
| --------------- | ----------------------- |
| string | If it is the link that is being long pressed, the URL that has passed the security check is returned.|
### getUnfilterendLinkUrl<sup>9+</sup>
getUnfilterendLinkUrl(): string
Obtains the URL of the destination link.
**Return value**
| Type | Description |
| --------------- | ----------------------- |
| string | If it is the link that is being long pressed, the original URL is returned.|
### getSourceUrl<sup>9+</sup>
getSourceUrl(): string
Obtain the source URL.
**Return value**
| Type | Description |
| --------------- | ----------------------- |
| string | If the selected element has the **src** attribute, the URL in the **src** is returned.|
### existsImageContents<sup>9+</sup>
existsImageContents(): boolean
Checks whether image content exists.
**Return value**
| Type | Description |
| --------------- | ----------------------- |
| boolean | The value **true** means that there is image content in the element being long pressed, and **false** means the opposite.|
## WebContextMenuResult<sup>9+</sup>
Defines the response event executed when a context menu is displayed. For details about the sample code, see [onContextMenuShow](#oncontextmenushow9).
### closeContextMenu<sup>9+</sup>
closeContextMenu(): void
Closes this context menu. This API must be called when no operations in **WebContextMenuResult** are performed.
### copyImage<sup>9+</sup>
copyImage(): void
Copies the image specified in **WebContextMenuParam**.
## JsGeolocation
Implements the **PermissionRequest** object. For details about the sample code, see [onGeolocationShow Event](#ongeolocationshow).
### invoke
invoke(origin: string, allow: boolean, retain: boolean): void
Sets the geolocation permission status of a web page.
**Parameters**
| Name | Type| Mandatory| Default Value| Description |
| --------- | ------- | ---- | ----- | ---------------------- |
| origin | string | Yes | - | Index of the source. |
| allow | boolean | Yes | - | Geolocation permission status.|
| retain | boolean | Yes | - | Whether the geolocation permission status can be saved to the system. The **[GeolocationPermissions](#geolocationpermissions9)** API can be used to manage the geolocation permission status saved to the system.|
## WebController ## WebController
Defines a **WebController** to control the behavior of the **\<Web>** component. A **WebController** can control only one **\<Web>** component, and the APIs in the **WebController** can be invoked only after it has been bound to the target **\<Web>** component. Defines a **WebController** to control the behavior of the **\<Web>** component. A **WebController** can control only one **\<Web>** component, and the APIs in the **WebController** can be invoked only after it has been bound to the target **\<Web>** component.
...@@ -1728,6 +2343,7 @@ requestFocus() ...@@ -1728,6 +2343,7 @@ requestFocus()
Requests focus for this web page. Requests focus for this web page.
**Example** **Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
...@@ -1754,11 +2370,13 @@ accessBackward(): boolean ...@@ -1754,11 +2370,13 @@ accessBackward(): boolean
Checks whether going to the previous page can be performed on the current page. Checks whether going to the previous page can be performed on the current page.
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------- | --------------------- | | ------- | --------------------- |
| boolean | Returns **true** if going to the previous page can be performed on the current page; returns **false** otherwise.| | boolean | Returns **true** if going to the previous page can be performed on the current page; returns **false** otherwise.|
**Example** **Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
...@@ -1786,11 +2404,13 @@ accessForward(): boolean ...@@ -1786,11 +2404,13 @@ accessForward(): boolean
Checks whether going to the next page can be performed on the current page. Checks whether going to the next page can be performed on the current page.
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------- | --------------------- | | ------- | --------------------- |
| boolean | Returns **true** if going to the next page can be performed on the current page; returns **false** otherwise.| | boolean | Returns **true** if going to the next page can be performed on the current page; returns **false** otherwise.|
**Example** **Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
...@@ -1824,11 +2444,13 @@ Indicates whether a specific number of steps forward or backward can be performe ...@@ -1824,11 +2444,13 @@ Indicates whether a specific number of steps forward or backward can be performe
| step | number | Yes | - | Number of the steps to take. A positive number means to going forward, and a negative number means to going backward.| | step | number | Yes | - | Number of the steps to take. A positive number means to going forward, and a negative number means to going backward.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------- | --------- | | ------- | --------- |
| boolean | Whether to go forward or backward from the current page.| | boolean | Whether to go forward or backward from the current page.|
**Example** **Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
...@@ -1857,6 +2479,7 @@ backward(): void ...@@ -1857,6 +2479,7 @@ backward(): void
Goes to the previous page based on the history stack. This API is generally used together with **accessBackward**. Goes to the previous page based on the history stack. This API is generally used together with **accessBackward**.
**Example** **Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
...@@ -1883,6 +2506,7 @@ forward(): void ...@@ -1883,6 +2506,7 @@ forward(): void
Goes to the next page based on the history stack. This API is generally used together with **accessForward**. Goes to the next page based on the history stack. This API is generally used together with **accessForward**.
**Example** **Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
...@@ -1909,24 +2533,29 @@ backOrForward(step: number): void ...@@ -1909,24 +2533,29 @@ backOrForward(step: number): void
Performs a specific number of steps forward or backward on the current page based on the history stack. No redirection will be performed if the corresponding page does not exist in the history stack. Performs a specific number of steps forward or backward on the current page based on the history stack. No redirection will be performed if the corresponding page does not exist in the history stack.
**Parameters** **Parameters**
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| ---- | ------ | ---- | ---- | ----------- | | ---- | ------ | ---- | ---- | ----------- |
| step | number | Yes | - | Number of the steps to take.| | step | number | Yes | - | Number of the steps to take.|
**Example** **Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller:WebController = new WebController(); controller: WebController = new WebController();
@State step: number = -2;
build() { build() {
Column() { Column() {
Button('backOrForward') Button('backOrForward')
.onClick(() => { .onClick(() => {
this.controller.backOrForward(); this.controller.backOrForward(this.step);
}) })
Web({ src:'www.example.com', controller:this.controller }) Web({ src: 'www.example.com', controller: this.controller })
}
} }
} }
``` ```
...@@ -1938,11 +2567,13 @@ deleteJavaScriptRegister(name: string) ...@@ -1938,11 +2567,13 @@ deleteJavaScriptRegister(name: string)
Deletes a specific application JavaScript object that is registered with the window through **registerJavaScriptProxy**. The deletion takes effect immediately, with no need for invoking the [refresh](#refresh) API. Deletes a specific application JavaScript object that is registered with the window through **registerJavaScriptProxy**. The deletion takes effect immediately, with no need for invoking the [refresh](#refresh) API.
**Parameters** **Parameters**
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| ---- | ------ | ---- | ---- | ---------------------------------------- | | ---- | ------ | ---- | ---- | ---------------------------------------- |
| name | string | Yes | - | Name of the registered JavaScript object, which can be used to invoke the corresponding object on the application side from the web side.| | name | string | Yes | - | Name of the registered JavaScript object, which can be used to invoke the corresponding object on the application side from the web side.|
**Example** **Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
...@@ -1970,11 +2601,13 @@ getHitTest(): HitTestType ...@@ -1970,11 +2601,13 @@ getHitTest(): HitTestType
Obtains the element type of the area being clicked. Obtains the element type of the area being clicked.
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------------------------------- | ----------- | | ------------------------------- | ----------- |
| [HitTestType](#hittesttype)| Element type of the area being clicked.| | [HitTestType](#hittesttype)| Element type of the area being clicked.|
**Example** **Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
...@@ -2001,11 +2634,13 @@ getHitTestValue(): HitTestValue ...@@ -2001,11 +2634,13 @@ getHitTestValue(): HitTestValue
Obtains the element information of the area being clicked. Obtains the element information of the area being clicked.
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------------------------------ | ---------- | | ------------------------------ | ---------- |
| [HitTestValue](#hittestvalue9) | Element information of the area being clicked.| | [HitTestValue](#hittestvalue9) | Element information of the area being clicked.|
**Example** **Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
...@@ -2033,11 +2668,13 @@ getWebId(): number ...@@ -2033,11 +2668,13 @@ getWebId(): number
Obtains the index value of this **\<Web>** component, which can be used for **\<Web>** component management. Obtains the index value of this **\<Web>** component, which can be used for **\<Web>** component management.
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------ | ------------ | | ------ | ------------ |
| number | Index value of the current **\<Web>** component.| | number | Index value of the current **\<Web>** component.|
**Example** **Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
...@@ -2064,11 +2701,13 @@ getTitle(): string ...@@ -2064,11 +2701,13 @@ getTitle(): string
Obtains the title of the current web page. Obtains the title of the current web page.
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------ | -------- | | ------ | -------- |
| string | Title of the current web page.| | string | Title of the current web page.|
**Example** **Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
...@@ -2095,11 +2734,13 @@ getPageHeight(): number ...@@ -2095,11 +2734,13 @@ getPageHeight(): number
Obtains the height of the current web page. Obtains the height of the current web page.
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------ | ---------- | | ------ | ---------- |
| number | Height of the current web page.| | number | Height of the current web page.|
**Example** **Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
...@@ -2126,11 +2767,13 @@ getDefaultUserAgent(): string ...@@ -2126,11 +2767,13 @@ getDefaultUserAgent(): string
Obtains the default user agent of the current web page. Obtains the default user agent of the current web page.
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------ | ------- | | ------ | ------- |
| string | Default user agent.| | string | Default user agent.|
**Example** **Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
...@@ -2162,6 +2805,7 @@ If **baseUrl** is set to a data URL, the encoded string will be loaded by the ** ...@@ -2162,6 +2805,7 @@ If **baseUrl** is set to a data URL, the encoded string will be loaded by the **
If **baseUrl** is set to an HTTP or HTTPS URL, the encoded string will be processed by the **\<Web>** component as a non-encoded string in a manner similar to **loadUrl**. If **baseUrl** is set to an HTTP or HTTPS URL, the encoded string will be processed by the **\<Web>** component as a non-encoded string in a manner similar to **loadUrl**.
**Parameters** **Parameters**
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| ---------- | ------ | ---- | ---- | ---------------------------------------- | | ---------- | ------ | ---- | ---- | ---------------------------------------- |
| data | string | Yes | - | Character string obtained after being Base64 or URL encoded. | | data | string | Yes | - | Character string obtained after being Base64 or URL encoded. |
...@@ -2171,6 +2815,7 @@ If **baseUrl** is set to an HTTP or HTTPS URL, the encoded string will be proces ...@@ -2171,6 +2815,7 @@ If **baseUrl** is set to an HTTP or HTTPS URL, the encoded string will be proces
| historyUrl | string | No | - | Historical record URL. If this parameter is not empty, it can be managed in historical records to implement page going backward and forward. This parameter is invalid when **baseUrl** is left empty.| | historyUrl | string | No | - | Historical record URL. If this parameter is not empty, it can be managed in historical records to implement page going backward and forward. This parameter is invalid when **baseUrl** is left empty.|
**Example** **Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
...@@ -2205,12 +2850,14 @@ The object injected through **loadUrl** is valid only in the current document. I ...@@ -2205,12 +2850,14 @@ The object injected through **loadUrl** is valid only in the current document. I
The object injected through **registerJavaScriptProxy** is still valid on a new page redirected through **loadUrl**. The object injected through **registerJavaScriptProxy** is still valid on a new page redirected through **loadUrl**.
**Parameters** **Parameters**
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| ------- | -------------------------- | ---- | ---- | -------------- | | ------- | -------------------------- | ---- | ---- | -------------- |
| url | string | Yes | - | URL to load. | | url | string | Yes | - | URL to load. |
| headers | Array\<[Header](#header)\> | No | [] | Additional HTTP request header of the URL.| | headers | Array\<[Header](#header)\> | No | [] | Additional HTTP request header of the URL.|
**Example** **Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
...@@ -2237,6 +2884,7 @@ onActive(): void ...@@ -2237,6 +2884,7 @@ onActive(): void
Invoked to instruct the **\<Web>** component to enter the foreground, active state. Invoked to instruct the **\<Web>** component to enter the foreground, active state.
**Example** **Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
...@@ -2263,6 +2911,7 @@ onInactive(): void ...@@ -2263,6 +2911,7 @@ onInactive(): void
Invoked to instruct the **\<Web>** component to enter the inactive state. Invoked to instruct the **\<Web>** component to enter the inactive state.
**Example** **Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
...@@ -2288,11 +2937,13 @@ zoom(factor: number): void ...@@ -2288,11 +2937,13 @@ zoom(factor: number): void
Sets a zoom factor for the current web page. Sets a zoom factor for the current web page.
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ------ | ------ | ---- | ------------------------------ | | ------ | ------ | ---- | ------------------------------ |
| factor | number | Yes | Zoom factor to set. A positive value indicates zoom-in, and a negative value indicates zoom-out.| | factor | number | Yes | Zoom factor to set. A positive value indicates zoom-in, and a negative value indicates zoom-out.|
**Example** **Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
...@@ -2319,11 +2970,13 @@ zoomIn(): boolean ...@@ -2319,11 +2970,13 @@ zoomIn(): boolean
Zooms in on the current web page by 20%. Zooms in on the current web page by 20%.
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------- | ----------- | | ------- | ----------- |
| boolean | Operation result.| | boolean | Operation result.|
**Example** **Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
...@@ -2350,11 +3003,13 @@ zoomOut(): boolean ...@@ -2350,11 +3003,13 @@ zoomOut(): boolean
Zooms out the current web page by 20%. Zooms out the current web page by 20%.
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------- | ----------- | | ------- | ----------- |
| boolean | Operation result.| | boolean | Operation result.|
**Example** **Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
...@@ -2382,6 +3037,7 @@ refresh() ...@@ -2382,6 +3037,7 @@ refresh()
Invoked to instruct the **\<Web>** component to refresh the web page. Invoked to instruct the **\<Web>** component to refresh the web page.
**Example** **Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
...@@ -2408,6 +3064,7 @@ registerJavaScriptProxy(options: { object: object, name: string, methodList: Arr ...@@ -2408,6 +3064,7 @@ registerJavaScriptProxy(options: { object: object, name: string, methodList: Arr
Registers a JavaScript object and invokes the methods of the object in the window. You must invoke the [refresh](#refresh) API for the registration to take effect. Registers a JavaScript object and invokes the methods of the object in the window. You must invoke the [refresh](#refresh) API for the registration to take effect.
**Parameters** **Parameters**
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| ---------- | --------------- | ---- | ---- | ---------------------------------------- | | ---------- | --------------- | ---- | ---- | ---------------------------------------- |
| object | object | Yes | - | Application-side JavaScript object to be registered. Methods can be declared, but not attributes. The parameters and return value can only be of the string, number, or Boolean type.| | object | object | Yes | - | Application-side JavaScript object to be registered. Methods can be declared, but not attributes. The parameters and return value can only be of the string, number, or Boolean type.|
...@@ -2415,6 +3072,7 @@ Registers a JavaScript object and invokes the methods of the object in the windo ...@@ -2415,6 +3072,7 @@ Registers a JavaScript object and invokes the methods of the object in the windo
| methodList | Array\<string\> | Yes | - | Methods of the JavaScript object to be registered at the application side. | | methodList | Array\<string\> | Yes | - | Methods of the JavaScript object to be registered at the application side. |
**Example** **Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
...@@ -2472,12 +3130,14 @@ runJavaScript(options: { script: string, callback?: (result: string) => void }) ...@@ -2472,12 +3130,14 @@ runJavaScript(options: { script: string, callback?: (result: string) => void })
Asynchronously executes a JavaScript script. This API uses a callback to return the script execution result. **runJavaScript** can be invoked only after **loadUrl** is executed. For example, it can be executed in **onPageEnd**. Asynchronously executes a JavaScript script. This API uses a callback to return the script execution result. **runJavaScript** can be invoked only after **loadUrl** is executed. For example, it can be executed in **onPageEnd**.
**Parameters** **Parameters**
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| -------- | ------------------------ | ---- | ---- | ---------------------------------------- | | -------- | ------------------------ | ---- | ---- | ---------------------------------------- |
| script | string | Yes | - | JavaScript script. | | script | string | Yes | - | JavaScript script. |
| callback | (result: string) => void | No | - | Callback used to return the result. Returns **null** if the JavaScript script fails to be executed or no value is returned.| | callback | (result: string) => void | No | - | Callback used to return the result. Returns **null** if the JavaScript script fails to be executed or no value is returned.|
**Example** **Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
...@@ -2529,6 +3189,7 @@ stop() ...@@ -2529,6 +3189,7 @@ stop()
Stops page loading. Stops page loading.
**Example** **Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
...@@ -2555,6 +3216,7 @@ clearHistory(): void ...@@ -2555,6 +3216,7 @@ clearHistory(): void
Clears the browsing history. Clears the browsing history.
**Example** **Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
...@@ -2574,6 +3236,60 @@ Clears the browsing history. ...@@ -2574,6 +3236,60 @@ Clears the browsing history.
} }
``` ```
### clearSslCache
clearSslCache(): void
Clears user operation corresponding to the SSL certificate error event recorded by the web component.
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
build() {
Column() {
Button('clearSslCache')
.onClick(() => {
this.controller.clearSslCache();
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### clearClientAuthenticationCache
clearClientAuthenticationCache(): void
Clears the user operation corresponding to the client certificate request event recorded by the web component.
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
build() {
Column() {
Button('clearClientAuthenticationCache')
.onClick(() => {
this.controller.clearClientAuthenticationCache();
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### getCookieManager<sup>9+</sup> ### getCookieManager<sup>9+</sup>
getCookieManager(): WebCookie getCookieManager(): WebCookie
...@@ -2581,11 +3297,13 @@ getCookieManager(): WebCookie ...@@ -2581,11 +3297,13 @@ getCookieManager(): WebCookie
Obtains the cookie management object of the **\<Web>** component. Obtains the cookie management object of the **\<Web>** component.
**Return value** **Return value**
| Type | Description | | Type | Description |
| --------- | ---------------------------------------- | | --------- | ---------------------------------------- |
| WebCookie | Cookie management object. For details, see [WebCookie](#webcookie).| | WebCookie | Cookie management object. For details, see [WebCookie](#webcookie).|
**Example** **Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
...@@ -2605,95 +3323,880 @@ Obtains the cookie management object of the **\<Web>** component. ...@@ -2605,95 +3323,880 @@ Obtains the cookie management object of the **\<Web>** component.
} }
``` ```
## HitTestValue<sup>9+</sup> ### createWebMessagePorts<sup>9+</sup>
Implements the **HitTestValue** object. For details about the sample code, see [getHitTestValue](#gethittestvalue9).
### getType<sup>9+</sup> createWebMessagePorts(): Array\<WebMessagePort\>
getType(): HitTestType
Obtains the element type of the area being clicked. Creates web message ports.
**Return value** **Return value**
| Type | Description |
| ------------------------------- | ------------- |
| [HitTestType](#hittesttype)| Element type of the area being clicked.|
### getExtra<sup>9+</sup>
getExtra(): string
Obtains the extra information of the area being clicked. If the area being clicked is an image or a link, the extra information is the URL of the image or link.
**Return value** | Type | Description |
| Type | Description | | ------------------------------- | ------------- |
| ------ | ------------ | | Array\<[WebMessagePort](#webmessageport9)\> | Array of web message ports.|
| string | Extra information of the area being clicked.|
**Example**
## WebCookie ```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
ports: WebMessagePort[] = null;
build() {
Column() {
Button('createWebMessagePorts')
.onClick(() => {
this.ports = this.controller.createWebMessagePorts();
console.log("createWebMessagePorts size:" + this.ports.length)
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
Manages behavior of cookies in **\<Web>** components. All **\<Web>** components in an application share a **WebCookie**. You can use the **getCookieManager** API in **controller** to obtain the **WebCookie** for subsequent cookie management. ### postMessage<sup>9+</sup>
### setCookie<sup>9+</sup> postMessage(options: { message: WebMessageEvent, uri: string}): void
setCookie(url: string, value: string): boolean
Sets the cookie. This API returns the result synchronously. Sends a web message to an HTML5 page.
**Parameters** **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ----- | ------ | ---- | ---- | ----------------- |
| url | string | Yes | - | URL of the cookie to set.|
| value | string | Yes | - | Value of the cookie to set. |
**Return value** | Name | Type | Mandatory | Default Value | Description |
| Type | Description | | ---------- | --------------- | ---- | ---- | ------------------------- |
| ------- | ------------- | | message | [WebMessageEvent](#webmessageevent9) | Yes | - |Message to send, including data and the message port.|
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| | uri | string | Yes | - | URI to receive the message.|
**Example** **Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController();
ports: WebMessagePort[] = null;
build() { build() {
Column() { Column() {
Button('setCookie') Button('postMessage')
.onClick(() => { .onClick(() => {
let result = this.controller.getCookieManager().setCookie("www.example.com", "a=b"); var sendPortArray = new Array(this.ports[1]);
console.log("result: " + result); var msgEvent = new WebMessageEvent();
msgEvent.setData("__init_ports__");
msgEvent.setPorts(sendPortArray);
this.controller.postMessage({message: msgEvent, uri: "*"});
}) })
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
} }
} }
} }
// xxx.js
var h5Port;
window.addEventListener('message', function(event){
if (event.data == '__init_ports__') {
if(event.ports[0] != null) {
h5Port = event.ports[0];
h5Port.onmessage = function(event) {
console.log('receive message from ets, on message:' + event.data);
}
}
}
})
``` ```
### saveCookieSync<sup>9+</sup> ### getUrl<sup>9+</sup>
saveCookieSync(): boolean
getUrl(): string
Obtains the URL of the current page.
**Return value**
| Type | Description |
| ------------------------------- | ------------- |
| string | URL of the current page.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
build() {
Column() {
Button('getUrl')
.onClick(() => {
console.log("url: " + this.controller.getUrl());
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
## HitTestValue<sup>9+</sup>
Implements the **HitTestValue** object. For details about the sample code, see [getHitTestValue](#gethittestvalue9).
### getType<sup>9+</sup>
getType(): HitTestType
Obtains the element type of the area being clicked.
**Return value**
| Type | Description |
| ------------------------------- | ------------- |
| [HitTestType](#hittesttype)| Element type of the area being clicked.|
### getExtra<sup>9+</sup>
getExtra(): string
Obtains the extra information of the area being clicked. If the area being clicked is an image or a link, the extra information is the URL of the image or link.
**Return value**
| Type | Description |
| ------ | ------------ |
| string | Extra information of the area being clicked.|
## WebCookie
Manages behavior of cookies in **\<Web>** components. All **\<Web>** components in an application share a **WebCookie**. You can use the **getCookieManager** API in **controller** to obtain the **WebCookie** for subsequent cookie management.
### setCookie<sup>9+</sup>
setCookie(url: string, value: string): boolean
Sets the cookie. This API returns the result synchronously. Returns **true** if the operation is successful; returns **false** otherwise.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ----- | ------ | ---- | ---- | ----------------- |
| url | string | Yes | - | URL of the cookie to set.|
| value | string | Yes | - | Value of the cookie to set. |
**Return value**
| Type | Description |
| ------- | ------------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
build() {
Column() {
Button('setCookie')
.onClick(() => {
let result = this.controller.getCookieManager().setCookie("www.example.com", "a=b");
console.log("result: " + result);
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### saveCookieSync<sup>9+</sup>
saveCookieSync(): boolean
Saves this cookie in the memory to the drive. This API returns the result synchronously. Saves this cookie in the memory to the drive. This API returns the result synchronously.
**Return value** **Return value**
| Type | Description |
| ------- | -------------------- |
| boolean | Operation result.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
build() {
Column() {
Button('saveCookieSync')
.onClick(() => {
let result = this.controller.getCookieManager().saveCookieSync();
console.log("result: " + result);
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### getCookie<sup>9+</sup>
getCookie(url: string): string
Obtains the cookie value corresponding to the specified URL.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ----- | ------ | ---- | ---- | ----------------- |
| url | string | Yes | - | URL of the cookie value to obtain.|
**Return value**
| Type | Description |
| ------- | -------------------- |
| string | Cookie value corresponding to the specified URL.|
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
build() {
Column() {
Button('getCookie')
.onClick(() => {
let value = webview.WebCookieManager.getCookie('www.example.com');
console.log("value: " + value);
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### setCookie<sup>9+</sup>
setCookie(url: string, value: string): boolean
Sets a cookie value for the specified URL.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ----- | ------ | ---- | ---- | ----------------- |
| url | string | Yes | - | URL of the cookie to set.|
| value | string | Yes | - | Cookie value to set.|
**Return value**
| Type | Description |
| ------- | -------------------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
build() {
Column() {
Button('setCookie')
.onClick(() => {
let result = web_webview.WebCookieManager.setCookie('www.example.com', 'a=b');
console.log("result: " + result);
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### saveCookieSync<sup>9+</sup>
saveCookieSync(): boolean
Saves cookies in the memory to the drive. This API is synchronous.
**Return value**
| Type | Description | | Type | Description |
| ------- | -------------------- | | ------- | -------------------- |
| boolean | Operation result.| | boolean | Operation result.|
**Example** **Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
build() {
Column() {
Button('saveCookieSync')
.onClick(() => {
let result = web_webview.WebCookieManager.saveCookieSync();
console.log("result: " + result);
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### saveCookieAsync<sup>9+</sup>
saveCookieAsync(): Promise\<boolean>
Saves cookies in the memory to the drive. This API uses a promise to return the value.
**Return value**
| Type | Description |
| ------- | -------------------- |
| Promise\<boolean> | Promise used to return the result.|
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
build() {
Column() {
Button('saveCookieAsync')
.onClick(() => {
web_webview.WebCookieManager.saveCookieAsync()
.then (function(result) {
console.log("result: " + result);
})
.catch(function(error) {
console.error("error: " + error);
});
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### saveCookieAsync<sup>9+</sup>
saveCookieAsync(callback: AsyncCallback\<boolean>): void
Saves cookies in the memory to the drive. This API uses an asynchronous callback to return the value.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ----- | ------ | ---- | ---- | ----------------- |
| callback | AsyncCallback\<boolean> | Yes | - | Callback used to return the operation result.|
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
build() {
Column() {
Button('saveCookieAsync')
.onClick(() => {
web_webview.WebCookieManager.saveCookieAsync(function(result) {
console.log("result: " + result);
});
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### isCookieAllowed<sup>9+</sup>
isCookieAllowed(): boolean
Checks whether the **WebCookieManager** instance has the permission to send and receive cookies.
**Return value**
| Type | Description |
| ------- | -------------------- |
| boolean | Whether the **WebCookieManager** instance has the permission to send and receive cookies.|
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
build() {
Column() {
Button('isCookieAllowed')
.onClick(() => {
let result = web_webview.WebCookieManager.isCookieAllowed();
console.log("result: " + result);
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### putAcceptCookieEnabled<sup>9+</sup>
putAcceptCookieEnabled(accept: boolean): void
Sets whether the **WebCookieManager** instance has the permission to send and receive cookies.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ----- | ------ | ---- | ---- | ----------------- |
| accept | boolean | Yes | - | Whether the **WebCookieManager** instance has the permission to send and receive cookies.|
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
build() {
Column() {
Button('putAcceptCookieEnabled')
.onClick(() => {
web_webview.WebCookieManager.putAcceptCookieEnabled(false);
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### isThirdPartyCookieAllowed<sup>9+</sup>
isThirdCookieAllowed(): boolean
Checks whether the **WebCookieManager** instance has the permission to send and receive third-party cookies.
**Return value**
| Type | Description |
| ------- | -------------------- |
| boolean | Whether the **WebCookieManager** instance has the permission to send and receive third-party cookies.|
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
build() {
Column() {
Button('isThirdPartyCookieAllowed')
.onClick(() => {
let result = web_webview.WebCookieManager.isThirdPartyCookieAllowed();
console.log("result: " + result);
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### putAcceptThirdPartyCookieEnabled<sup>9+</sup>
putAcceptThirdPartyCookieEnabled(accept: boolean): void
Sets whether the **WebCookieManager** instance has the permission to send and receive third-party cookies.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ----- | ------ | ---- | ---- | ----------------- |
| accept | boolean | Yes | - | Whether the **WebCookieManager** instance has the permission to send and receive third-party cookies.|
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
build() {
Column() {
Button('putAcceptThirdPartyCookieEnabled')
.onClick(() => {
web_webview.WebCookieManager.putAcceptThirdPartyCookieEnabled(false);
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### existCookie<sup>9+</sup>
existCookie(): boolean
Checks whether cookies exist.
**Return value**
| Type | Description |
| ------- | -------------------- |
| boolean | Whether cookies exist.|
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
build() {
Column() {
Button('existCookie')
.onClick(() => {
let result = web_webview.WebCookieManager.existCookie();
console.log("result: " + result);
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### deleteEntireCookie<sup>9+</sup>
deleteEntireCookie(): void
Deletes all cookies.
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
build() {
Column() {
Button('deleteEntireCookie')
.onClick(() => {
web_webview.WebCookieManager.deleteEntireCookie();
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### deleteSessionCookie<sup>9+</sup>
deleteSessionCookie(): void
Deletes all session cookies.
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
build() {
Column() {
Button('deleteSessionCookie')
.onClick(() => {
webview.WebCookieManager.deleteSessionCookie();
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
## WebDataBase<sup>9+</sup>
Implements the **WebDataBase** object.
### existHttpAuthCredentials<sup>9+</sup>
static existHttpAuthCredentials(): boolean
Checks whether any saved HTTP authentication credentials exist. This API is synchronous.
**Return value**
| Type | Description |
| ------- | ---------------------------------------- |
| boolean | Whether any saved HTTP authentication credentials exist. Returns **true** if any saved HTTP authentication credentials exist exists; returns **false** otherwise.|
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
build() {
Column() {
Button('existHttpAuthCredentials')
.onClick(() => {
let result = web_webview.WebDataBase.existHttpAuthCredentials();
console.log('result: ' + result);
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### deleteHttpAuthCredentials<sup>9+</sup>
static deleteHttpAuthCredentials(): void
Deletes all HTTP authentication credentials saved in the cache. This API returns the result synchronously.
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
build() {
Column() {
Button('deleteHttpAuthCredentials')
.onClick(() => {
web_webview.WebDataBase.deleteHttpAuthCredentials();
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### getHttpAuthCredentials<sup>9+</sup>
static getHttpAuthCredentials(host: string, realm: string): Array\<string\>
Retrieves HTTP authentication credentials for a given host and domain. This API is synchronous.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ----- | ------ | ---- | ---- | ---------------- |
| host | string | Yes | - | Host for which you want to obtain the HTTP authentication credentials.|
| realm | string | Yes | - | Realm for which you want to obtain the HTTP authentication credentials. |
**Return value**
| Type | Description |
| --------------- | ---------------------- |
| Array\<string\> | Returns the array of the matching user names and passwords if the operation is successful; returns an empty array otherwise.|
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
host: string = "www.spincast.org";
realm: string = "protected example";
username_password: string[];
build() {
Column() {
Button('getHttpAuthCredentials')
.onClick(() => {
this.username_password = web_webview.WebDataBase.getHttpAuthCredentials(this.host, this.realm);
console.log('num: ' + this.username_password.length);
ForEach(this.username_password, (item) => {
console.log('username_password: ' + item);
}, item => item)
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### saveHttpAuthCredentials<sup>9+</sup>
static saveHttpAuthCredentials(host: string, realm: string, username: string, password: string): void
Saves HTTP authentication credentials for a given host and realm. This API returns the result synchronously.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| -------- | ------ | ---- | ---- | ---------------- |
| host | string | Yes | - | Host for which you want to obtain the HTTP authentication credentials.|
| realm | string | Yes | - | Realm to which HTTP authentication credentials apply. |
| username | string | Yes | - | User name. |
| password | string | Yes | - | Password. |
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
host: string = "www.spincast.org";
realm: string = "protected example";
build() {
Column() {
Button('saveHttpAuthCredentials')
.onClick(() => {
web_webview.WebDataBase.saveHttpAuthCredentials(this.host, this.realm, "Stromgol", "Laroche");
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
## GeolocationPermissions<sup>9+</sup>
Defines a **GeolocationPermissions** object.
### allowGeolocation<sup>9+</sup>
static allowGeolocation(origin: string): void
Allows the specified source to use the geolocation information.
**Parameters**
| Name | Type| Mandatory| Default Value| Description |
| -------- | -------- | ---- | ----- | ------------- |
| origin | string | Yes | - | Index of the source.|
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
origin: string = "file:///";
build() {
Column() {
Button('allowGeolocation')
.onClick(() => {
web_webview.GeolocationPermissions.allowGeolocation(this.origin);
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### deleteGeolocation<sup>9+</sup>
static deleteGeolocation(origin: string): void
Clears the geolocation permission status of a specified source.
**Parameters**
| Name | Type| Mandatory| Default Value| Description |
| -------- | -------- | ---- | ----- | ------------- |
| origin | string | Yes | - | Index of the source.|
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
origin: string = "file:///";
build() {
Column() {
Button('deleteGeolocation')
.onClick(() => {
web_webview.GeolocationPermissions.deleteGeolocation(this.origin);
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### deleteAllGeolocation<sup>9+</sup>
static deleteAllGeolocation(): void
Clears the geolocation permission status of all sources.
**Example**
```ts ```ts
// xxx.ets // xxx.ets
import web_webview from '@ohos.web.webview';
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController();
build() { build() {
Column() { Column() {
Button('saveCookieSync') Button('deleteAllGeolocation')
.onClick(() => { .onClick(() => {
let result = this.controller.getCookieManager().saveCookieSync(); web_webview.GeolocationPermissions.deleteAllGeolocation();
console.log("result: " + result);
}) })
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
} }
...@@ -2701,35 +4204,40 @@ Saves this cookie in the memory to the drive. This API returns the result synchr ...@@ -2701,35 +4204,40 @@ Saves this cookie in the memory to the drive. This API returns the result synchr
} }
``` ```
## WebDataBase<sup>9+</sup> ### getAccessibleGeolocation<sup>9+</sup>
Implements the **WebDataBase** object.
### existHttpAuthCredentials<sup>9+</sup> static getAccessibleGeolocation(origin: string, callback: AsyncCallback\<boolean\>): void
static existHttpAuthCredentials(): boolean Obtains the geolocation permission status of the specified source. This API uses an asynchronous callback to return the result.
Checks whether any HTTP authentication credentials exist in the cache. This API returns the result synchronously. **Parameters**
**Return value** | Name | Type| Mandatory| Default Value| Description |
| Type | Description | | -------- | -------- | ---- | ----- | ------------- |
| ------- | ---------------------------------------- | | origin | string | Yes | - | Index of the origin.|
| boolean | Returns **true** if any HTTP authentication credentials exist in the cache; returns **false** otherwise.| | callback | AsyncCallback\<boolean\> | Yes| - | Callback used to return the geolocation permission status of the specified source. If the operation is successful, the value **true** means that the geolocation permission is granted, and **false** means the opposite. If the operation fails, the geolocation permission status of the specified source is not found.|
**Example** **Example**
```ts ```ts
// xxx.ets // xxx.ets
import web from '@ohos.web'; import web_webview from '@ohos.web.webview';
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController();
origin: string = "file:///";
build() { build() {
Column() { Column() {
Button('existHttpAuthCredentials') Button('getAccessibleGeolocationAsync')
.onClick(() => { .onClick(() => {
let result = web.WebDataBase.existHttpAuthCredentials(); web_webview.GeolocationPermissions.getAccessibleGeolocation(this.origin, (error, result) => {
console.log('result: ' + result); if (error) {
console.log('getAccessibleGeolocationAsync error: ' + JSON.stringify(error));
return;
}
console.log('getAccessibleGeolocationAsync result: ' + result);
});
}) })
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
} }
...@@ -2737,26 +4245,43 @@ Checks whether any HTTP authentication credentials exist in the cache. This API ...@@ -2737,26 +4245,43 @@ Checks whether any HTTP authentication credentials exist in the cache. This API
} }
``` ```
### deleteHttpAuthCredentials<sup>9+</sup> ### getAccessibleGeolocation<sup>9+</sup>
static deleteHttpAuthCredentials(): void static getAccessibleGeolocation(origin: string): Promise\<boolean\>
Deletes all HTTP authentication credentials saved in the cache. This API returns the result synchronously. Obtains the geolocation permission status of the specified source. This API uses a promise to return the result.
**Parameters**
| Name | Type| Mandatory| Default Value| Description |
| -------- | -------- | ---- | ----- | ------------- |
| origin | string | Yes | - | Index of the origin.|
**Return value**
| Type | Description |
| ------------------ | ------------------------------------ |
| Promise\<boolean\> | Promise used to return the geolocation permission status of the specified source. If the operation is successful, the value **true** means that the geolocation permission is granted, and **false** means the opposite. If the operation fails, the geolocation permission status of the specified source is not found.|
**Example** **Example**
```ts ```ts
// xxx.ets // xxx.ets
import web from '@ohos.web'; import web_webview from '@ohos.web.webview';
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController();
origin: string = "file:///";
build() { build() {
Column() { Column() {
Button('deleteHttpAuthCredentials') Button('getAccessibleGeolocationPromise')
.onClick(() => { .onClick(() => {
web.WebDataBase.deleteHttpAuthCredentials(); web_webview.GeolocationPermissions.getAccessibleGeolocation(this.origin).then(result => {
console.log('getAccessibleGeolocationPromise result: ' + result);
}).catch(error => {
console.log('getAccessibleGeolocationPromise error: ' + JSON.stringify(error));
});
}) })
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
} }
...@@ -2764,43 +4289,39 @@ Deletes all HTTP authentication credentials saved in the cache. This API returns ...@@ -2764,43 +4289,39 @@ Deletes all HTTP authentication credentials saved in the cache. This API returns
} }
``` ```
### getHttpAuthCredentials<sup>9+</sup> ### getStoredGeolocation<sup>9+</sup>
static getHttpAuthCredentials(host: string, realm: string): Array\<string\> static getStoredGeolocation(callback: AsyncCallback\<Array\<string\>\>): void
Obtains the HTTP authentication credentials for a given host and realm. This API returns the result synchronously. Obtains the geolocation permission status of all sources. This API uses an asynchronous callback to return the result.
**Parameters** **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ----- | ------ | ---- | ---- | ---------------- |
| host | string | Yes | - | Host for which you want to obtain the HTTP authentication credentials.|
| realm | string | Yes | - | Realm for which you want to obtain the HTTP authentication credentials. |
**Return value** | Name | Type| Mandatory| Default Value| Description |
| Type | Description | | -------- | -------- | ---- | ----- | ------------- |
| --------------- | ---------------------- | | callback | AsyncCallback\<Array\<string\>\> | Yes| - | Callback used to return the geolocation permission status of all sources.|
| Array\<string\> | Returns the array of the matching user names and passwords if the operation is successful; returns an empty array otherwise.|
**Example** **Example**
```ts ```ts
// xxx.ets // xxx.ets
import web from '@ohos.web'; import web_webview from '@ohos.web.webview';
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController();
host: string = "www.spincast.org";
realm: string = "protected example";
username_password: string[];
build() { build() {
Column() { Column() {
Button('getHttpAuthCredentials') Button('getStoredGeolocationAsync')
.onClick(() => { .onClick(() => {
this.username_password = web.WebDataBase.getHttpAuthCredentials(this.host, this.realm); web_webview.GeolocationPermissions.getStoredGeolocation((error, origins) => {
console.log('num: ' + this.username_password.length); if (error) {
ForEach(this.username_password, (item) => { console.log('getStoredGeolocationAsync error: ' + JSON.stringify(error));
console.log('username_password: ' + item); return;
}, item => item) }
let origins_str: string = origins.join();
console.log('getStoredGeolocationAsync origins: ' + origins_str);
});
}) })
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
} }
...@@ -2808,35 +4329,43 @@ Obtains the HTTP authentication credentials for a given host and realm. This API ...@@ -2808,35 +4329,43 @@ Obtains the HTTP authentication credentials for a given host and realm. This API
} }
``` ```
### saveHttpAuthCredentials<sup>9+</sup> ### getStoredGeolocation<sup>9+</sup>
static saveHttpAuthCredentials(host: string, realm: string, username: string, password: string): void static getStoredGeolocation(): Promise\<Array\<string\>\>
Saves HTTP authentication credentials for a given host and realm. This API returns the result synchronously. Obtains the geolocation permission status of all sources. This API uses a promise to return the result.
**Parameters** **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| -------- | ------ | ---- | ---- | ---------------- | | Name | Type| Mandatory| Default Value| Description |
| host | string | Yes | - | Host to which HTTP authentication credentials apply.| | -------- | -------- | ---- | ----- | ------------- |
| realm | string | Yes | - | Realm to which HTTP authentication credentials apply. | | callback | AsyncCallback\<Array\<string\>\> | Yes| - | Callback used to return the geolocation permission status of all sources.|
| username | string | Yes | - | User name. |
| password | string | Yes | - | Password. | **Return value**
| Type | Description |
| -------------------------- | ------------------------------------ |
| Promise\<Array\<string\>\> | Promise used to return the geolocation permission status of all sources.|
**Example** **Example**
```ts ```ts
// xxx.ets // xxx.ets
import web from '@ohos.web'; import web_webview from '@ohos.web.webview';
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: WebController = new WebController();
host: string = "www.spincast.org";
realm: string = "protected example";
build() { build() {
Column() { Column() {
Button('saveHttpAuthCredentials') Button('getStoredGeolocationPromise')
.onClick(() => { .onClick(() => {
web.WebDataBase.saveHttpAuthCredentials(this.host, this.realm, "Stromgol", "Laroche"); web_webview.GeolocationPermissions.getStoredGeolocation().then(origins => {
let origins_str: string = origins.join();
console.log('getStoredGeolocationPromise origins: ' + origins_str);
}).catch(error => {
console.log('getStoredGeolocationPromise error: ' + JSON.stringify(error));
});
}) })
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
} }
...@@ -2852,9 +4381,10 @@ static deleteAllData(): void ...@@ -2852,9 +4381,10 @@ static deleteAllData(): void
Deletes all data in the Web SQL database. Deletes all data in the Web SQL database.
**Example** **Example**
```ts ```ts
// xxx.ets // xxx.ets
import web from '@ohos.web'; import web_webview from '@ohos.web.webview'
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
...@@ -2863,7 +4393,7 @@ Deletes all data in the Web SQL database. ...@@ -2863,7 +4393,7 @@ Deletes all data in the Web SQL database.
Column() { Column() {
Button('deleteAllData') Button('deleteAllData')
.onClick(() => { .onClick(() => {
web.WebStorage.deleteAllData(); web_webview.WebStorage.deleteAllData();
}) })
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
.databaseAccess(true) .databaseAccess(true)
...@@ -2878,14 +4408,16 @@ static deleteOrigin(origin : string): void ...@@ -2878,14 +4408,16 @@ static deleteOrigin(origin : string): void
Deletes all data in the specified origin. Deletes all data in the specified origin.
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ------ | ------ | ---- | ---------- | | ------ | ------ | ---- | ---------- |
| origin | string | Yes | Index of the origin.| | origin | string | Yes | Index of the origin.|
**Example** **Example**
```ts ```ts
// xxx.ets // xxx.ets
import web from '@ohos.web'; import web_webview from '@ohos.web.webview'
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
...@@ -2895,7 +4427,7 @@ Deletes all data in the specified origin. ...@@ -2895,7 +4427,7 @@ Deletes all data in the specified origin.
Column() { Column() {
Button('getHttpAuthCredentials') Button('getHttpAuthCredentials')
.onClick(() => { .onClick(() => {
web.WebStorage.deleteOrigin(this.origin); web_webview.WebStorage.deleteOrigin(this.origin);
}) })
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
.databaseAccess(true) .databaseAccess(true)
...@@ -2905,19 +4437,21 @@ Deletes all data in the specified origin. ...@@ -2905,19 +4437,21 @@ Deletes all data in the specified origin.
``` ```
### getOrigins<sup>9+</sup> ### getOrigins<sup>9+</sup>
static getOrigins(callback: AsyncCallback<Array<[WebStorageOrigin]>>) : void static getOrigins(callback: AsyncCallback<Array<WebStorageOrigin>>) : void
Obtains information about all origins that are currently using the Web SQL database. This API uses an asynchronous callback to return the result. Obtains information about all origins that are currently using the Web SQL database. This API uses an asynchronous callback to return the result.
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | ----------------------------------- | | -------- | ---------------------------------------- | ---- | ----------------------------------- |
| callback | AsyncCallback<Array<[WebStorageOrigin](#webstorageorigin9)>> | Yes | Callback used to return the information about the origins. For details, see **WebStorageOrigin**.| | callback | AsyncCallback<Array<[WebStorageOrigin](#webstorageorigin9)>> | Yes | Callback used to return the information about the origins. For details, see **WebStorageOrigin**.|
**Example** **Example**
```ts ```ts
// xxx.ets // xxx.ets
import web from '@ohos.web'; import web_webview from '@ohos.web.webview'
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
...@@ -2927,7 +4461,7 @@ Obtains information about all origins that are currently using the Web SQL datab ...@@ -2927,7 +4461,7 @@ Obtains information about all origins that are currently using the Web SQL datab
Column() { Column() {
Button('getOrigins') Button('getOrigins')
.onClick(() => { .onClick(() => {
web.WebStorage.getOrigins((error, origins) => { web_webview.WebStorage.getOrigins((error, origins) => {
if (error) { if (error) {
console.log('error: ' + error); console.log('error: ' + error);
return; return;
...@@ -2947,7 +4481,7 @@ Obtains information about all origins that are currently using the Web SQL datab ...@@ -2947,7 +4481,7 @@ Obtains information about all origins that are currently using the Web SQL datab
``` ```
### getOrigins<sup>9+</sup> ### getOrigins<sup>9+</sup>
static getOrigins() : Promise<Array<[WebStorageOrigin]>> static getOrigins() : Promise<Array<WebStorageOrigin>>
Obtains information about all origins that are currently using the Web SQL database. This API uses a promise to return the result. Obtains information about all origins that are currently using the Web SQL database. This API uses a promise to return the result.
...@@ -2958,9 +4492,10 @@ Obtains information about all origins that are currently using the Web SQL datab ...@@ -2958,9 +4492,10 @@ Obtains information about all origins that are currently using the Web SQL datab
| Promise<Array<[WebStorageOrigin](#webstorageorigin9)>> | Promise used to return the information about the origins. For details, see **WebStorageOrigin**.| | Promise<Array<[WebStorageOrigin](#webstorageorigin9)>> | Promise used to return the information about the origins. For details, see **WebStorageOrigin**.|
**Example** **Example**
```ts ```ts
// xxx.ets // xxx.ets
import web from '@ohos.web'; import web_webview from '@ohos.web.webview'
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
...@@ -2970,7 +4505,7 @@ Obtains information about all origins that are currently using the Web SQL datab ...@@ -2970,7 +4505,7 @@ Obtains information about all origins that are currently using the Web SQL datab
Column() { Column() {
Button('getOrigins') Button('getOrigins')
.onClick(() => { .onClick(() => {
web.WebStorage.getOrigins() web_webview.WebStorage.getOrigins()
.then(origins => { .then(origins => {
for (let i = 0; i < origins.length; i++) { for (let i = 0; i < origins.length; i++) {
console.log('origin: ' + origins[i].origin); console.log('origin: ' + origins[i].origin);
...@@ -2995,15 +4530,17 @@ static getOriginQuota(origin : string, callback : AsyncCallback\<number>) : void ...@@ -2995,15 +4530,17 @@ static getOriginQuota(origin : string, callback : AsyncCallback\<number>) : void
Obtains the storage quota of an origin in the Web SQL database, in bytes. This API uses an asynchronous callback to return the result. Obtains the storage quota of an origin in the Web SQL database, in bytes. This API uses an asynchronous callback to return the result.
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | ---------------------- | ---- | --------- | | -------- | ---------------------- | ---- | --------- |
| origin | string | Yes | Index of the origin.| | origin | string | Yes | Index of the origin.|
| callback | AsyncCallback\<number> | Yes | Callback used to return the storage quota of the origin.| | callback | AsyncCallback\<number> | Yes | Callback used to return the storage quota of the origin.|
**Example** **Example**
```ts ```ts
// xxx.ets // xxx.ets
import web from '@ohos.web'; import web_webview from '@ohos.web.webview'
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
...@@ -3013,7 +4550,7 @@ Obtains the storage quota of an origin in the Web SQL database, in bytes. This A ...@@ -3013,7 +4550,7 @@ Obtains the storage quota of an origin in the Web SQL database, in bytes. This A
Column() { Column() {
Button('getOriginQuota') Button('getOriginQuota')
.onClick(() => { .onClick(() => {
web.WebStorage.getOriginQuota(this.origin, (error, quota) => { web_webview.WebStorage.getOriginQuota(this.origin, (error, quota) => {
if (error) { if (error) {
console.log('error: ' + error); console.log('error: ' + error);
return; return;
...@@ -3034,19 +4571,22 @@ static getOriginQuota(origin : string) : Promise\<number> ...@@ -3034,19 +4571,22 @@ static getOriginQuota(origin : string) : Promise\<number>
Obtains the storage quota of an origin in the Web SQL database, in bytes. This API uses a promise to return the result. Obtains the storage quota of an origin in the Web SQL database, in bytes. This API uses a promise to return the result.
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ------ | ------ | ---- | ---------- | | ------ | ------ | ---- | ---------- |
| origin | string | Yes | Index of the origin.| | origin | string | Yes | Index of the origin.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| ---------------- | ----------------------- | | ---------------- | ----------------------- |
| Promise\<number> | Promise used to return the storage quota of the origin.| | Promise\<number> | Promise used to return the storage quota of the origin.|
**Example** **Example**
```ts ```ts
// xxx.ets // xxx.ets
import web from '@ohos.web'; import web_webview from '@ohos.web.webview'
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
...@@ -3056,7 +4596,7 @@ Obtains the storage quota of an origin in the Web SQL database, in bytes. This A ...@@ -3056,7 +4596,7 @@ Obtains the storage quota of an origin in the Web SQL database, in bytes. This A
Column() { Column() {
Button('getOriginQuota') Button('getOriginQuota')
.onClick(() => { .onClick(() => {
web.WebStorage.getOriginQuota(this.origin) web_webview.WebStorage.getOriginQuota(this.origin)
.then(quota => { .then(quota => {
console.log('quota: ' + quota); console.log('quota: ' + quota);
}) })
...@@ -3077,15 +4617,17 @@ static getOriginUsage(origin : string, callback : AsyncCallback\<number>) : void ...@@ -3077,15 +4617,17 @@ static getOriginUsage(origin : string, callback : AsyncCallback\<number>) : void
Obtains the storage usage of an origin in the Web SQL database, in bytes. This API uses an asynchronous callback to return the result. Obtains the storage usage of an origin in the Web SQL database, in bytes. This API uses an asynchronous callback to return the result.
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | ---------------------- | ---- | ---------- | | -------- | ---------------------- | ---- | ---------- |
| origin | string | Yes | Index of the origin.| | origin | string | Yes | Index of the origin.|
| callback | AsyncCallback\<number> | Yes | Callback used to return the storage usage of the origin. | | callback | AsyncCallback\<number> | Yes | Callback used to return the storage usage of the origin. |
**Example** **Example**
```ts ```ts
// xxx.ets // xxx.ets
import web from '@ohos.web'; import web_webview from '@ohos.web.webview'
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
...@@ -3095,12 +4637,12 @@ Obtains the storage usage of an origin in the Web SQL database, in bytes. This A ...@@ -3095,12 +4637,12 @@ Obtains the storage usage of an origin in the Web SQL database, in bytes. This A
Column() { Column() {
Button('getOriginUsage') Button('getOriginUsage')
.onClick(() => { .onClick(() => {
web.WebStorage.getOriginUsage(this.origin, (error, usage) => { web_webview.WebStorage.getOriginUsage(this.origin, (error, usage) => {
if (error) { if (error) {
console.log('error: ' + error); console.log('error: ' + error);
return; return;
} }
consloe.log('usage: ' + usage); console.log('usage: ' + usage);
}) })
}) })
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
...@@ -3116,19 +4658,22 @@ static getOriginUsage(origin : string) : Promise\<number> ...@@ -3116,19 +4658,22 @@ static getOriginUsage(origin : string) : Promise\<number>
Obtains the storage usage of an origin in the Web SQL database, in bytes. This API uses a promise to return the result. Obtains the storage usage of an origin in the Web SQL database, in bytes. This API uses a promise to return the result.
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ------ | ------ | ---- | ---------- | | ------ | ------ | ---- | ---------- |
| origin | string | Yes | Index of the origin.| | origin | string | Yes | Index of the origin.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| ---------------- | ---------------------- | | ---------------- | ---------------------- |
| Promise\<number> | Promise used to return the storage usage of the origin.| | Promise\<number> | Promise used to return the storage usage of the origin.|
**Example** **Example**
```ts ```ts
// xxx.ets // xxx.ets
import web from '@ohos.web'; import web_webview from '@ohos.web.webview'
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
...@@ -3138,7 +4683,7 @@ Obtains the storage usage of an origin in the Web SQL database, in bytes. This A ...@@ -3138,7 +4683,7 @@ Obtains the storage usage of an origin in the Web SQL database, in bytes. This A
Column() { Column() {
Button('getOriginQuota') Button('getOriginQuota')
.onClick(() => { .onClick(() => {
web.WebStorage.getOriginUsage(this.origin) web_webview.WebStorage.getOriginUsage(this.origin)
.then(usage => { .then(usage => {
console.log('usage: ' + usage); console.log('usage: ' + usage);
}) })
...@@ -3165,6 +4710,7 @@ Searches the web page for content that matches the keyword specified by **'searc ...@@ -3165,6 +4710,7 @@ Searches the web page for content that matches the keyword specified by **'searc
| searchString | string | Yes | - | Search keyword.| | searchString | string | Yes | - | Search keyword.|
**Example** **Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
...@@ -3204,6 +4750,7 @@ clearMatches(): void ...@@ -3204,6 +4750,7 @@ clearMatches(): void
Clears the matches found through [searchAllAsync](#searchallasync9). Clears the matches found through [searchAllAsync](#searchallasync9).
**Example** **Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
...@@ -3237,6 +4784,7 @@ Searches for and highlights the next match. ...@@ -3237,6 +4784,7 @@ Searches for and highlights the next match.
**Example** **Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
...@@ -3271,6 +4819,7 @@ Invoked to notify the caller of the search result on the web page. ...@@ -3271,6 +4819,7 @@ Invoked to notify the caller of the search result on the web page.
| isDoneCounting | boolean | Whether the search operation on the current page is complete. This API may be called multiple times until **isDoneCounting** is **true**.| | isDoneCounting | boolean | Whether the search operation on the current page is complete. This API may be called multiple times until **isDoneCounting** is **true**.|
**Example** **Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
...@@ -3295,6 +4844,7 @@ Invoked to notify the caller of the search result on the web page. ...@@ -3295,6 +4844,7 @@ Invoked to notify the caller of the search result on the web page.
Provides usage information about the Web SQL database. Provides usage information about the Web SQL database.
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ------ | ------ | ---- | ---------- | | ------ | ------ | ---- | ---------- |
| origin | string | Yes | Index of the origin.| | origin | string | Yes | Index of the origin.|
...@@ -3359,11 +4909,22 @@ Explains why the rendering process exits. ...@@ -3359,11 +4909,22 @@ Explains why the rendering process exits.
| Map | Geographical address. | | Map | Geographical address. |
| Unknown | Unknown content. | | Unknown | Unknown content. |
## SslError<sup>9+</sup>
Enumerates the error codes returned by **onSslErrorEventReceive** API.
| Name | Description |
| -------------- | ----------------- |
| Invalid | Minor error. |
| HostMismatch | The host name does not match. |
| DateInvalid | The certificate has an invalid date. |
| Untrusted | The certificate issuer is not trusted.|
## ProtectedResourceType<sup>9+</sup> ## ProtectedResourceType<sup>9+</sup>
| Name | Description | Remarks | | Name | Description | Remarks |
| --------- | -------------- | -------------- | | --------- | -------------- | -------------- |
| MidiSysex | MIDI SYSEX resources| Currently, only permission events can be reported. MIDI devices are not yet supported.| | MidiSysex | MIDI SYSEX resource.| Currently, only permission events can be reported. MIDI devices are not yet supported.|
## WebAsyncController ## WebAsyncController
...@@ -3378,7 +4939,7 @@ webAsyncController: WebAsyncController = new WebAsyncController(webController); ...@@ -3378,7 +4939,7 @@ webAsyncController: WebAsyncController = new WebAsyncController(webController);
### storeWebArchive<sup>9+</sup> ### storeWebArchive<sup>9+</sup>
storeWebArchive(baseName: string, autoName: boolean, callback: AsyncCallback\<string>): void storeWebArchive(baseName: string, autoName: boolean, callback: AsyncCallback<string>): void
Saves the current web page. This API uses an asynchronous callback to return the result. Saves the current web page. This API uses an asynchronous callback to return the result.
...@@ -3386,15 +4947,15 @@ Saves the current web page. This API uses an asynchronous callback to return the ...@@ -3386,15 +4947,15 @@ Saves the current web page. This API uses an asynchronous callback to return the
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | ----------------------------------- | | -------- | ---------------------------------------- | ---- | ----------------------------------- |
| baseName | string | Yes| Save path. The value cannot be null.| | baseName | string | Yes| Save path. The value cannot be null.
| autoName | boolean | Yes| Whether to automatically generate a file name.<br>The value **true** means to automatically generate a file name based on the URL of current page and the **baseName** value. In this case, **baseName** is regarded as a directory.<br>The value **false** means not to automatically generate a file name.| | autoName | boolean | Yes| Whether to automatically generate a file name.<br>The value **false** means not to automatically generate a file name.<br>The value **true** means to automatically generate a file name based on the URL of current page and the **baseName** value. In this case, **baseName** is regarded as a directory.
| callback | AsyncCallback\<string> | Yes | Callback used to return the save path if the operation is successful and null otherwise.| | callback | AsyncCallback<string> | Yes | Callback used to return the save path if the operation is successful and null otherwise.|
**Example** **Example**
```ts ```ts
// xxx.ets // xxx.ets
import WebAsyncController from '@ohos.web'; import web_webview from '@ohos.web.webview'
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
...@@ -3403,7 +4964,7 @@ Saves the current web page. This API uses an asynchronous callback to return the ...@@ -3403,7 +4964,7 @@ Saves the current web page. This API uses an asynchronous callback to return the
Column() { Column() {
Button('saveWebArchive') Button('saveWebArchive')
.onClick(() => { .onClick(() => {
let webAsyncController = new WebAsyncController(this.controller); let webAsyncController = new web_webview.WebAsyncController(this.controller);
webAsyncController.storeWebArchive("/data/storage/el2/base/", true, (filename) => { webAsyncController.storeWebArchive("/data/storage/el2/base/", true, (filename) => {
if (filename != null) { if (filename != null) {
console.info(`save web archive success: ${filename}`) console.info(`save web archive success: ${filename}`)
...@@ -3418,7 +4979,7 @@ Saves the current web page. This API uses an asynchronous callback to return the ...@@ -3418,7 +4979,7 @@ Saves the current web page. This API uses an asynchronous callback to return the
### storeWebArchive<sup>9+</sup> ### storeWebArchive<sup>9+</sup>
storeWebArchive(baseName: string, autoName: boolean): Promise\<string> storeWebArchive(baseName: string, autoName: boolean): Promise<string>
Stores the current web page. This API uses an asynchronous callback to return the result. Stores the current web page. This API uses an asynchronous callback to return the result.
...@@ -3426,20 +4987,20 @@ Stores the current web page. This API uses an asynchronous callback to return th ...@@ -3426,20 +4987,20 @@ Stores the current web page. This API uses an asynchronous callback to return th
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | ----------------------------------- | | -------- | ---------------------------------------- | ---- | ----------------------------------- |
| baseName | string | Yes| Save path. The value cannot be null.| | baseName | string | Yes| Save path. The value cannot be null.
| autoName | boolean | Yes| Determines whether to automatically generate a file name.<br>The value **true** means to automatically generate a file name based on the URL of current page and the **baseName** value. In this case, **baseName** is regarded as a directory.<br>The value **false** means not to automatically generate a file name.| | autoName | boolean | Yes| Whether to automatically generate a file name.<br>The value **false** means not to automatically generate a file name.<br>The value **true** means to automatically generate a file name based on the URL of current page and the **baseName** value. In this case, **baseName** is regarded as a directory.
**Return value** **Return value**
| Type | Description | | Type | Description |
| ---------------- | ------------------------------------------------------------ | | ---------------------------------------- | ---------------------------------------- |
| Promise\<string> | Promise used to return the save path if the operation is successful and null otherwise. | | Promise<string> | Promise used to return the save path if the operation is successful and null otherwise.|
**Example** **Example**
```ts ```ts
// xxx.ets // xxx.ets
import WebAsyncController from '@ohos.web'; import web_webview from '@ohos.web.webview'
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
...@@ -3448,7 +5009,7 @@ Stores the current web page. This API uses an asynchronous callback to return th ...@@ -3448,7 +5009,7 @@ Stores the current web page. This API uses an asynchronous callback to return th
Column() { Column() {
Button('saveWebArchive') Button('saveWebArchive')
.onClick(() => { .onClick(() => {
let webAsyncController = new WebAsyncController(this.controller); let webAsyncController = new web_webview.WebAsyncController(this.controller);
webAsyncController.storeWebArchive("/data/storage/el2/base/", true) webAsyncController.storeWebArchive("/data/storage/el2/base/", true)
.then(filename => { .then(filename => {
if (filename != null) { if (filename != null) {
...@@ -3461,3 +5022,224 @@ Stores the current web page. This API uses an asynchronous callback to return th ...@@ -3461,3 +5022,224 @@ Stores the current web page. This API uses an asynchronous callback to return th
} }
} }
``` ```
## WebMessagePort<sup>9+</sup>
Defines a **WebMessagePort** instance, which can can be used to send and receive messages.
### close<sup>9+</sup>
close(): void
Disables this message port.
### postMessageEvent<sup>9+</sup>
postMessageEvent(message: WebMessageEvent): void
Sends messages.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ----- | ------ | ---- | ---- | ----------------- |
| message | [WebMessageEvent](#webmessageevent9) | Yes | - | Message to send.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
ports: WebMessagePort[] = null;
build() {
Column() {
Button('postMessageEvent')
.onClick(() => {
var msg = new WebMessageEvent();
msg.setData("post message from ets to html5");
this.ports[0].postMessageEvent(msg);
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### onMessageEvent<sup>9+</sup>
onMessageEvent(callback: (result: string) => void): void
Registers a callback to receive messages from an HTML5 page.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ----- | ------ | ---- | ---- | ----------------- |
| callback | function | Yes | - | Callback for receiving messages.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
ports: WebMessagePort[] = null;
build() {
Column() {
Button('onMessageEvent')
.onClick(() => {
this.ports[0].onMessageEvent((result: string) => {
console.log("received message from html5, on message:" + result);
})
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
## WebMessageEvent<sup>9+</sup>
Implements the **WebMessageEvent** object to encapsulate the message and port.
### getData<sup>9+</sup>
getData(): string
Obtains the messages stored in this object.
**Return value**
| Type | Description |
| ------------------------------- | ------------- |
| string | Message stored in the object of this type.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
build() {
Column() {
Button('getPorts')
.onClick(() => {
var msgEvent = new WebMessageEvent();
msgEvent.setData("message event data");
var messageData = msgEvent.getData();
console.log("message is:" + messageData);
})
}
}
}
```
### setData<sup>9+</sup>
setData(data: string): void
Sets the message in this object.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ----- | ------ | ---- | ---- | ----------------- |
| data | string | Yes | - | Message to send.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
ports: WebMessagePort[] = null;
build() {
Column() {
Button('setData')
.onClick(() => {
var msg = new WebMessageEvent();
msg.setData("post message from ets to HTML5");
this.ports[0].postMessageEvent(msg);
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### getPorts<sup>9+</sup>
getPorts(): Array\<WebMessagePort\>
Obtains the message port stored in this object.
**Return value**
| Type | Description |
| ------------------------------- | ------------- |
| Array\<[WebMessagePort](#webmessageport9)\> | Message port stored in the object of this type.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
ports: WebMessagePort[] = null;
build() {
Column() {
Button('getPorts')
.onClick(() => {
var sendPortArray = new Array(this.ports[0]);
var msgEvent = new WebMessageEvent();
msgEvent.setPorts(sendPortArray);
var getPorts = msgEvent.getPorts();
console.log("Ports is:" + getPorts);
})
}
}
}
```
### setPorts<sup>9+</sup>
setPorts(ports: Array\<WebMessagePort\>): void
Sets the message port in this object.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ----- | ------ | ---- | ---- | ----------------- |
| ports | Array\<[WebMessagePort](#webmessageport9)\> | Yes | - | Message port.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
ports: WebMessagePort[] = null;
build() {
Column() {
Button('setPorts')
.onClick(() => {
var sendPortArray = new Array(this.ports[1]);
var msgEvent = new WebMessageEvent();
msgEvent.setData("__init_ports__");
msgEvent.setPorts(sendPortArray);
this.controller.postMessage({message: msgEvent, uri: "*"});
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
# XComponent # XComponent
> **NOTE** The **\<XComponent>** can accept and display the EGL/OpenGL ES and media data input.
>
> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. > **NOTE**
>
> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
The **\<XComponent>** can accept and display the EGL/OpenGL ES and media data input.
## Required Permissions ## Required Permissions
None None
## Child Components ## Child Components
Not supported Not supported
## APIs ## APIs
XComponent(value: {id: string, type: string, libraryname?: string, controller?: XComponentController}) XComponent(value: {id: string, type: string, libraryname?: string, controller?: XComponentController})
**Parameters** **Parameters**
......
...@@ -7,36 +7,27 @@ ...@@ -7,36 +7,27 @@
> This gesture is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > This gesture is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
None
## APIs ## APIs
LongPressGesture(options?: { fingers?: number, repeat?: boolean, duration?: number }) LongPressGesture(value?: { fingers?: number, repeat?: boolean, duration?: number })
- Parameters **Parameters**
| Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- | | Name| Type| Mandatory| Description|
| fingers | number | No| 1 | Minimum number of fingers to trigger a long press gesture. The value ranges from 1 to 10.| | -------- | -------- | -------- | -------- |
| repeat | boolean | No| false | Whether to continuously trigger the event callback.| | fingers | number | No| Minimum number of fingers to trigger a long press gesture. The value ranges from 1 to 10.<br>Default value: **1**|
| duration | number | No| 500 | Minimum hold-down time, in ms.| | repeat | boolean | No| Whether to continuously trigger the event callback.<br>Default value: **false**|
| duration | number | No| Minimum hold-down time, in ms.<br>Default value: **500**|
## Events ## Events
| Name| Description| | Name| Description|
| -------- | -------- | | -------- | -------- |
| onAction((event?: GestureEvent) =&gt; void) | Callback invoked when a long press gesture is recognized.| | onAction(event:(event?: [GestureEvent](ts-gesture-settings.md)) =&gt; void) | Callback invoked when a long press gesture is recognized.|
| onActionEnd((event?: GestureEvent) =&gt; void) | Callback invoked when the finger used for a long press gesture is lift.| | onActionEnd(event:(event?: [GestureEvent](ts-gesture-settings.md)) =&gt; void) | Callback invoked when the finger used for a long press gesture is lift.|
| onActionCancel(event: () =&gt; void) | Callback invoked when a tap cancellation event is received after a long press gesture is recognized.| | onActionCancel(event: () =&gt; void) | Callback invoked when a tap cancellation event is received after a long press gesture is recognized.|
- GestureEvent attributes related to the long press gesture
| Name| Type| Description|
| -------- | -------- | -------- |
| repeat | boolean | Whether the event is repeated.|
## Example ## Example
......
...@@ -7,67 +7,63 @@ ...@@ -7,67 +7,63 @@
> This gesture is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > This gesture is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions ## APIs
None
PanGesture(value?: { fingers?: number; direction?: PanDirection; distance?: number } | [PanGestureOptions](#pangestureoptions))
## APIs **Parameters**
PanGesture(options?: { fingers?: number, direction?: PanDirection, distance?: number } | [PanGestureOptions](#pangestureoptions)) | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| fingers | number | No| Minimum number of fingers to trigger a pan gesture. The value ranges from 1 to 10.<br>Default value: **1**|
| direction | PanDirection | No| Pan direction. The enumerated value supports the AND (&amp;) and OR (\|) operations.<br>Default value: **PanDirection.All**|
| distance | number | No| Minimum pan distance to trigger the gesture, in vp.<br>Default value: **5.0**<br>**NOTE**<br>If a pan gesture and tab swipe occur at the same time, set **distance** to **1** so that the gesture can be more easily recognized.|
- Parameters ## PanDirection enums
| Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- |
| fingers | number | No| 1 | Minimum number of fingers to trigger a pan gesture. The value ranges from 1 to 10.|
| direction | PanDirection | No| All | Pan direction. The enumerated value supports the AND (&amp;) and OR (\|)|operations.|
| distance | number | No| 5.0 | Minimum pan distance to trigger the gesture, in vp.<br>**NOTE**<br>If a pan gesture and tab swipe occur at the same time, set **distance** to **1** so that the gesture can be more easily recognized.|
- PanDirection enums | Name| Description|
| Name| Description| | -------- | -------- |
| -------- | -------- | | All | All directions.|
| All | All directions.| | Horizontal | Horizontal panning.|
| Horizontal | Horizontal panning.| | Vertical | Vertical panning.|
| Vertical | Vertical panning.| | Left | Panning to the left.|
| Left | Panning to the left.| | Right | Panning to the right.|
| Right | Panning to the right.| | Up | Panning up.|
| Up | Panning up.| | Down | Panning down.|
| Down | Panning down.| | None | Panning disabled.|
| None | Panning disabled.|
### PanGestureOptions ## PanGestureOptions
The attributes of the pan gesture recognizer can be dynamically modified using the **PanGestureOptions** API. This avoids modifying attributes through state variables, which will cause the UI to be refreshed. The attributes of the pan gesture recognizer can be dynamically modified using the **PanGestureOptions** API. This avoids modifying attributes through state variables, which will cause the UI to be refreshed.
PanGestureOptions(options?: { fingers?: number, direction?: PanDirection, distance?: number }) PanGestureOptions(value?: { fingers?: number; direction?: PanDirection; distance?: number })
- Parameters **Parameters**
For details, see **PanGesture**. | Name | Type | Mandatory| Description |
| --------- | ------------ | ---- | ------------------------------------------------------------ |
- APIs | fingers | number | No | Minimum number of fingers to trigger a pan gesture. The value ranges from 1 to 10.<br>Default value: **1**|
| Name| Description| | direction | PanDirection | No | Pan direction. The enumerated value supports the AND (&amp;) and OR (\|) operations.<br>Default value: **All**|
| -------- | -------- | | distance | number | No | Minimum pan distance to trigger the gesture, in vp.<br>Default value: **5.0**<br>**NOTE**<br>If a pan gesture and tab swipe occur at the same time, set **distance** to **1** so that the gesture can be more easily recognized.|
| setDirection(value: PanDirection) | Sets the direction.|
| setDistance(value: number) | Sets the distance.| **APIs**
| setFingers(value: number) | Sets the number of fingers.|
| Name| Description|
| -------- | -------- |
| setDirection(value: PanDirection) | Sets the direction.|
| setDistance(value: number) | Sets the distance.|
| setFingers(value: number) | Sets the number of fingers.|
## Events ## Events
| Name| Description| | Name| Description|
| -------- | -------- | | -------- | -------- |
| onActionStart(callback: (event?: GestureEvent) =&gt; void) | Callback invoked when a pan gesture is recognized.| | onActionStart(event: (event?: [GestureEvent](ts-gesture-settings.md)) =&gt; void) | Callback invoked when a pan gesture is recognized.|
| onActionUpdate(callback: (event?: GestureEvent) =&gt; void) | Callback invoked when the pan gesture status is updated.| | onActionUpdate(event: (event?: [GestureEvent](ts-gesture-settings.md)) =&gt; void) | Callback invoked when the pan gesture status is updated.|
| onActionEnd(callback: (event?: GestureEvent) =&gt; void) | Callback invoked when the finger used for a pan gesture is lift.| | onActionEnd(event: (event?: [GestureEvent](ts-gesture-settings.md)) =&gt; void) | Callback invoked when the finger used for a pan gesture is lift.|
| onActionCancel(callback: () =&gt; void) | Callback invoked when a tap cancellation event is received after a pan gesture is recognized.| | onActionCancel(event: () =&gt; void) | Callback invoked when a tap cancellation event is received after a pan gesture is recognized.|
- GestureEvent attributes related to the pan gesture
| Name| Type| Description|
| -------- | -------- | -------- |
| offsetX | number | Offset of the gesture event, in vp.|
| offsetY | number | Offset of the gesture event, in vp.|
## Example ## Example
......
# PinchGesture # PinchGesture
PinchGesture is used to trigger a pinch gesture, which requires two to five fingers with a minimum 3 vp distance between the fingers. **PinchGesture** is used to trigger a pinch gesture, which requires two to five fingers with a minimum 3 vp distance between the fingers.
> **NOTE** > **NOTE**
> >
> This gesture is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > This gesture is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
None
## APIs ## APIs
PinchGesture(options?: { fingers?: number, distance?: number }) PinchGesture(value?: { fingers?: number, distance?: number })
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- | | Name| Type| Mandatory| Description|
| fingers | number | No | 2 | Minimum number of fingers to trigger a pinch. The value ranges from 2 to 5. | | -------- | -------- | -------- | -------- |
| distance | number | No | 3.0 | Minimum recognition distance, in vp. | | fingers | number | No| Minimum number of fingers to trigger a pinch. The value ranges from 2 to 5.<br>Default value: **2**|
| distance | number | No| Minimum recognition distance, in vp.<br>Default value: **3.0**|
## Events ## Events
| Name | Description | | Name| Description|
| -------- | -------- | | -------- | -------- |
| onActionStart((event?: GestureEvent) =&gt; void) | Callback invoked when a pinch gesture is recognized. | | onActionStart(event:(event?: [GestureEvent](ts-gesture-settings.md)) =&gt; void) | Triggered when a pinch gesture is recognized.|
| onActionUpdate((event?: GestureEvent) =&gt; void) | Callback invoked during the movement of a pinch gesture. | | onActionUpdate(event:(event?: [GestureEvent](ts-gesture-settings.md)) =&gt; void) | Triggered when the user moves the finger in a pinch gesture on the screen.|
| onActionEnd((event?: GestureEvent) =&gt; void) | Callback invoked when the finger used for a pinch gesture is lift. | | onActionEnd(event:(event?: [GestureEvent](ts-gesture-settings.md)) =&gt; void) | Triggered when the finger used for a pinch gesture is lift.|
| onActionCancel(event: () =&gt; void) | Callback invoked when a tap cancellation event is received after a pinch gesture is recognized. | | onActionCancel(event: () =&gt; void) | Triggered when a tap cancellation event is received after a pinch gesture is recognized.|
- GestureEvent attributes related to the pinch gesture
| Name | Type | Description |
| -------- | -------- | -------- |
| scale | number | Scale ratio. This attribute is used for the pinch gesture. |
| pinchCenterX | number | X-coordinate of the center of the pinch gesture, in px. |
| pinchCenterY | number | Y-coordinate of the center of the pinch gesture, in px. |
## Example ## Example
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
......
# RotationGesture # RotationGesture
**RotationGesture** is used to trigger a rotation gesture, which requires two to five fingers with a minimum 1-degree rotation angle.
> **NOTE**<br> > **NOTE**
> This gesture is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. >
> This gesture is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
None
## APIs ## APIs
RotationGesture(options?: { fingers?: number, angle?: number }) RotationGesture(value?: { fingers?: number, angle?: number })
**Parameters**
- Parameters | Name| Type| Mandatory| Description|
| Name | Type | Mandatory | Default Value | Description | | -------- | -------- | -------- | -------- |
| -------- | -------- | -------- | -------- | -------- | | fingers | number | No| Minimum number of fingers to trigger a rotation. The value ranges from 2 to 5.<br>Default value: **2**|
| fingers | number | No | 2 | Minimum number of fingers to trigger a rotation. The value ranges from 2 to 5. | | angle | number | No| Minimum degree that can trigger the rotation gesture.<br>Default value: **1.0**|
| angle | number | No | 1.0 | Minimum degree that can trigger the rotation gesture. |
## Events ## Events
| Name | Description | | Parameter| Description|
| -------- | -------- | | -------- | -------- |
| onActionStart((event?: GestureEvent) =&gt; void) | Callback invoked when a rotation gesture is recognized. | | onActionStart(event:(event?: [GestureEvent](ts-gesture-settings.md)) =&gt; void) | Triggered when a rotation gesture is recognized.|
| onActionUpdate((event?: GestureEvent) =&gt; void) | Callback invoked during the movement of the rotation gesture. | | onActionUpdate(event:(event?: [GestureEvent](ts-gesture-settings.md)) =&gt; void) | Triggered when the user moves the finger in a rotation gesture on the screen.|
| onActionEnd((event?: GestureEvent) =&gt; void) | Callback invoked when the finger used for the rotation gesture is lift. | | onActionEnd(event:(event?: [GestureEvent](ts-gesture-settings.md)) =&gt; void) | Triggered when the finger used for the rotation gesture is lift.|
| onActionCancel(event: () =&gt; void) | Callback invoked when a tap cancellation event is received after the rotation gesture is recognized. | | onActionCancel(event: () =&gt; void) | Triggered when a tap cancellation event is received after the rotation gesture is recognized.|
- GestureEvent attributes related to the rotation gesture
| Name | Type | Description |
| -------- | -------- | -------- |
| angle | number | Rotation angle. |
## Example ## Example
```ts
``` // xxx.ets
@Entry @Entry
@Component @Component
struct RotationGestureExample { struct RotationGestureExample {
......
...@@ -2,54 +2,44 @@ ...@@ -2,54 +2,44 @@
**\<SwipeGesture>** is used to implement a swipe gesture, which can be recognized when the swipe speed is 100 vp/s or higher. **\<SwipeGesture>** is used to implement a swipe gesture, which can be recognized when the swipe speed is 100 vp/s or higher.
> **NOTE** > **NOTE**
> >
> This gesture is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. > This gesture is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
None
## APIs ## APIs
SwipeGesture(value?: { fingers?: number; direction?: SwipeDirection; speed?: number }) SwipeGesture(value?: { fingers?: number; direction?: SwipeDirection; speed?: number })
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| fingers | number | No | 1 | Minimum number of fingers to trigger a swipe gesture. The value ranges from 1 to 10. |
| direction | SwipeDirection | No | SwipeDirection.All | Swipe direction. |
| speed | number | No | 100 | Minimum speed of the swipe gesture (100 vp/s). |
- SwipeDirection enums | Name| Type| Mandatory| Description|
| Name | Description | | -------- | -------- | -------- | -------- |
| -------- | -------- | | fingers | number | No| Minimum number of fingers to trigger a swipe gesture. The value ranges from 1 to 10.<br>Default value: **1**|
| All | All directions. | | direction | SwipeDirection | No| Swipe direction.<br>Default value: **SwipeDirection.All**|
| Horizontal | Horizontal direction. | | speed | number | No| Minimum speed of the swipe gesture, in vp/s.<br>Default value: **100**|
| Vertical | Vertical direction. |
## SwipeDirection
## Events | Name| Description|
| Name | Description |
| -------- | -------- | | -------- | -------- |
| onAction(callback:(event?: GestureEvent) =&gt; void) | Invoked when a swipe gesture is recognized. | | All | All directions.|
| Horizontal | Horizontal direction.|
| Vertical | Vertical direction.|
| None | Swiping disabled.|
- GestureEvent attributes related to the swipe gesture ## Events
| Name | Type | Description |
| -------- | -------- | -------- |
| angle | number | Angle of the swipe gesture.<br/>**NOTE**<br/>Angle calculation method: After a swipe gesture is recognized, a line connecting the two fingers is identified as the initial line. As the fingers swipe, the line between the fingers rotates. Based on the coordinates of the initial line's and current line's end points, an arc tangent function is used to calculate the respective included angle of the points relative to the horizontal direction. Rotation angle = arctan2(cy2-cy1,cx2-cx1) - arctan2(y2-y1,x2-x1). The initial line is used as the coordinate system. The clockwise rotation is 0 to 180 degrees, and the counter-clockwise rotation is –180 to 0 degrees. |
| speed | number | Speed of the swipe gesture. |
![en-us_image_0000001231374559](figures/en-us_image_0000001231374661.png) | Name| Description|
| -------- | -------- |
| onAction(event:(event?: [GestureEvent](ts-gesture-settings.md)) =&gt; void) | Triggered when a swipe gesture is recognized.|
![en-us_image_0000001231374661](figures/en-us_image_0000001231374661.png)
## Example ## Example
```ts
``` // xxx.ets
@Entry @Entry
@Component @Component
struct SwipeGestureExample { struct SwipeGestureExample {
...@@ -66,7 +56,7 @@ struct SwipeGestureExample { ...@@ -66,7 +56,7 @@ struct SwipeGestureExample {
.width(260).height(260) .width(260).height(260)
.rotate({x: 0, y: 0, z: 1, angle: this.rotateAngle}) .rotate({x: 0, y: 0, z: 1, angle: this.rotateAngle})
.gesture( .gesture(
SwipeGesture({fingers: 1, direction:SwipeDirection.Vertical}) SwipeGesture({fingers: 1, direction: SwipeDirection.Vertical})
.onAction((event: GestureEvent) => { .onAction((event: GestureEvent) => {
this.speed = event.speed this.speed = event.speed
this.rotateAngle = event.angle this.rotateAngle = event.angle
......
# TapGesture # TapGesture
A tap gesture can recognize one or more taps. **TapGesture** is used to trigger a tap gesture with one or more taps.
> **NOTE** > **NOTE**
> >
> This gesture is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > This gesture is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
None
## APIs ## APIs
TapGesture(options?: { count?: number, fingers?: number }) TapGesture(value?: { count?: number, fingers?: number })
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- | | Name| Type| Mandatory| Description|
| count | number | No | 1 | Number of consecutive taps. If this parameter is set to a value less than **1**, the default value will be used.<br/>> **NOTE**<br/>> If multi-tap is configured, the timeout interval between a lift and the next tap is 300 ms. | | -------- | -------- | -------- | -------- |
| fingers | number | No | 1 | Minimum number of fingers to trigger a tap. The value ranges from 1 to 10.<br/>> **NOTE**<br/>> 1. When multi-finger is configured, if the number of fingers used for tap does not reach the specified number within 300 ms after the first finger is tapped, the gesture fails to be recognized.<br/>> 2. Gesture recognition fails if the number of fingers used for tap exceeds the configured number. | | count | number | No| Number of consecutive taps. If this parameter is set to a value less than **1**, the default value will be used.<br>Default value: **1**<br>> **NOTE**<br>> If multi-tap is configured, the timeout interval between a lift and the next tap is 300 ms.|
| fingers | number | No| Minimum number of fingers to trigger a tap. The value ranges from 1 to 10.<br>Default value: **1**<br>> **NOTE**<br>> 1. When multi-finger is configured, the gesture will fail to be recognized if the number of fingers used for tapping is less than the configured number within 300 ms after the first finger is tapped.<br>> 2. The gesture will fail to be recognized if the number of fingers used for tapping exceeds the configured number.|
## Events ## Events
| Name | Description | | Name| Description|
| -------- | -------- | | -------- | -------- |
| onAction((event?:&nbsp;[GestureEvent](ts-gesture-settings.md))&nbsp;=&gt;&nbsp;void) | Callback invoked when a tap gesture is recognized. | | onAction(event: (event?: [GestureEvent](ts-gesture-settings.md)) =&gt; void) | Callback invoked when a tap gesture is recognized.|
## Example ## Example
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
......
# CanvasRenderingContext2D # CanvasRenderingContext2D
Use **RenderingContext** to draw rectangles, text, images, and other objects on a canvas.
The **\<RenderingContext>** component is used to draw rectangles, text, images, and other objects on a canvas.
> **NOTE** > **NOTE**
> >
> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. > The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
## APIs ## APIs
CanvasRenderingContext2D(setting: RenderingContextSetting) CanvasRenderingContext2D(setting: RenderingContextSetting)
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ------- | ---------------------------------------- | --------- | ------------- | ----------------------------- | | Name | Type | Mandatory | Description |
| setting | [RenderingContextSettings](#renderingcontextsettings) | Yes | - | See [RenderingContextSettings](#renderingcontextsettings). | | ------- | ---------------------------------------- | ---- | ---------------------------------------- |
| setting | [RenderingContextSettings](#renderingcontextsettings) | Yes | See [RenderingContextSettings](#renderingcontextsettings).|
### RenderingContextSettings ### RenderingContextSettings
...@@ -23,37 +23,38 @@ RenderingContextSettings(antialias?: boolean) ...@@ -23,37 +23,38 @@ RenderingContextSettings(antialias?: boolean)
Configures the settings of a **CanvasRenderingContext2D** object, including whether to enable antialiasing. Configures the settings of a **CanvasRenderingContext2D** object, including whether to enable antialiasing.
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| --------- | ---- | --------- | ------------- | -------------------------------- | | Name | Type | Mandatory | Description |
| antialias | boolean | No | false | Whether antialiasing is enabled. | | --------- | ------- | ---- | ----------------------------- |
| antialias | boolean | No | Whether antialiasing is enabled.<br>Default value: **false**|
## Attributes ## Attributes
| Name | Type | Default Value | Description | | Name | Type | Description |
| ---------------------------------------- | ---------------------------------------- | ------------------------------- | ---------------------------------------- | | ---------------------------------------- | ---------------------------------------- | ---------------------------------------- |
| [fillStyle](#fillstyle) | &lt;color&gt; \| [CanvasGradient](ts-components-canvas-canvasgradient.md) \| [CanvasPattern](#canvaspattern) | - | Style used to fill an area.<br>- When the type is **&lt;color&gt;**, this attribute indicates the fill color.<br>- When the type is **CanvasGradient**, this attribute indicates a gradient object, which is created using the [createLinearGradient](#createlineargradient) method.<br>- When the type is **CanvasPattern**, this attribute indicates a pattern, which is created using the [createPattern](#createpattern) method. | | [fillStyle](#fillstyle) | string \| [CanvasGradient](ts-components-canvas-canvasgradient.md) \| [CanvasPattern](#canvaspattern) | Style to fill an area.<br>- When the type is string, this attribute indicates the color of the fill area.<br>- When the type is **CanvasGradient**, this attribute indicates a gradient object, which is created using the **[createLinearGradient](#createlineargradient)** API.<br>- When the type is **CanvasPattern**, this attribute indicates a pattern, which is created using the **[createPattern](#createpattern)** API.|
| [lineWidth](#linewidth) | number | - | Line width. | | [lineWidth](#linewidth) | number | Line width. |
| [strokeStyle](#strokestyle) | &lt;color&gt; \| [CanvasGradient](ts-components-canvas-canvasgradient.md) \| [CanvasPattern](#canvaspattern) | - | Stroke style.<br>- When the type is **&lt;color&gt;**, this attribute indicates the stroke color.<br>- When the type is **CanvasGradient**, this attribute indicates a gradient object, which is created using the [createLinearGradient](#createlineargradient) method.<br>- When the type is **CanvasPattern**, this attribute indicates a pattern, which is created using the [createPattern](#createpattern) method. | | [strokeStyle](#strokestyle) | string \| [CanvasGradient](ts-components-canvas-canvasgradient.md) \| [CanvasPattern](#canvaspattern) | Stroke style.<br>- When the type is string, this attribute indicates the stroke color.<br>- When the type is **CanvasGradient**, this attribute indicates a gradient object, which is created using the **[createLinearGradient](#createlineargradient)** API.<br>- When the type is **CanvasPattern**, this attribute indicates a pattern, which is created using the **[createPattern](#createpattern)** API.|
| [lineCap](#linecap) | string | 'butt' | Style of the line endpoints. The options are as follows:<br>- **'butt'**: The endpoints of the line are squared off.<br>- **'round'**: The endpoints of the line are rounded.<br>- **'square'**: The endpoints of the line are squared off by adding a box with an equal width and half the height of the line's thickness. | | [lineCap](#linecap) | CanvasLineCap | Style of the line endpoints. The options are as follows:<br>- **'butt'**: The endpoints of the line are squared off.<br>- **'round'**: The endpoints of the line are rounded.<br>- **'square'**: The endpoints of the line are squared off by adding a box with an equal width and half the height of the line's thickness.<br>Default value: **'butt'**|
| [lineJoin](#linejoin) | string | 'miter' | Style of the shape used to join line segments. The options are as follows:<br>- **'round'**: The shape used to join line segments is a rounded corner with the radius equal to the line width.<br>- **'bevel'**: The shape used to join line segments is a beveled corner. The rectangular corner of each line is independent.<br>- **'miter'**: The shape used to join line segments is a mitered corner. The corner is formed by extending the outside edges of the lines until they meet. You can adjust the effect of this attribute using **miterLimit**. | | [lineJoin](#linejoin) | CanvasLineJoin | Style of the shape used to join line segments. The options are as follows:<br>- **'round'**: The shape used to join line segments is a sector, whose radius at the rounded corner is equal to the line width.<br>- **'bevel'**: The shape used to join line segments is a triangle. The rectangular corner of each line is independent.<br>- **'miter'**: The shape used to join line segments has a mitered corner by extending the outside edges of the lines until they meet. You can view the effect of this attribute in **miterLimit**.<br>Default value: **'miter'**|
| [miterLimit](#miterlimit) | number | 10 | Maximum miter length. The miter length is the distance between the inner corner and the outer corner where two lines meet. | | [miterLimit](#miterlimit) | number | Maximum miter length. The miter length is the distance between the inner corner and the outer corner where two lines meet.<br>Default value: **10**|
| [font](#font) | string | 'normal normal 14px sans-serif' | Font style.<br>Syntax: ctx.font='font-size font-family'<br>- (Optional) **font-size**: font size and row height. The unit can only be px.<br>- (Optional) **font-family**: font family.<br>Syntax: ctx.font='font-style font-weight font-size font-family'<br>- (Optional) **font-style**: font style. Available values are **'normal'** and **'italic'**.<br>- (Optional) **font-weight**: font weight. Available values are as follows: **'normal'**, **'bold'**, **'bolder'**, **'lighter'**, **100**, **200**, **300**, **400**, **500**, **600**, **700**, **800**, **900**<br>- (Optional) **font-size**: font size and row height. The unit can only be px.<br>- (Optional) **font-family**: font family. Available values are **'sans-serif'**, **'serif'**, and **'monospace'**. | | [font](#font) | string | Font style.<br>Syntax: ctx.font='font-size font-family'<br>- (Optional) **font-size**: font size and row height. The unit can only be pixels.<br>- (Optional) **font-family**: font family.<br>Syntax: ctx.font='font-style font-weight font-size font-family'<br>- (Optional) **font-style**: font style. Available values are **'normal'** and **'italic'**.<br>- (Optional) **font-weight**: font weight. Available values are as follows: **'normal'**, **'bold'**, **'bolder'**, **'lighter'**, **'100'**, **'200'**, **'300'**, **'400'**, **'500'**, **'600'**, **'700'**, **'800'**, **'900'**.<br>- (Optional) **font-size**: font size and row height. The unit can only be pixels.<br>- (Optional) **font-family**: font family. Available values are **'sans-serif'**, **'serif'**, and **'monospace'**.<br>Default value: **'normal normal 14px sans-serif'**|
| [textAlign](#textalign) | string | 'left' | Text alignment mode. Available values are as follows:<br>- **'left'**: The text is left-aligned.<br>- **'right'**: The text is right-aligned.<br>- **'center'**: The text is center-aligned.<br>- **'start'**: The text is aligned with the start bound.<br>- **'end'**: The text is aligned with the end bound.<br>**NOTE**<br>In the **ltr** layout mode, the value **'start'** equals **'left'**. In the **rtl** layout mode, the value **'start'** equals **'right'**. | | [textAlign](#textalign) | CanvasTextAlign | Text alignment mode. Available values are as follows:<br>- **'left'**: The text is left-aligned.<br>- **'right'**: The text is right-aligned.<br>- **'center'**: The text is center-aligned.<br>- **'start'**: The text is aligned with the start bound.<br>- **'end'**: The text is aligned with the end bound.<br>In the **ltr** layout mode, the value **'start'** equals **'left'**. In the **rtl** layout mode, the value **'start'** equals **'right'**.<br>Default value: **'left'**|
| [textBaseline](#textbaseline) | string | 'alphabetic' | Horizontal alignment mode of text. Available values are as follows:<br>- **'alphabetic'**: The text baseline is the normal alphabetic baseline.<br>- **'top'**: The text baseline is on the top of the text bounding box.<br>- **'hanging'**: The text baseline is a hanging baseline over the text.<br>- **'middle'**: The text baseline is in the middle of the text bounding box.<br>- **'ideographic'**: The text baseline is the ideographic baseline. If a character exceeds the alphabetic baseline, the ideographic baseline is located at the bottom of the excess character.<br>- **'bottom'**: The text baseline is at the bottom of the text bounding box. Its difference from the ideographic baseline is that the ideographic baseline does not consider letters in the next line. | | [textBaseline](#textbaseline) | CanvasTextBaseline | Horizontal alignment mode of text. Available values are as follows:<br>- **'alphabetic'**: The text baseline is the normal alphabetic baseline.<br>- **'top'**: The text baseline is on the top of the text bounding box.<br>- **'hanging'**: The text baseline is a hanging baseline over the text.<br>- **'middle'**: The text baseline is in the middle of the text bounding box.<br>**'ideographic'**: The text baseline is the ideographic baseline. If a character exceeds the alphabetic baseline, the ideographic baseline is located at the bottom of the excess character.<br>- **'bottom'**: The text baseline is at the bottom of the text bounding box. Its difference from the ideographic baseline is that the ideographic baseline does not consider letters in the next line.<br>Default value: **'alphabetic'**|
| [globalAlpha](#globalalpha) | number | - | Opacity. **0.0**: completely transparent; **1.0**: completely opaque. | | [globalAlpha](#globalalpha) | number | Opacity.<br>**0.0**: completely transparent.<br>**1.0**: completely opaque. |
| [lineDashOffset](#linedashoffset) | number | 0.0 | Offset of the dashed line. The precision is float. | | [lineDashOffset](#linedashoffset) | number | Offset of the dashed line. The precision is float.<br>Default value: **0.0** |
| [globalCompositeOperation](#globalcompositeoperation) | string | 'source-over' | Composition operation type. Available values are as follows: **'source-over'**, **'source-atop'**, **'source-in'**, **'source-out'**, **'destination-over'**, **'destination-atop'**, **'destination-in'**, **'destination-out'**, **'lighter'**, **'copy'**, and **'xor'**. | | [globalCompositeOperation](#globalcompositeoperation) | string | Composition operation type. Available values are as follows: **'source-over'**, **'source-atop'**, **'source-in'**, **'source-out'**, **'destination-over'**, **'destination-atop'**, **'destination-in'**, **'destination-out'**, **'lighter'**, **'copy'**, and **'xor'**.<br>Default value: **'source-over'**|
| [shadowBlur](#shadowblur) | number | 0.0 | Blur level during shadow drawing. A larger value indicates a more blurred effect. The precision is float. | | [shadowBlur](#shadowblur) | number | Blur level during shadow drawing. A larger value indicates a more blurred effect. The precision is float.<br>Default value: **0.0**|
| [shadowColor](#shadowcolor) | &lt;color&gt; | - | Shadow color. | | [shadowColor](#shadowcolor) | string | Shadow color. |
| [shadowOffsetX](#shadowoffsetx) | number | - | X-axis shadow offset relative to the original object. | | [shadowOffsetX](#shadowoffsetx) | number | X-axis shadow offset relative to the original object. |
| [shadowOffsetY](#shadowoffsety) | number | - | Y-axis shadow offset relative to the original object. | | [shadowOffsetY](#shadowoffsety) | number | Y-axis shadow offset relative to the original object. |
| [imageSmoothingEnabled](#imagesmoothingenabled) | boolean | true | Whether to adjust the image smoothness during image drawing. The value **true** means to enable this feature, and **false** means the opposite. | | [imageSmoothingEnabled](#imagesmoothingenabled) | boolean | Whether to adjust the image smoothness during image drawing. The value **true** means to enable this feature, and **false** means the opposite.<br>Default value: **true**|
| imageSmoothingQuality | string | 'low' | Image smoothness. The value can be **'low'**, **'medium'**, or **'high'**. |
> **NOTE**
> **NOTE**<br> >
> The value of the **&lt;color&gt;** type can be in 'rgb(255, 255, 255)', 'rgba(255, 255, 255, 1.0)', or '\#FFFFFF' format. > The string-type value of **fillStyle**, **shadowColor**, and **strokeStyle** can be in 'rgb(255, 255, 255)', 'rgba(255, 255, 255, 1.0)', or '\#FFFFFF' format.
### fillStyle ### fillStyle
...@@ -63,8 +64,8 @@ Configures the settings of a **CanvasRenderingContext2D** object, including whet ...@@ -63,8 +64,8 @@ Configures the settings of a **CanvasRenderingContext2D** object, including whet
@Entry @Entry
@Component @Component
struct FillStyleExample { struct FillStyleExample {
private settings: RenderingContextSettings = new RenderingContextSettings(true) private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -93,8 +94,8 @@ struct FillStyleExample { ...@@ -93,8 +94,8 @@ struct FillStyleExample {
@Entry @Entry
@Component @Component
struct LineWidthExample { struct LineWidthExample {
private settings: RenderingContextSettings = new RenderingContextSettings(true) private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -123,8 +124,8 @@ struct LineWidthExample { ...@@ -123,8 +124,8 @@ struct LineWidthExample {
@Entry @Entry
@Component @Component
struct StrokeStyleExample { struct StrokeStyleExample {
private settings: RenderingContextSettings = new RenderingContextSettings(true) private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -155,8 +156,8 @@ struct StrokeStyleExample { ...@@ -155,8 +156,8 @@ struct StrokeStyleExample {
@Entry @Entry
@Component @Component
struct LineCapExample { struct LineCapExample {
private settings: RenderingContextSettings = new RenderingContextSettings(true) private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -189,8 +190,8 @@ struct LineCapExample { ...@@ -189,8 +190,8 @@ struct LineCapExample {
@Entry @Entry
@Component @Component
struct LineJoinExample { struct LineJoinExample {
private settings: RenderingContextSettings = new RenderingContextSettings(true) private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -224,8 +225,8 @@ struct LineJoinExample { ...@@ -224,8 +225,8 @@ struct LineJoinExample {
@Entry @Entry
@Component @Component
struct MiterLimit { struct MiterLimit {
private settings: RenderingContextSettings = new RenderingContextSettings(true) private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -259,8 +260,8 @@ struct MiterLimit { ...@@ -259,8 +260,8 @@ struct MiterLimit {
@Entry @Entry
@Component @Component
struct Fonts { struct Fonts {
private settings: RenderingContextSettings = new RenderingContextSettings(true) private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -289,8 +290,8 @@ struct Fonts { ...@@ -289,8 +290,8 @@ struct Fonts {
@Entry @Entry
@Component @Component
struct CanvasExample { struct CanvasExample {
private settings: RenderingContextSettings = new RenderingContextSettings(true) private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -334,8 +335,8 @@ struct CanvasExample { ...@@ -334,8 +335,8 @@ struct CanvasExample {
@Entry @Entry
@Component @Component
struct TextBaseline { struct TextBaseline {
private settings: RenderingContextSettings = new RenderingContextSettings(true) private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -379,8 +380,8 @@ struct TextBaseline { ...@@ -379,8 +380,8 @@ struct TextBaseline {
@Entry @Entry
@Component @Component
struct GlobalAlpha { struct GlobalAlpha {
private settings: RenderingContextSettings = new RenderingContextSettings(true) private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -402,7 +403,7 @@ struct GlobalAlpha { ...@@ -402,7 +403,7 @@ struct GlobalAlpha {
} }
``` ```
![en-us_image_0000001212218444](figures/en-us_image_0000001212218444.png) ![en-us_image_0000001194192434](figures/en-us_image_0000001194192434.png)
### lineDashOffset ### lineDashOffset
...@@ -412,8 +413,8 @@ struct GlobalAlpha { ...@@ -412,8 +413,8 @@ struct GlobalAlpha {
@Entry @Entry
@Component @Component
struct LineDashOffset { struct LineDashOffset {
private settings: RenderingContextSettings = new RenderingContextSettings(true) private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -424,6 +425,7 @@ struct LineDashOffset { ...@@ -424,6 +425,7 @@ struct LineDashOffset {
.onReady(() =>{ .onReady(() =>{
this.context.arc(100, 75, 50, 0, 6.28) this.context.arc(100, 75, 50, 0, 6.28)
this.context.setLineDash([10,20]) this.context.setLineDash([10,20])
this.context.lineDashOffset = 10.0;
this.context.stroke(); this.context.stroke();
}) })
} }
...@@ -433,32 +435,32 @@ struct LineDashOffset { ...@@ -433,32 +435,32 @@ struct LineDashOffset {
} }
``` ```
![en-us_image_0000001212058480](figures/en-us_image_0000001212058480.png) ![en-us_image_0000001194352434](figures/en-us_image_0000001194352434.png)
### globalCompositeOperation ### globalCompositeOperation
| Name | Description | | Name | Description |
| ---------------- | ---------------------------------------- | | ---------------- | ------------------------ |
| source-over | Displays the new drawing above the existing drawing. This attribute is used by default. | | source-over | Displays the new drawing above the existing drawing. This attribute is used by default. |
| source-atop | Displays the new drawing on the top of the existing drawing. | | source-atop | Displays the new drawing on the top of the existing drawing. |
| source-in | Displays the new drawing inside the existing drawing. | | source-in | Displays the new drawing inside the existing drawing. |
| source-out | Displays the part of the new drawing that is outside of the existing drawing. | | source-out | Displays part of the new drawing that is outside of the existing drawing. |
| destination-over | Displays the existing drawing above the new drawing. | | destination-over | Displays the existing drawing above the new drawing. |
| destination-atop | Displays the existing drawing on the top of the new drawing. | | destination-atop | Displays the existing drawing on the top of the new drawing. |
| destination-in | Displays the existing drawing inside the new drawing. | | destination-in | Displays the existing drawing inside the new drawing. |
| destination-out | Displays the part of the existing drawing that is outside of the new drawing. | | destination-out | Displays the existing drawing outside the new drawing. |
| lighter | Displays both the new drawing and the existing drawing. | | lighter | Displays both the new and existing drawing. |
| copy | Displays the new drawing and neglects the existing drawing. | | copy | Displays the new drawing and neglects the existing drawing. |
| xor | Combines the new drawing and existing drawing using the XOR operation. | | xor | Combines the new drawing and existing drawing using the XOR operation.|
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
@Component @Component
struct GlobalCompositeOperation { struct GlobalCompositeOperation {
private settings: RenderingContextSettings = new RenderingContextSettings(true) private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -527,8 +529,8 @@ struct ShadowBlur { ...@@ -527,8 +529,8 @@ struct ShadowBlur {
@Entry @Entry
@Component @Component
struct ShadowColor { struct ShadowColor {
private settings: RenderingContextSettings = new RenderingContextSettings(true) private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -559,8 +561,8 @@ struct ShadowColor { ...@@ -559,8 +561,8 @@ struct ShadowColor {
@Entry @Entry
@Component @Component
struct ShadowOffsetX { struct ShadowOffsetX {
private settings: RenderingContextSettings = new RenderingContextSettings(true) private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -592,8 +594,8 @@ struct ShadowOffsetX { ...@@ -592,8 +594,8 @@ struct ShadowOffsetX {
@Entry @Entry
@Component @Component
struct ShadowOffsetY { struct ShadowOffsetY {
private settings: RenderingContextSettings = new RenderingContextSettings(true) private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context) Canvas(this.context)
...@@ -624,9 +626,9 @@ struct ShadowOffsetY { ...@@ -624,9 +626,9 @@ struct ShadowOffsetY {
@Entry @Entry
@Component @Component
struct ImageSmoothingEnabled { struct ImageSmoothingEnabled {
private settings: RenderingContextSettings = new RenderingContextSettings(true) private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
private img:ImageBitmap = new ImageBitmap("common/images/icon.jpg") private img:ImageBitmap = new ImageBitmap("common/images/icon.jpg");
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -657,23 +659,24 @@ fillRect(x: number, y: number, w: number, h: number): void ...@@ -657,23 +659,24 @@ fillRect(x: number, y: number, w: number, h: number): void
Fills a rectangle on the canvas. Fills a rectangle on the canvas.
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ------ | ------ | --------- | ------------- | ---------------------------------------- | | Name | Type | Mandatory | Default Value | Description |
| x | number | Yes | 0 | X-coordinate of the upper left corner of the rectangle. | | ------ | ------ | ---- | ---- | ------------- |
| y | number | Yes | 0 | Y-coordinate of the upper left corner of the rectangle. | | x | number | Yes | 0 | X-coordinate of the upper left corner of the rectangle.|
| width | number | Yes | 0 | Width of the rectangle. | | y | number | Yes | 0 | Y-coordinate of the upper left corner of the rectangle.|
| height | number | Yes | 0 | Height of the rectangle. | | width | number | Yes | 0 | Width of the rectangle. |
| height | number | Yes | 0 | Height of the rectangle. |
- Example **Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
@Component @Component
struct FillRect { struct FillRect {
private settings: RenderingContextSettings = new RenderingContextSettings(true) private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -700,23 +703,24 @@ strokeRect(x: number, y: number, w: number, h: number): void ...@@ -700,23 +703,24 @@ strokeRect(x: number, y: number, w: number, h: number): void
Draws an outlined rectangle on the canvas. Draws an outlined rectangle on the canvas.
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ------ | ------ | --------- | ------------- | ---------------------------------------- | | Name | Type | Mandatory | Default Value | Description |
| x | number | Yes | 0 | X-coordinate of the upper left corner of the rectangle. | | ---- | ------ | ---- | ---- | ------------ |
| y | number | Yes | 0 | Y-coordinate of the upper left corner of the rectangle. | | x | number | Yes | 0 | X-coordinate of the upper left corner of the rectangle.|
| width | number | Yes | 0 | Width of the rectangle. | | y | number | Yes | 0 | Y-coordinate of the upper left corner of the rectangle.|
| height | number | Yes | 0 | Height of the rectangle. | | w | number | Yes | 0 | Width of the rectangle. |
| h | number | Yes | 0 | Height of the rectangle. |
- Example **Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
@Component @Component
struct StrokeRect { struct StrokeRect {
private settings: RenderingContextSettings = new RenderingContextSettings(true) private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context) Canvas(this.context)
...@@ -742,23 +746,24 @@ clearRect(x: number, y: number, w: number, h: number): void ...@@ -742,23 +746,24 @@ clearRect(x: number, y: number, w: number, h: number): void
Clears the content in a rectangle on the canvas. Clears the content in a rectangle on the canvas.
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ------ | ------ | --------- | ------------- | ---------------------------------------- | | Name | Type | Mandatory | Default Value | Description |
| x | number | Yes | 0 | X-coordinate of the upper left corner of the rectangle. | | ---- | ------ | ---- | ---- | ------------- |
| y | number | Yes | 0 | Y-coordinate of the upper left corner of the rectangle. | | x | number | Yes | 0 | X-coordinate of the upper left corner of the rectangle.|
| width | number | Yes | 0 | Width of the rectangle. | | y | number | Yes | 0 | Y-coordinate of the upper left corner of the rectangle.|
| height | number | Yes | 0 | Height of the rectangle. | | w | number | Yes | 0 | Width of the rectangle. |
| h | number | Yes | 0 | Height of the rectangle. |
- Example **Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
@Component @Component
struct ClearRect { struct ClearRect {
private settings: RenderingContextSettings = new RenderingContextSettings(true) private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context) Canvas(this.context)
...@@ -782,26 +787,28 @@ Clears the content in a rectangle on the canvas. ...@@ -782,26 +787,28 @@ Clears the content in a rectangle on the canvas.
### fillText ### fillText
fillText(text: string, x: number, y: number): void fillText(text: string, x: number, y: number, maxWidth?: number): void
Draws filled text on the canvas. Draws filled text on the canvas.
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ---- | ------ | --------- | ------------- | ---------------------------------------- | | Name | Type | Mandatory | Default Value | Description |
| text | string | Yes | "" | Text to draw. | | -------- | ------ | ---- | ---- | --------------- |
| x | number | Yes | 0 | X-coordinate of the lower left corner of the text. | | text | string | Yes | "" | Text to draw. |
| y | number | Yes | 0 | Y-coordinate of the lower left corner of the text. | | x | number | Yes | 0 | X-coordinate of the lower left corner of the text.|
| y | number | Yes | 0 | Y-coordinate of the lower left corner of the text.|
| maxWidth | number | No | - | Maximum width allowed for the text. |
- Example **Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
@Component @Component
struct FillText { struct FillText {
private settings: RenderingContextSettings = new RenderingContextSettings(true) private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context) Canvas(this.context)
...@@ -824,26 +831,28 @@ Draws filled text on the canvas. ...@@ -824,26 +831,28 @@ Draws filled text on the canvas.
### strokeText ### strokeText
strokeText(text: string, x: number, y: number): void strokeText(text: string, x: number, y: number, maxWidth?:number): void
Draws a text stroke on the canvas. Draws a text stroke on the canvas.
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ---- | ------ | --------- | ------------- | ---------------------------------------- | | Name | Type | Mandatory | Default Value | Description |
| text | string | Yes | "" | Text to draw. | | -------- | ------ | ---- | ---- | --------------- |
| x | number | Yes | 0 | X-coordinate of the lower left corner of the text. | | text | string | Yes | "" | Text to draw. |
| y | number | Yes | 0 | Y-coordinate of the lower left corner of the text. | | x | number | Yes | 0 | X-coordinate of the lower left corner of the text.|
| y | number | Yes | 0 | Y-coordinate of the lower left corner of the text.|
| maxWidth | number | No | - | Maximum width of the text to be drawn. |
- Example **Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
@Component @Component
struct StrokeText { struct StrokeText {
private settings: RenderingContextSettings = new RenderingContextSettings(true) private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context) Canvas(this.context)
...@@ -868,32 +877,50 @@ Draws a text stroke on the canvas. ...@@ -868,32 +877,50 @@ Draws a text stroke on the canvas.
measureText(text: string): TextMetrics measureText(text: string): TextMetrics
Returns a **TextMetrics** object used to obtain the width of specified text. Measures the specified text to obtain its width. This API returns a **TextMetrics** object.
**Parameters**
- Parameters | Name | Type | Mandatory | Default Value | Description |
| Name | Type | Mandatory | Default Value | Description | | ---- | ------ | ---- | ---- | ---------- |
| ---- | ------ | --------- | ------------- | -------------------- | | text | string | Yes | "" | Text to be measured.|
| text | string | Yes | "" | Text to be measured. |
- Return value **Return value**
| Type | Description |
| ----------- | ----------------------- |
| TextMetrics | **TextMetrics** object. |
- **TextMetrics** attributes | Type | Description |
| Name | Type | Description | | ----------- | ------- |
| ----- | ------ | ------------------ | | TextMetrics | **TextMetrics** object.|
| width | number | Width of the text. |
- Example **TextMetrics**
| Attribute | Type | Description |
| ------------------------ | ------ | ---------------------------------------- |
| width | number | Width of the text. |
| height | number | Height of the text. |
| actualBoundingBoxAscent | number | Distance from the horizontal line specified by the **CanvasRenderingContext2D.textBaseline** attribute to the top of the bounding rectangle used to render the text. The current value is **0**.|
| actualBoundingBoxDescent | number | Distance from the horizontal line specified by the **CanvasRenderingContext2D.textBaseline** attribute to the bottom of the bounding rectangle used to render the text. The current value is **0**.|
| actualBoundingBoxLeft | number | Distance parallel to the baseline from the alignment point determined by the **CanvasRenderingContext2D.textAlign** attribute to the left side of the bounding rectangle of the text. The current value is **0**.|
| actualBoundingBoxRight | number | Distance parallel to the baseline from the alignment point determined by the **CanvasRenderingContext2D.textAlign** attribute to the right side of the bounding rectangle of the text. The current value is **0**.|
| alphabeticBaseline | number | Distance from the horizontal line specified by the **CanvasRenderingContext2D.textBaseline** attribute to the alphabetic baseline of the line box. The current value is **0**.|
| emHeightAscent | number | Distance from the horizontal line specified by the **CanvasRenderingContext2D.textBaseline** attribute to the top of the em square in the line box. The current value is **0**.|
| emHeightDescent | number | Distance from the horizontal line specified by the **CanvasRenderingContext2D.textBaseline** attribute to the bottom of the em square in the line box. The current value is **0**.|
| fontBoundingBoxAscent | number | Distance from the horizontal line specified by the **CanvasRenderingContext2D.textBaseline** attribute to the top of the highest bounding rectangle of all the fonts used to render the text. The current value is **0**.|
| fontBoundingBoxDescent | number | Distance from the horizontal line specified by the **CanvasRenderingContext2D.textBaseline** attribute to the bottom of the bounding rectangle of all the fonts used to render the text. The current value is **0**.|
| hangingBaseline | number | Distance from the horizontal line specified by the **CanvasRenderingContext2D.textBaseline** attribute to the hanging baseline of the line box. The current value is **0**.|
| ideographicBaseline | number | Distance from the horizontal line indicated by the **CanvasRenderingContext2D.textBaseline** attribute to the ideographic baseline of the line box. The current value is **0**.|
**Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
@Component @Component
struct MeasureText { struct MeasureText {
private settings: RenderingContextSettings = new RenderingContextSettings(true) private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context) Canvas(this.context)
...@@ -921,20 +948,21 @@ stroke(path?: Path2D): void ...@@ -921,20 +948,21 @@ stroke(path?: Path2D): void
Strokes a path. Strokes a path.
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ---- | ---------------------------------------- | --------- | ------------- | -------------------------- | | Name | Type | Mandatory | Default Value | Description |
| path | [Path2D](ts-components-canvas-path2d.md) | No | null | A **Path2D** path to draw. | | ---- | ---------------------------------------- | ---- | ---- | ------------ |
| path | [Path2D](ts-components-canvas-path2d.md) | No | null | A **Path2D** path to draw.|
- Example **Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
@Component @Component
struct Stroke { struct Stroke {
private settings: RenderingContextSettings = new RenderingContextSettings(true) private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -964,15 +992,15 @@ beginPath(): void ...@@ -964,15 +992,15 @@ beginPath(): void
Creates a drawing path. Creates a drawing path.
- Example **Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
@Component @Component
struct BeginPath { struct BeginPath {
private settings: RenderingContextSettings = new RenderingContextSettings(true) private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -1004,21 +1032,22 @@ moveTo(x: number, y: number): void ...@@ -1004,21 +1032,22 @@ moveTo(x: number, y: number): void
Moves a drawing path to a target position on the canvas. Moves a drawing path to a target position on the canvas.
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ---- | ------ | --------- | ------------- | ------------------------------------ | | Name | Type | Mandatory | Default Value | Description |
| x | number | Yes | 0 | X-coordinate of the target position. | | ---- | ------ | ---- | ---- | --------- |
| y | number | Yes | 0 | Y-coordinate of the target position. | | x | number | Yes | 0 | X-coordinate of the target position.|
| y | number | Yes | 0 | Y-coordinate of the target position.|
- Example **Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
@Component @Component
struct MoveTo { struct MoveTo {
private settings: RenderingContextSettings = new RenderingContextSettings(true) private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -1048,21 +1077,22 @@ lineTo(x: number, y: number): void ...@@ -1048,21 +1077,22 @@ lineTo(x: number, y: number): void
Connects the current point to a target position using a straight line. Connects the current point to a target position using a straight line.
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ---- | ------ | --------- | ------------- | ------------------------------------ | | Name | Type | Mandatory | Default Value | Description |
| x | number | Yes | 0 | X-coordinate of the target position. | | ---- | ------ | ---- | ---- | --------- |
| y | number | Yes | 0 | Y-coordinate of the target position. | | x | number | Yes | 0 | X-coordinate of the target position.|
| y | number | Yes | 0 | Y-coordinate of the target position.|
- Example **Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
@Component @Component
struct LineTo { struct LineTo {
private settings: RenderingContextSettings = new RenderingContextSettings(true) private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -1092,15 +1122,15 @@ closePath(): void ...@@ -1092,15 +1122,15 @@ closePath(): void
Draws a closed path. Draws a closed path.
- Example **Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
@Component @Component
struct ClosePath { struct ClosePath {
private settings: RenderingContextSettings = new RenderingContextSettings(true) private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -1128,26 +1158,33 @@ Draws a closed path. ...@@ -1128,26 +1158,33 @@ Draws a closed path.
### createPattern ### createPattern
createPattern(image: ImageBitmap, repetition: string): void createPattern(image: ImageBitmap, repetition: string | null): CanvasPattern | null
Creates a pattern for image filling based on a specified source image and repetition mode. Creates a pattern for image filling based on a specified source image and repetition mode.
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ---------- | ---------------------------------------- | --------- | ------------- | ---------------------------------------- | | Name | Type | Mandatory | Default Value | Description |
| image | [ImageBitmap](ts-components-canvas-imagebitmap.md) | Yes | null | Source image. For details, see ImageBitmap. | | ---------- | ---------------------------------------- | ---- | ---- | ---------------------------------------- |
| repetition | string | Yes | "" | Repetition mode. The value can be **'repeat'**, **'repeat-x'**, **'repeat-y'**, or **'no-repeat'**. | | image | [ImageBitmap](ts-components-canvas-imagebitmap.md) | Yes | null | Source image. For details, see **ImageBitmap**. |
| repetition | string | Yes | "" | Repetition mode. The value can be **"repeat"**, **"repeat-x"**, **"repeat-y"**, or **"no-repeat"**.|
**Return value**
- Example | Type | Description |
| ------------------------------- | ----------------------- |
| [CanvasPattern](#canvaspattern) | Created pattern for image filling based on a specified source image and repetition mode.|
**Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
@Component @Component
struct CreatePattern { struct CreatePattern {
private settings: RenderingContextSettings = new RenderingContextSettings(true) private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
private img:ImageBitmap = new ImageBitmap("common/images/icon.jpg") private img:ImageBitmap = new ImageBitmap("common/images/icon.jpg");
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -1176,25 +1213,26 @@ bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number, ...@@ -1176,25 +1213,26 @@ bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number,
Draws a cubic bezier curve on the canvas. Draws a cubic bezier curve on the canvas.
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ---- | ------ | --------- | ------------- | ---------------------------------------- | | Name | Type | Mandatory | Default Value | Description |
| cp1x | number | Yes | 0 | X-coordinate of the first parameter of the bezier curve. | | ---- | ------ | ---- | ---- | -------------- |
| cp1y | number | Yes | 0 | Y-coordinate of the first parameter of the bezier curve. | | cp1x | number | Yes | 0 | X-coordinate of the first parameter of the bezier curve.|
| cp2x | number | Yes | 0 | X-coordinate of the second parameter of the bezier curve. | | cp1y | number | Yes | 0 | Y-coordinate of the first parameter of the bezier curve.|
| cp2y | number | Yes | 0 | Y-coordinate of the second parameter of the bezier curve. | | cp2x | number | Yes | 0 | X-coordinate of the second parameter of the bezier curve.|
| x | number | Yes | 0 | X-coordinate of the end point on the bezier curve. | | cp2y | number | Yes | 0 | Y-coordinate of the second parameter of the bezier curve.|
| y | number | Yes | 0 | Y-coordinate of the end point on the bezier curve. | | x | number | Yes | 0 | X-coordinate of the end point on the bezier curve. |
| y | number | Yes | 0 | Y-coordinate of the end point on the bezier curve. |
- Example **Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
@Component @Component
struct BezierCurveTo { struct BezierCurveTo {
private settings: RenderingContextSettings = new RenderingContextSettings(true) private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -1224,15 +1262,16 @@ quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void ...@@ -1224,15 +1262,16 @@ quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void
Draws a quadratic curve on the canvas. Draws a quadratic curve on the canvas.
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ---- | ------ | --------- | ------------- | ---------------------------------------- |
| cpx | number | Yes | 0 | X-coordinate of the bezier curve parameter. |
| cpy | number | Yes | 0 | Y-coordinate of the bezier curve parameter. |
| x | number | Yes | 0 | X-coordinate of the end point on the bezier curve. |
| y | number | Yes | 0 | Y-coordinate of the end point on the bezier curve. |
- Example | Name | Type | Mandatory | Default Value | Description |
| ---- | ------ | ---- | ---- | ----------- |
| cpx | number | Yes | 0 | X-coordinate of the bezier curve parameter.|
| cpy | number | Yes | 0 | Y-coordinate of the bezier curve parameter.|
| x | number | Yes | 0 | X-coordinate of the end point on the bezier curve.|
| y | number | Yes | 0 | Y-coordinate of the end point on the bezier curve.|
**Example**
```ts ```ts
// xxx.ets // xxx.ets
...@@ -1241,6 +1280,7 @@ Draws a quadratic curve on the canvas. ...@@ -1241,6 +1280,7 @@ Draws a quadratic curve on the canvas.
struct QuadraticCurveTo { struct QuadraticCurveTo {
private settings: RenderingContextSettings = new RenderingContextSettings(true); private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context) Canvas(this.context)
...@@ -1265,29 +1305,30 @@ Draws a quadratic curve on the canvas. ...@@ -1265,29 +1305,30 @@ Draws a quadratic curve on the canvas.
### arc ### arc
arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, anticlockwise?: boolean): void arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, counterclockwise?: boolean): void
Draws an arc on the canvas. Draws an arc on the canvas.
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ------------- | ------- | --------- | ------------- | ---------------------------------------- | | Name | Type | Mandatory | Default Value | Description |
| x | number | Yes | 0 | X-coordinate of the center point of the arc. | | ---------------- | ------- | ---- | ----- | ---------- |
| y | number | Yes | 0 | Y-coordinate of the center point of the arc. | | x | number | Yes | 0 | X-coordinate of the center point of the arc.|
| radius | number | Yes | 0 | Radius of the arc. | | y | number | Yes | 0 | Y-coordinate of the center point of the arc.|
| startAngle | number | Yes | 0 | Start radian of the arc. | | radius | number | Yes | 0 | Radius of the arc. |
| endAngle | number | Yes | 0 | End radian of the arc. | | startAngle | number | Yes | 0 | Start radian of the arc. |
| anticlockwise | boolean | No | false | Whether to draw the arc counterclockwise. | | endAngle | number | Yes | 0 | End radian of the arc. |
| counterclockwise | boolean | No | false | Whether to draw the arc counterclockwise.|
- Example **Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
@Component @Component
struct Arc { struct Arc {
private settings: RenderingContextSettings = new RenderingContextSettings(true) private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -1316,24 +1357,25 @@ arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void ...@@ -1316,24 +1357,25 @@ arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void
Draws an arc based on the radius and points on the arc. Draws an arc based on the radius and points on the arc.
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ------ | ------ | --------- | ------------- | ---------------------------------------- |
| x1 | number | Yes | 0 | X-coordinate of the first point on the arc. |
| y1 | number | Yes | 0 | Y-coordinate of the first point on the arc. |
| x2 | number | Yes | 0 | X-coordinate of the second point on the arc. |
| y2 | number | Yes | 0 | Y-coordinate of the second point on the arc. |
| radius | number | Yes | 0 | Radius of the arc. |
- Example | Name | Type | Mandatory | Default Value | Description |
| ------ | ------ | ---- | ---- | --------------- |
| x1 | number | Yes | 0 | X-coordinate of the first point on the arc.|
| y1 | number | Yes | 0 | Y-coordinate of the first point on the arc.|
| x2 | number | Yes | 0 | X-coordinate of the second point on the arc.|
| y2 | number | Yes | 0 | Y-coordinate of the second point on the arc.|
| radius | number | Yes | 0 | Radius of the arc. |
**Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
@Component @Component
struct ArcTo { struct ArcTo {
private settings: RenderingContextSettings = new RenderingContextSettings(true) private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -1358,32 +1400,32 @@ Draws an arc based on the radius and points on the arc. ...@@ -1358,32 +1400,32 @@ Draws an arc based on the radius and points on the arc.
### ellipse ### ellipse
ellipse(x: number, y: number, radiusX: number, radiusY: number, rotation: number, startAngle: number, endAngle: number, anticlockwise?: boolean): void ellipse(x: number, y: number, radiusX: number, radiusY: number, rotation: number, startAngle: number, endAngle: number, counterclockwise?: boolean): void
Draws an ellipse in the specified rectangular region. Draws an ellipse in the specified rectangular region on the canvas.
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ------------- | ------- | --------- | ------------- | ---------------------------------------- |
| x | number | Yes | 0 | X-coordinate of the ellipse center. |
| y | number | Yes | 0 | Y-coordinate of the ellipse center. |
| radiusX | number | Yes | 0 | Ellipse radius on the x-axis. |
| radiusY | number | Yes | 0 | Ellipse radius on the y-axis. |
| rotation | number | Yes | 0 | Rotation angle of the ellipse, in radians. |
| startAngle | number | Yes | 0 | Angle of the start point for drawing the ellipse, in radians. |
| endAngle | number | Yes | 0 | Angle of the end point for drawing the ellipse, in radians. |
| anticlockwise | boolean | No | false | Whether to draw the ellipse in the counterclockwise direction. |
- Example | Name | Type | Mandatory | Default Value | Description |
| ---------------- | ------- | ---- | ----- | ----------------- |
| x | number | Yes | 0 | X-coordinate of the ellipse center. |
| y | number | Yes | 0 | Y-coordinate of the ellipse center. |
| radiusX | number | Yes | 0 | Ellipse radius on the x-axis. |
| radiusY | number | Yes | 0 | Ellipse radius on the y-axis. |
| rotation | number | Yes | 0 | Rotation angle of the ellipse. The unit is radian. |
| startAngle | number | Yes | 0 | Angle of the start point for drawing the ellipse. The unit is radian.|
| endAngle | number | Yes | 0 | Angle of the end point for drawing the ellipse. The unit is radian.|
| counterclockwise | boolean | No | false | Whether to draw the ellipse in the counterclockwise direction. |
**Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
@Component @Component
struct CanvasExample { struct CanvasExample {
private settings: RenderingContextSettings = new RenderingContextSettings(true) private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -1408,27 +1450,28 @@ Draws an ellipse in the specified rectangular region. ...@@ -1408,27 +1450,28 @@ Draws an ellipse in the specified rectangular region.
### rect ### rect
rect(x: number, y: number, width: number, height: number): void rect(x: number, y: number, w: number, h: number): void
Creates a rectangle on the canvas.
Creates a rectangle. **Parameters**
- Parameters | Name | Type | Mandatory | Default Value | Description |
| Name | Type | Mandatory | Default Value | Description | | ---- | ------ | ---- | ---- | ------------- |
| ------ | ------ | --------- | ------------- | ---------------------------------------- | | x | number | Yes | 0 | X-coordinate of the upper left corner of the rectangle.|
| x | number | Yes | 0 | X-coordinate of the upper left corner of the rectangle. | | y | number | Yes | 0 | Y-coordinate of the upper left corner of the rectangle.|
| y | number | Yes | 0 | Y-coordinate of the upper left corner of the rectangle. | | w | number | Yes | 0 | Width of the rectangle. |
| width | number | Yes | 0 | Width of the rectangle. | | h | number | Yes | 0 | Height of the rectangle. |
| height | number | Yes | 0 | Height of the rectangle. |
- Example **Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
@Component @Component
struct CanvasExample { struct CanvasExample {
private settings: RenderingContextSettings = new RenderingContextSettings(true) private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -1452,19 +1495,26 @@ Creates a rectangle. ...@@ -1452,19 +1495,26 @@ Creates a rectangle.
### fill ### fill
fill(): void fill(fillRule?: CanvasFillRule): void
Fills the area inside a closed path on the canvas.
**Parameters**
Fills the area inside a closed path. | Name | Type | Mandatory | Default Value | Description |
| -------- | -------------- | ---- | --------- | ---------------------------------------- |
| fillRule | CanvasFillRule | No | "nonzero" | Specifies the rule to populate the object.<br>The options are **"nonzero"** and **"evenodd"**.|
- Example
**Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
@Component @Component
struct Fill { struct Fill {
private settings: RenderingContextSettings = new RenderingContextSettings(true) private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -1486,21 +1536,78 @@ Fills the area inside a closed path. ...@@ -1486,21 +1536,78 @@ Fills the area inside a closed path.
![en-us_image_0000001256858389](figures/en-us_image_0000001256858389.png) ![en-us_image_0000001256858389](figures/en-us_image_0000001256858389.png)
fill(path: Path2D, fillRule?: CanvasFillRule): void
Fills the area inside a closed path on the canvas.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------------- | ---- | --------- | ---------------------------------------- |
| path | Path2D | Yes | | A **Path2D** path to fill. |
| fillRule | CanvasFillRule | No | "nonzero" | Rule by which to determine whether a point is inside or outside the area to fill.<br>The options are **"nonzero"** and **"evenodd"**.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct Fill {
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('#ffff00')
.onReady(() =>{
let region = new Path2D();
region.moveTo(30, 90);
region.lineTo(110, 20);
region.lineTo(240, 130);
region.lineTo(60, 130);
region.lineTo(190, 20);
region.lineTo(270, 90);
region.closePath();
// Fill path
this.context.fillStyle = 'green';
this.context.fill(region, "evenodd");
})
}
.width('100%')
.height('100%')
}
}
```
![en-us_image_000000127777774](figures/en-us_image_000000127777774.png)
### clip ### clip
clip(): void clip(fillRule?: CanvasFillRule): void
Sets the current path to a clipping area.
Sets the current path to a clipping path. **Parameters**
- Example | Name | Type | Mandatory | Default Value | Description |
| -------- | -------------- | ---- | --------- | ---------------------------------------- |
| fillRule | CanvasFillRule | No | "nonzero" | Rule by which to determine whether a point is inside or outside the area to clip.<br>The options are **"nonzero"** and **"evenodd"**.|
**Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
@Component @Component
struct Clip { struct Clip {
private settings: RenderingContextSettings = new RenderingContextSettings(true) private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -1525,26 +1632,74 @@ Sets the current path to a clipping path. ...@@ -1525,26 +1632,74 @@ Sets the current path to a clipping path.
![en-us_image_0000001211898488](figures/en-us_image_0000001211898488.png) ![en-us_image_0000001211898488](figures/en-us_image_0000001211898488.png)
clip(path: Path2D, fillRule?: CanvasFillRule): void
Sets a **Path2D** path to a clipping area. This API is a null API.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------------- | ---- | --------- | ---------------------------------------- |
| path | Path2D | Yes | - | A **Path2D** path to use as a clipping area. |
| fillRule | CanvasFillRule | No | "nonzero" | Rule by which to determine whether a point is inside or outside the area to clip.<br>The options are **"nonzero"** and **"evenodd"**.|
### filter
filter(filter: string): void
Provides filter effects. This API is a null API.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ------ | ------ | ---- | ---- | ------------ |
| filter | string | Yes | - | Filter functions.|
### getTransform
getTransform(): Matrix2D
Obtains the current transformation matrix being applied to the context. This API is a null API.
### resetTransform
resetTransform(): void
Resets the current transform to the identity matrix. This API is a null API.
### direction
direction(direction: CanvasDirection): void
Sets the current text direction used to draw text. This API is a null API.
### rotate ### rotate
rotate(rotate: number): void rotate(angle: number): void
Rotates a canvas clockwise around its coordinate axes. Rotates a canvas clockwise around its coordinate axes.
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ------ | ------ | --------- | ------------- | ---------------------------------------- |
| rotate | number | Yes | 0 | Clockwise rotation angle. You can use **Math.PI / 180** to convert the angle to a radian. |
- Example | Name | Type | Mandatory | Default Value | Description |
| ----- | ------ | ---- | ---- | ---------------------------------------- |
| angle | number | Yes | 0 | Clockwise rotation angle. You can use **Math.PI / 180** to convert the angle to a radian.|
**Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
@Component @Component
struct Rotate { struct Rotate {
private settings: RenderingContextSettings = new RenderingContextSettings(true) private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -1570,23 +1725,24 @@ Rotates a canvas clockwise around its coordinate axes. ...@@ -1570,23 +1725,24 @@ Rotates a canvas clockwise around its coordinate axes.
scale(x: number, y: number): void scale(x: number, y: number): void
Scales a canvas based on scale factors. Scales the canvas based on the given scale factors.
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ---- | ------ | --------- | ------------- | ------------------------ |
| x | number | Yes | 0 | Horizontal scale factor. |
| y | number | Yes | 0 | Vertical scale factor. |
- Example | Name | Type | Mandatory | Default Value | Description |
| ---- | ------ | ---- | ---- | ----------- |
| x | number | Yes | 0 | Horizontal scale factor.|
| y | number | Yes | 0 | Vertical scale factor.|
**Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
@Component @Component
struct Scale { struct Scale {
private settings: RenderingContextSettings = new RenderingContextSettings(true) private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -1611,36 +1767,37 @@ Scales a canvas based on scale factors. ...@@ -1611,36 +1767,37 @@ Scales a canvas based on scale factors.
### transform ### transform
transform(scaleX: number, skewX: number, skewY: number, scaleY: number, translateX: number, translateY: number): void transform(a: number, b: number, c: number, d: number, e: number, f: number): void
Defines a transformation matrix. To transform a graph, you only need to set parameters of the matrix. The coordinates of the graph are multiplied by the matrix values to obtain new coordinates of the transformed graph. You can use the matrix to implement multiple transform effects. Defines a transformation matrix. To transform a graph, you only need to set parameters of the matrix. The coordinates of the graph are multiplied by the matrix values to obtain new coordinates of the transformed graph. You can use the matrix to implement multiple transform effects.
> **NOTE**<br> > **NOTE**
> The following formulas calculate coordinates of the transformed graph. **x** and **y** represent coordinates before transformation, and **x'** and **y'** represent coordinates after transformation. > The following formulas calculate coordinates of the transformed graph. **x** and **y** represent coordinates before transformation, and **x'** and **y'** represent coordinates after transformation.
> >
> - x' = scaleX \* x + skewY \* y + translateX > - x' = scaleX \* x + skewY \* y + translateX
> >
> - y' = skewX \* x + scaleY \* y + translateY > - y' = skewX \* x + scaleY \* y + translateY
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ---------- | ------ | --------- | ------------- | ------------------- | | Name | Type | Mandatory | Default Value | Description |
| scaleX | number | Yes | 0 | X-axis scale. | | ---- | ------ | ---- | ---- | -------------------- |
| skewX | number | Yes | 0 | X-axis skew. | | a | number | Yes | 0 | X-axis scale. |
| skewY | number | Yes | 0 | Y-axis skew. | | b | number | Yes | 0 | X-axis skew. |
| scaleY | number | Yes | 0 | Y-axis scale. | | c | number | Yes | 0 | Y-axis skew. |
| translateX | number | Yes | 0 | X-axis translation. | | d | number | Yes | 0 | Y-axis scale. |
| translateY | number | Yes | 0 | Y-axis translation. | | e | number | Yes | 0 | X-axis translation.|
| f | number | Yes | 0 | Y-axis translation.|
- Example **Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
@Component @Component
struct Transform { struct Transform {
private settings: RenderingContextSettings = new RenderingContextSettings(true) private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -1670,29 +1827,30 @@ Defines a transformation matrix. To transform a graph, you only need to set para ...@@ -1670,29 +1827,30 @@ Defines a transformation matrix. To transform a graph, you only need to set para
### setTransform ### setTransform
setTransform(scaleX: number, skewX: number, skewY: number, scale: number, translateX: number, translateY: number): void setTransform(a: number, b: number, c: number, d: number, e: number, f: number): void
Resets the existing transformation matrix and creates a new transformation matrix by using the same parameters as the **transform()** function. Resets the existing transformation matrix and creates a new transformation matrix by using the same parameters as the **transform()** API.
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ---------- | ------ | --------- | ------------- | ------------------- |
| scaleX | number | Yes | 0 | X-axis scale. |
| skewX | number | Yes | 0 | X-axis skew. |
| skewY | number | Yes | 0 | Y-axis skew. |
| scaleY | number | Yes | 0 | Y-axis scale. |
| translateX | number | Yes | 0 | X-axis translation. |
| translateY | number | Yes | 0 | Y-axis translation. |
- Example | Name | Type | Mandatory | Default Value | Description |
| ---- | ------ | ---- | ---- | -------------------- |
| a | number | Yes | 0 | X-axis scale. |
| b | number | Yes | 0 | X-axis skew. |
| c | number | Yes | 0 | Y-axis skew. |
| d | number | Yes | 0 | Y-axis scale. |
| e | number | Yes | 0 | X-axis translation.|
| f | number | Yes | 0 | Y-axis translation.|
**Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
@Component @Component
struct SetTransform { struct SetTransform {
private settings: RenderingContextSettings = new RenderingContextSettings(true) private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -1717,27 +1875,33 @@ Resets the existing transformation matrix and creates a new transformation matri ...@@ -1717,27 +1875,33 @@ Resets the existing transformation matrix and creates a new transformation matri
![en-us_image_0000001256858395](figures/en-us_image_0000001256858395.png) ![en-us_image_0000001256858395](figures/en-us_image_0000001256858395.png)
setTransform(transform?: Matrix2D): void
Resets the current transformation to the identity matrix, and then creates a new transformation matrix based on the specified **Matrix2D** object. This API is a null API.
### translate ### translate
translate(x: number, y: number): void translate(x: number, y: number): void
Moves the origin of the coordinate system. Moves the origin of the coordinate system.
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ---- | ------ | --------- | ------------- | ------------------- | | Name | Type | Mandatory | Default Value | Description |
| x | number | Yes | 0 | X-axis translation. | | ---- | ------ | ---- | ---- | -------- |
| y | number | Yes | 0 | Y-axis translation. | | x | number | Yes | 0 | X-axis translation.|
| y | number | Yes | 0 | Y-axis translation.|
- Example **Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
@Component @Component
struct Translate { struct Translate {
private settings: RenderingContextSettings = new RenderingContextSettings(true) private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -1764,27 +1928,28 @@ Moves the origin of the coordinate system. ...@@ -1764,27 +1928,28 @@ Moves the origin of the coordinate system.
drawImage(image: ImageBitmap | PixelMap, dx: number, dy: number): void drawImage(image: ImageBitmap | PixelMap, dx: number, dy: number): void
drawImage(image: ImageBitmap | PixelMap, dx: number, dy: number, dWidth: number, dHeight: number): void drawImage(image: ImageBitmap | PixelMap, dx: number, dy: number, dw: number, dh: number): void
drawImage(image: ImageBitmap | PixelMap, sx: number, sy: number, sw: number, sh: number, dx: number, dy: number, dw: number, dh: number):void
drawImage(image: ImageBitmap | PixelMap, sx: number, sy: number, sWidth: number, sHeight: number, dx: number, dy: number, dWidth: number, dHeight: number):void Draws an image on the canvas.
Draws an image. **Parameters**
- Parameters | Name | Type | Mandatory | Default Value | Description |
| Name | Type | Mandatory | Default Value | Description | | ----- | ---------------------------------------- | ---- | ---- | ---------------------------------------- |
| ------- | ------------------------------------------------------------ | --------- | ------------- | ------------------------------------------------------------ | | image | [ImageBitmap](ts-components-canvas-imagebitmap.md) or [PixelMap](../apis/js-apis-image.md#pixelmap7)| Yes | null | Image resource. For details, see **ImageBitmap** or PixelMap. |
| image | [ImageBitmap](ts-components-canvas-imagebitmap.md) or [PixelMap](../apis/js-apis-image.md#pixelmap7) | Yes | null | Image resource. For details, see ImageBitmap or PixelMap. | | sx | number | No | 0 | X-coordinate of the upper left corner of the rectangle used to crop the source image. |
| sx | number | No | 0 | X-coordinate of the upper left corner of the rectangle used to crop the source image. | | sy | number | No | 0 | Y-coordinate of the upper left corner of the rectangle used to crop the source image. |
| sy | number | No | 0 | Y-coordinate of the upper left corner of the rectangle used to crop the source image. | | sw | number | No | 0 | Target width to crop the source image. |
| sWidth | number | No | 0 | Target width to crop the source image. | | sh | number | No | 0 | Target height to crop the source image. |
| sHeight | number | No | 0 | Target height to crop the source image. | | dx | number | Yes | 0 | X-coordinate of the upper left corner of the drawing area on the canvas. |
| dx | number | Yes | 0 | X-coordinate of the upper left corner of the drawing area on the canvas. | | dy | number | Yes | 0 | Y-coordinate of the upper left corner of the drawing area on the canvas. |
| dy | number | Yes | 0 | Y-coordinate of the upper left corner of the drawing area on the canvas. | | dw | number | No | 0 | Width of the drawing area. If the width of the drawing area is different from that of the cropped image, the latter will be stretched or compressed to the former.|
| dWidth | number | No | 0 | Width of the drawing area. If the width of the drawing area is different from that of the cropped image, the latter will be stretched or compressed to the former. | | dh | number | No | 0 | Height of the drawing area. If the height of the drawing area is different from that of the cropped image, the latter will be stretched or compressed to the former.|
| dHeight | number | No | 0 | Height of the drawing area. If the height of the drawing area is different from that of the cropped image, the latter will be stretched or compressed to the former. |
- Example **Example**
```ts ```ts
// xxx.ets // xxx.ets
...@@ -1794,6 +1959,7 @@ Draws an image. ...@@ -1794,6 +1959,7 @@ Draws an image.
private settings: RenderingContextSettings = new RenderingContextSettings(true); private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
private img:ImageBitmap = new ImageBitmap("common/images/example.jpg"); private img:ImageBitmap = new ImageBitmap("common/images/example.jpg");
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context) Canvas(this.context)
...@@ -1815,81 +1981,109 @@ Draws an image. ...@@ -1815,81 +1981,109 @@ Draws an image.
### createImageData ### createImageData
createImageData(width: number, height: number): Object createImageData(sw: number, sh: number): ImageData
Creates an **ImageData** object. For details, see [ImageData](ts-components-canvas-imagebitmap.md). Creates an **ImageData** object with the specified dimensions. For details, see [ImageData](ts-components-canvas-imagebitmap.md).
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ------ | ------ | --------- | ------------- | ----------------------------------- | | Name | Type | Mandatory | Default Value | Description |
| width | number | Yes | 0 | Width of the **ImageData** object. | | ---- | ------ | ---- | ---- | ------------- |
| height | number | Yes | 0 | Height of the **ImageData** object. | | sw | number | Yes | 0 | Width of the **ImageData** object.|
| sh | number | Yes | 0 | Height of the **ImageData** object.|
### createImageData ### createImageData
createImageData(imageData: Object): Object createImageData(imageData: ImageData): ImageData
Creates an **ImageData** object. For details, see [ImageData](ts-components-canvas-imagebitmap.md). Creates an **ImageData** object. For details, see [ImageData](ts-components-canvas-imagebitmap.md).
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| --------- | ------ | --------- | ------------- | ---------------------------------------- | | Name | Type | Mandatory | Default Value | Description |
| imagedata | Object | Yes | null | **ImageData** object with the same width and height copied from the original **ImageData** object. | | --------- | ---------------------------------------- | ---- | ---- | ----------------- |
| imagedata | [ImageData](ts-components-canvas-imagebitmap.md) | Yes | null | **ImageData** object with the same width and height copied from the original **ImageData** object.|
**Return value**
| Type | Description |
| ---------------------------------------- | -------------- |
| [ImageData](ts-components-canvas-imagebitmap.md) | New **ImageData** object.|
### getPixelMap ### getPixelMap
getPixelMap(sx: number, sy: number, sw: number, sh: number): PixelMap getPixelMap(sx: number, sy: number, sw: number, sh: number): PixelMap
Obtains the **[PixelMap](../apis/js-apis-image.md#pixelmap7)** object created with the pixels within the specified area on the canvas. Obtains the **[PixelMap](../apis/js-apis-image.md#pixelmap7)** object created with the pixels within the specified area on the canvas.
- Parameters
| Name | Type | Mandatory | Default Value | Description | **Parameters**
| ---- | ------ | ---- | ---- | --------------- |
| sx | number | Yes | 0 | X-coordinate of the upper left corner of the output area.| | Name | Type | Mandatory | Default Value | Description |
| sy | number | Yes | 0 | Y-coordinate of the upper left corner of the output area.| | ---- | ------ | ---- | ---- | --------------- |
| sw | number | Yes | 0 | Width of the output area. | | sx | number | Yes | 0 | X-coordinate of the upper left corner of the output area.|
| sh | number | Yes | 0 | Height of the output area. | | sy | number | Yes | 0 | Y-coordinate of the upper left corner of the output area.|
| sw | number | Yes | 0 | Width of the output area. |
| sh | number | Yes | 0 | Height of the output area. |
**Return value**
| Type | Description |
| ---------------------------------------- | ------------- |
| [PixelMap](../apis/js-apis-image.md#pixelmap7) | **PixelMap** object.|
### getImageData ### getImageData
getImageData(sx: number, sy: number, sw: number, sh: number): Object getImageData(sx: number, sy: number, sw: number, sh: number): ImageData
Obtains the **[ImageData](ts-components-canvas-imagebitmap.md)** object created with the pixels within the specified area on the canvas. Obtains the **[ImageData](ts-components-canvas-imagebitmap.md)** object created with the pixels within the specified area on the canvas.
- Parameters
| Name | Type | Mandatory | Default Value | Description | **Parameters**
| ---- | ------ | --------- | ------------- | ---------------------------------------- |
| sx | number | Yes | 0 | X-coordinate of the upper left corner of the output area. | | Name | Type | Mandatory | Default Value | Description |
| sy | number | Yes | 0 | Y-coordinate of the upper left corner of the output area. | | ---- | ------ | ---- | ---- | --------------- |
| sw | number | Yes | 0 | Width of the output area. | | sx | number | Yes | 0 | X-coordinate of the upper left corner of the output area.|
| sh | number | Yes | 0 | Height of the output area. | | sy | number | Yes | 0 | Y-coordinate of the upper left corner of the output area.|
| sw | number | Yes | 0 | Width of the output area. |
| sh | number | Yes | 0 | Height of the output area. |
**Return value**
| Type | Description |
| ---------------------------------------- | -------------- |
| [ImageData](ts-components-canvas-imagebitmap.md) | **ImageData** object.|
### putImageData ### putImageData
putImageData(imageData: Object, dx: number, dy: number, dirtyX?: number, dirtyY?: number, dirtyWidth?: number, dirtyHeight?: number): void putImageData(imageData: ImageData, dx: number, dy: number): void
putImageData(imageData: ImageData, dx: number, dy: number, dirtyX: number, dirtyY: number, dirtyWidth: number, dirtyHeight: number): void
Puts data from the given **[ImageData](ts-components-canvas-imagebitmap.md)** object into the specified rectangular area on the canvas.
Puts the **[ImageData](ts-components-canvas-imagebitmap.md)** onto a rectangular area on the canvas. **Parameters**
- Parameters | Name | Type | Mandatory | Default Value | Description |
| Name | Type | Mandatory | Default Value | Description | | ----------- | ---------------------------------------- | ---- | ------------ | ----------------------------- |
| ----------- | ------ | --------- | ---------------------------------- | ---------------------------------------- | | imagedata | [ImageData](ts-components-canvas-imagebitmap.md) | Yes | null | **ImageData** object with pixels to put onto the canvas. |
| imagedata | Object | Yes | null | **ImageData** object with pixels to put onto the canvas. | | dx | number | Yes | 0 | X-axis offset of the rectangular area on the canvas. |
| dx | number | Yes | 0 | X-axis offset of the rectangular area on the canvas. | | dy | number | Yes | 0 | Y-axis offset of the rectangular area on the canvas. |
| dy | number | Yes | 0 | Y-axis offset of the rectangular area on the canvas. | | dirtyX | number | No | 0 | X-axis offset of the upper left corner of the rectangular area relative to that of the source image.|
| dirtyX | number | No | 0 | X-axis offset of the upper left corner of the rectangular area relative to that of the source image. | | dirtyY | number | No | 0 | Y-axis offset of the upper left corner of the rectangular area relative to that of the source image.|
| dirtyY | number | No | 0 | Y-axis offset of the upper left corner of the rectangular area relative to that of the source image. | | dirtyWidth | number | No | Width of the **ImageData** object| Width of the rectangular area to crop the source image. |
| dirtyWidth | number | No | Width of the **ImageData** object | Width of the rectangular area to crop the source image. | | dirtyHeight | number | No | Height of the **ImageData** object| Height of the rectangular area to crop the source image. |
| dirtyHeight | number | No | Height of the **ImageData** object | Height of the rectangular area to crop the source image. |
- Example **Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
@Component @Component
struct PutImageData { struct PutImageData {
private settings: RenderingContextSettings = new RenderingContextSettings(true) private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -1917,21 +2111,215 @@ Puts the **[ImageData](ts-components-canvas-imagebitmap.md)** onto a rectangular ...@@ -1917,21 +2111,215 @@ Puts the **[ImageData](ts-components-canvas-imagebitmap.md)** onto a rectangular
![en-us_image_0000001212378396](figures/en-us_image_0000001212378396.png) ![en-us_image_0000001212378396](figures/en-us_image_0000001212378396.png)
### setLineDash
setLineDash(segments: number[]): void
Sets the dash line style.
**Parameters**
| Name | Type | Description |
| -------- | -------- | ------------------- |
| segments | number[] | An array of numbers that specify distances to alternately draw a line and a gap.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct SetLineDash {
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('#ffff00')
.onReady(() =>{
this.context.arc(100, 75, 50, 0, 6.28)
this.context.setLineDash([10,20])
})
}
.width('100%')
.height('100%')
}
}
```
![en-us_image_000000127777771](figures/en-us_image_000000127777771.png)
### getLineDash
getLineDash(): number[]
Obtains the dash line style.
**Return value**
| Type | Description |
| -------- | ------------------------ |
| number[] | An array of numbers that specify distances to alternately draw a line and a gap.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct GetLineDash {
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('#ffff00')
.onReady(() =>{
var grad = this.context.createLinearGradient(50,0, 300,100)
this.context.arc(100, 75, 50, 0, 6.28)
this.context.setLineDash([10,20])
this.context.stroke();
let res = this.context.getLineDash()
})
}
.width('100%')
.height('100%')
}
}
```
### imageSmoothingQuality
imageSmoothingQuality(quality: imageSmoothingQuality)
Sets the quality of image smoothing. This API is a null API.
**Parameters**
| Name | Type | Description |
| ------- | --------------------- | ---------------------------------------- |
| quality | imageSmoothingQuality | The options are as follows: '**low'**, **'medium'**, and **'high'**.|
### transferFromImageBitmap
transferFromImageBitmap(bitmap: ImageBitmap): void
Displays the specified **ImageBitmap** object.
**Parameters**
| Name | Type | Description |
| ------ | ---------------------------------------- | ------------------ |
| bitmap | [ImageData](ts-components-canvas-imagebitmap.md) | **ImageBitmap** object to display.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct PutImageData {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings)
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context)
.width('100%')
.height('100%')
.backgroundColor('#ffff00')
.onReady(() =>{
var imageData = this.offContext.createImageData(100, 100)
for (var i = 0; i < imageData.data.length; i += 4) {
imageData.data[i + 0] = 255
imageData.data[i + 1] = 0
imageData.data[i + 2] = 255
imageData.data[i + 3] = 255
}
this.offContext.putImageData(imageData, 10, 10)
var image = this.offContext.transferToImageBitmap()
this.context.transferFromImageBitmap(image)
})
}
.width('100%')
.height('100%')
}
}
```
![en-us_image_000000127777773](figures/en-us_image_000000127777773.png)
### toDataURL
toDataURL(type?: string, quality?: number): string
Generates a URL containing image display information.
**Parameters**
| Name | Type | Mandatory | Description |
| ------- | ------ | ---- | ---------------------------------------- |
| type | string | No | Image format. The default value is **image/png**. |
| quality | number | No | Image quality, which ranges from 0 to 1, when the image format is **image/jpeg** or **image/webp**. If the set value is beyond the value range, the default value **0.92** is used.|
**Return value**
| Type | Description |
| ------ | --------- |
| string | Image URL.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct ToDataURL {
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('#ffff00')
.onReady(() =>{
var dataURL = this.context.toDataURL();
})
}
.width('100%')
.height('100%')
}
}
```
### restore ### restore
restore(): void restore(): void
Restores the saved drawing context. Restores the saved drawing context.
- Example **Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
@Component @Component
struct CanvasExample { struct CanvasExample {
private settings: RenderingContextSettings = new RenderingContextSettings(true) private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -1954,17 +2342,17 @@ Restores the saved drawing context. ...@@ -1954,17 +2342,17 @@ Restores the saved drawing context.
save(): void save(): void
Saves the current drawing context. Saves all states of the canvas in the stack. This API is usually called when the drawing state needs to be saved.
- Example **Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
@Component @Component
struct CanvasExample { struct CanvasExample {
private settings: RenderingContextSettings = new RenderingContextSettings(true) private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -1989,23 +2377,24 @@ createLinearGradient(x0: number, y0: number, x1: number, y1: number): void ...@@ -1989,23 +2377,24 @@ createLinearGradient(x0: number, y0: number, x1: number, y1: number): void
Creates a linear gradient. Creates a linear gradient.
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ---- | ------ | --------- | ------------- | -------------------------------- | | Name | Type | Mandatory | Default Value | Description |
| x0 | number | Yes | 0 | X-coordinate of the start point. | | ---- | ------ | ---- | ---- | -------- |
| y0 | number | Yes | 0 | Y-coordinate of the start point. | | x0 | number | Yes | 0 | X-coordinate of the start point.|
| x1 | number | Yes | 0 | X-coordinate of the end point. | | y0 | number | Yes | 0 | Y-coordinate of the start point.|
| y1 | number | Yes | 0 | Y-coordinate of the end point. | | x1 | number | Yes | 0 | X-coordinate of the end point.|
| y1 | number | Yes | 0 | Y-coordinate of the end point.|
- Example **Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
@Component @Component
struct CreateLinearGradient { struct CreateLinearGradient {
private settings: RenderingContextSettings = new RenderingContextSettings(true) private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -2037,25 +2426,26 @@ createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number, ...@@ -2037,25 +2426,26 @@ createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number,
Creates a linear gradient. Creates a linear gradient.
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ---- | ------ | --------- | ------------- | ---------------------------------------- | | Name | Type | Mandatory | Default Value | Description |
| x0 | number | Yes | 0 | X-coordinate of the center of the start circle. | | ---- | ------ | ---- | ---- | ----------------- |
| y0 | number | Yes | 0 | Y-coordinate of the center of the start circle. | | x0 | number | Yes | 0 | X-coordinate of the center of the start circle. |
| r0 | number | Yes | 0 | Radius of the start circle, which must be a non-negative finite number. | | y0 | number | Yes | 0 | Y-coordinate of the center of the start circle. |
| x1 | number | Yes | 0 | X-coordinate of the center of the end circle. | | r0 | number | Yes | 0 | Radius of the start circle, which must be a non-negative finite number.|
| y1 | number | Yes | 0 | Y-coordinate of the center of the end circle. | | x1 | number | Yes | 0 | X-coordinate of the center of the end circle. |
| r1 | number | Yes | 0 | Radius of the end circle, which must be a non-negative finite number. | | y1 | number | Yes | 0 | Y-coordinate of the center of the end circle. |
| r1 | number | Yes | 0 | Radius of the end circle, which must be a non-negative finite number.|
- Example **Example**
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
@Component @Component
struct CreateRadialGradient { struct CreateRadialGradient {
private settings: RenderingContextSettings = new RenderingContextSettings(true) private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -2083,4 +2473,4 @@ Creates a linear gradient. ...@@ -2083,4 +2473,4 @@ Creates a linear gradient.
## CanvasPattern ## CanvasPattern
Defines an object created by using the [createPattern](#createpattern) method. Defines an object created using the **[createPattern](#createpattern)** API.
...@@ -2,9 +2,9 @@ ...@@ -2,9 +2,9 @@
Continuous recognition, parallel recognition, and exclusive recognition are supported for a group of gestures. Continuous recognition, parallel recognition, and exclusive recognition are supported for a group of gestures.
> **NOTE** > **NOTE**
> >
> Combined gestures are supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > The APIs of this module are supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions ## Required Permissions
...@@ -17,29 +17,28 @@ None ...@@ -17,29 +17,28 @@ None
GestureGroup(mode: GestureMode, ...gesture: GestureType[]) GestureGroup(mode: GestureMode, ...gesture: GestureType[])
- Parameters - Parameters
| Name | Type | Mandatory | Default Value | Description | | Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| mode | GestureMode | Yes | - | Recognition mode of combined gestures. | | mode | GestureMode | Yes| - | Recognition mode of combined gestures.|
| gesture | [TapGesture](ts-basic-gestures-tapgesture.md)<br/>\| [LongPressGesture](ts-basic-gestures-longpressgesture.md)<br/>\| [PanGesture](ts-basic-gestures-pangesture.md)<br/>\| [PinchGesture](ts-basic-gestures-pinchgesture.md)<br/>\| [RotationGesture](ts-basic-gestures-rotationgesture.md) | Yes | - | Variable-length parameter, indicating one or more basic gesture types. These gestures are recognized in combination. | | gesture | [TapGesture](ts-basic-gestures-tapgesture.md)<br>\| [LongPressGesture](ts-basic-gestures-longpressgesture.md)<br>\| [PanGesture](ts-basic-gestures-pangesture.md)<br>\| [PinchGesture](ts-basic-gestures-pinchgesture.md)<br>\| [RotationGesture](ts-basic-gestures-rotationgesture.md) | Yes| - | Variable-length parameter, indicating one or more basic gesture types. These gestures are recognized in combination.|
- GestureMode enums - GestureMode enums
| Name | Description | | Name| Description|
| -------- | -------- | | -------- | -------- |
| Sequence | Sequential recognition: Gestures are recognized in the registration sequence until all gestures are recognized successfully. When one gesture fails to be recognized, all gestures fail to be recognized. | | Sequence | Sequential recognition: Gestures are recognized in the registration sequence until all gestures are recognized successfully. When one gesture fails to be recognized, all gestures fail to be recognized.|
| Parallel | Parallel recognition. Registered gestures are recognized concurrently until all gestures are recognized. The recognition result of each gesture does not affect each other. | | Parallel | Parallel recognition. Registered gestures are recognized concurrently until all gestures are recognized. The recognition result of each gesture does not affect each other.|
| Exclusive | Exclusive recognition. Registered gestures are identified concurrently. If one gesture is successfully recognized, gesture recognition ends. | | Exclusive | Exclusive recognition. Registered gestures are identified concurrently. If one gesture is successfully recognized, gesture recognition ends.|
## Events ## Events
| Name | Description | | Name| Description|
| -------- | -------- | | -------- | -------- |
| onCancel(event: () =&gt; void) | Callback for the GestureMode.Sequence cancellation event. | | onCancel(event: () =&gt; void) | Callback for the GestureMode.Sequence cancellation event.|
## Example ## Example
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
......
# Canvas # Canvas
The **\<Canvas>** component can be used to customize drawings.
> **NOTE**<br> > **NOTE**
>
> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. > This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
The **&lt;Canvas&gt;** component can be used to customize drawings.
## Required Permissions ## Required Permissions
None None
## Child Components ## Child Components
None Not supported
## APIs ## APIs
Canvas(context: CanvasRenderingContext2D) Canvas(context?: CanvasRenderingContext2D)
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ------- | ---------------------------------------- | --------- | ------------- | ---------------------------------------- |
| context | [CanvasRenderingContext2D](ts-canvasrenderingcontext2d.md) | Yes | - | For details, see [CanvasRenderingContext2D](ts-canvasrenderingcontext2d.md). |
| Name | Type | Mandatory | Default Value | Description |
| ------- | ---------------------------------------- | ---- | ---- | ---------------------------- |
| context | [CanvasRenderingContext2D](ts-canvasrenderingcontext2d.md) | No | - | For details, see **CanvasRenderingContext2D**.|
## Attributes ## Attributes
Universal attributes are supported. The [universal attributes](ts-universal-attributes-size.md) are supported.
## Events ## Events
In addition to universal events, the following events are supported. In addition to the [universal events](ts-universal-events-click.md), the following events are supported.
| Name | Parameter | Description |
| -------------------------------- | --------- | ---------------- |
| onReady(callback: () =&gt; void) | None | Triggered when a canvas is ready. |
| Name | Parameter | Description |
| ----------------------------- | ---- | -------------------- |
| onReady(event: () => void) | - | Triggered when a canvas is ready. When this event is triggered, the width and height of the canvas can be obtained, and you can use the canvas APIs to draw images.|
## Example ## Example
```ts
``` // xxx.ets
@Entry @Entry
@Component @Component
struct CanvasExample { struct CanvasExample {
......
...@@ -2,9 +2,9 @@ ...@@ -2,9 +2,9 @@
**CanvasGradient** provides a canvas gradient object. **CanvasGradient** provides a canvas gradient object.
> **NOTE** > **NOTE**
> >
> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. > The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
## addColorStop ## addColorStop
...@@ -13,41 +13,45 @@ addColorStop(offset: number, color: string): void ...@@ -13,41 +13,45 @@ addColorStop(offset: number, color: string): void
Adds a color stop for the **CanvasGradient** object based on the specified offset and gradient color. Adds a color stop for the **CanvasGradient** object based on the specified offset and gradient color.
**Parameters** - Parameters
| Name | Type | Mandatory | Default Value | Description |
| Name | Type | Mandatory | Default Value | Description | | ------ | ------ | ---- | --------- | ---------------------------- |
| -------- | -------- | -------- | -------- | -------- | | offset | number | Yes | 0 | Relative position of the gradient stop along the gradient vector. The value ranges from 0 to 1.|
| offset | number | Yes | 0 | Relative position of the gradient stop along the gradient vector. The value ranges from 0 to 1. | | color | string | Yes | '#ffffff' | Gradient color to set. |
| color | string | Yes | '#ffffff'| Gradient color to set. |
- Example
**Example**
```ts
```ts // xxx.ets
// xxx.ets @Entry
@Entry @Component
@Component struct Page45 {
struct Page45 { private settings: RenderingContextSettings = new RenderingContextSettings(true)
private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() {
build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context)
Canvas(this.context) .width('100%')
.width('100%') .height('100%')
.height('100%') .backgroundColor('#ffff00')
.backgroundColor('#ffff00') .onReady(() =>{
.onReady(() =>{ var grad = this.context.createLinearGradient(50,0, 300,100)
var grad = this.context.createLinearGradient(50,0, 300,100) grad.addColorStop(0.0, 'red')
grad.addColorStop(0.0, 'red') grad.addColorStop(0.5, 'white')
grad.addColorStop(0.5, 'white') grad.addColorStop(1.0, 'green')
grad.addColorStop(1.0, 'green') this.context.fillStyle = grad
this.context.fillStyle = grad this.context.fillRect(0, 0, 500, 500)
this.context.fillRect(0, 0, 500, 500) })
}) }
} .width('100%')
.width('100%') .height('100%')
.height('100%') }}
}} ```
```
![en-us_image_0000001256858381](figures/en-us_image_0000001256858381.png)
\ No newline at end of file
![en-us_image_0000001256858381](figures/en-us_image_0000001256858381.png)
# ImageBitmap # ImageBitmap
> **NOTE**
> **NOTE**
> >
> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. > The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
An **ImageBitmap** object stores pixel data rendered on a canvas. An **ImageBitmap** object stores pixel data rendered on a canvas.
...@@ -11,7 +10,17 @@ An **ImageBitmap** object stores pixel data rendered on a canvas. ...@@ -11,7 +10,17 @@ An **ImageBitmap** object stores pixel data rendered on a canvas.
## Attributes ## Attributes
| Name | Type | Description | | Name| Type| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| width | number | Actual width of the rectangle on the canvas, in pixels. | | width | number | Pixel width of the **ImageBitmap** object.|
| height | number | Actual height of the rectangle on the canvas, in pixels. | | height | number | Pixel height of the **ImageBitmap** object.|
## Methods
### close
close()
Releases all graphics resources associated with this **ImageBitmap** object. This API is a void API.
# ImageData # ImageData
> **NOTE**<br> An **ImageData** object stores pixel data rendered on a canvas.
> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
> **NOTE**
**ImageData** stores pixel data rendered on a canvas. >
> The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
## Attributes ## Attributes
| Name | Type | Description | | Name| Type| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| width | number | Actual width of the rectangle on the canvas, in pixels. | | width | number | Actual width of the rectangle on the canvas, in pixels.|
| height | number | Actual height of the rectangle on the canvas, in pixels. | | height | number | Actual height of the rectangle on the canvas, in pixels.|
| data | &lt;Uint8ClampedArray&gt; | A one-dimensional array of color values. The values range from 0 to 255. | | data | Uint8ClampedArray | A one-dimensional array of color values. The values range from 0 to 255.|
...@@ -3,7 +3,6 @@ ...@@ -3,7 +3,6 @@
**Lottie** allows you to implement animation-specific operations. **Lottie** allows you to implement animation-specific operations.
> **NOTE** > **NOTE**
>
> The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. > The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
...@@ -36,7 +35,7 @@ Loads an animation. Before calling this method, declare the **Animator('\__lotti ...@@ -36,7 +35,7 @@ Loads an animation. Before calling this method, declare the **Animator('\__lotti
- Parameters - Parameters
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------------- | --------------------------- | ---- | ---------------------------------------- | | -------------- | --------------------------- | ---- | ---------------------------------------- |
| path | string | Yes | Path of the animation resource file in the HAP file. The resource file must be in JSON format. Example: **path: "common/lottie/data.json"**. | | path | string | Yes | Path of the animation resource file in the HAP file. The resource file must be in JSON format. Example: **path: "common/lottie/data.json"**|
| container | object | Yes | Canvas drawing context. A **CanvasRenderingContext2D** object must be declared in advance.| | container | object | Yes | Canvas drawing context. A **CanvasRenderingContext2D** object must be declared in advance.|
| render | string | Yes | Rendering type. The value can only be **"canvas"**. | | render | string | Yes | Rendering type. The value can only be **"canvas"**. |
| loop | boolean \| number | No | If the value is of the Boolean type, this parameter indicates whether to repeat the animation cyclically after the animation ends; the default value is **true**. If the value is of the number type and is greater than or equal to 1, this parameter indicates the number of times the animation plays.| | loop | boolean \| number | No | If the value is of the Boolean type, this parameter indicates whether to repeat the animation cyclically after the animation ends; the default value is **true**. If the value is of the number type and is greater than or equal to 1, this parameter indicates the number of times the animation plays.|
...@@ -52,7 +51,7 @@ destroy(name: string): void ...@@ -52,7 +51,7 @@ destroy(name: string): void
Destroys the animation. This method must be called when a page exits. This method can be used together with a lifecycle callback of the **Canvas** component, for example, **onDisappear()** and **onPageHide()**. Destroys the animation. This method must be called when a page exits. This method can be used together with a lifecycle callback of the **Canvas** component, for example, **onDisappear()** and **onPageHide()**.
- Parameters - Parameters
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ---- | ------ | ---- | ---------------------------------------- | | ---- | ------ | ---- | ---------------------------------------- |
| name | string | Yes | Name of the animation to destroy, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are destroyed.| | name | string | Yes | Name of the animation to destroy, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are destroyed.|
...@@ -132,7 +131,7 @@ play(name: string): void ...@@ -132,7 +131,7 @@ play(name: string): void
Plays a specified animation. Plays a specified animation.
- Parameters - Parameters
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ---- | ------ | ---- | ---------------------------------------- | | ---- | ------ | ---- | ---------------------------------------- |
| name | string | Yes | Name of the animation to play, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are played.| | name | string | Yes | Name of the animation to play, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are played.|
...@@ -149,7 +148,7 @@ pause(name: string): void ...@@ -149,7 +148,7 @@ pause(name: string): void
Pauses a specified animation. The next time **lottie.play()** is called, the animation starts from the current frame. Pauses a specified animation. The next time **lottie.play()** is called, the animation starts from the current frame.
- Parameters - Parameters
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ---- | ------ | ---- | ---------------------------------------- | | ---- | ------ | ---- | ---------------------------------------- |
| name | string | Yes | Name of the animation to pause, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are paused.| | name | string | Yes | Name of the animation to pause, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are paused.|
...@@ -166,7 +165,7 @@ togglePause(name: string): void ...@@ -166,7 +165,7 @@ togglePause(name: string): void
Pauses or plays a specified animation. This method is equivalent to the switching between **lottie.play()** and **lottie.pause()**. Pauses or plays a specified animation. This method is equivalent to the switching between **lottie.play()** and **lottie.pause()**.
- Parameters - Parameters
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ---- | ------ | ---- | ---------------------------------------- | | ---- | ------ | ---- | ---------------------------------------- |
| name | string | Yes | Name of the target animation, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are paused.| | name | string | Yes | Name of the target animation, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are paused.|
...@@ -183,7 +182,7 @@ stop(name: string): void ...@@ -183,7 +182,7 @@ stop(name: string): void
Stops the specified animation. The next time **lottie.play()** is called, the animation starts from the first frame. Stops the specified animation. The next time **lottie.play()** is called, the animation starts from the first frame.
- Parameters - Parameters
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ---- | ------ | ---- | ---------------------------------------- | | ---- | ------ | ---- | ---------------------------------------- |
| name | string | Yes | Name of the target animation, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are paused.| | name | string | Yes | Name of the target animation, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are paused.|
...@@ -200,9 +199,9 @@ setSpeed(speed: number, name: string): void ...@@ -200,9 +199,9 @@ setSpeed(speed: number, name: string): void
Sets the playback speed of the specified animation. Sets the playback speed of the specified animation.
- Parameters - Parameters
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ----- | ------ | ---- | ---------------------------------------- | | ----- | ------ | ---- | ---------------------------------------- |
| speed | number | Yes | Playback speed. The value is a floating-point number. If the value is greater than 0, the animation plays forward. If the value is less than 0, the animation plays in backward. If the value is 0, the animation is paused. If the value is **1.0** or **-1.0**, the animation plays at the normal speed.| | speed | number | Yes | Playback speed. The value is a floating-point number. If the value is greater than 0, the animation plays in forward direction. If the value is less than 0, the animation plays in reversed direction. If the value is 0, the animation is paused. If the value is 1.0 or -1.0, the animation plays at the normal speed.|
| name | string | Yes | Name of the target animation, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are stopped.| | name | string | Yes | Name of the target animation, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are stopped.|
- Example - Example
...@@ -218,7 +217,7 @@ setDirection(direction: AnimationDirection, name: string): void ...@@ -218,7 +217,7 @@ setDirection(direction: AnimationDirection, name: string): void
Sets the direction in which the specified animation plays. Sets the direction in which the specified animation plays.
- Parameters - Parameters
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| --------- | ------------------ | ---- | ---------------------------------------- | | --------- | ------------------ | ---- | ---------------------------------------- |
| direction | AnimationDirection | Yes | Direction in which the animation plays. **1**: forwards; **-1**: backwards. When set to play backwards, the animation plays from the current playback progress to the first frame. When this setting is combined with **loop** being set to **true**, the animation plays backwards continuously. When the value of **speed** is less than 0, the animation also plays backwards.<br>AnimationDirection: 1 \| -1 | | direction | AnimationDirection | Yes | Direction in which the animation plays. **1**: forwards; **-1**: backwards. When set to play backwards, the animation plays from the current playback progress to the first frame. When this setting is combined with **loop** being set to **true**, the animation plays backwards continuously. When the value of **speed** is less than 0, the animation also plays backwards.<br>AnimationDirection: 1 \| -1 |
| name | string | Yes | Name of the target animation, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are set.| | name | string | Yes | Name of the target animation, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are set.|
...@@ -264,7 +263,7 @@ play(name?: string): void ...@@ -264,7 +263,7 @@ play(name?: string): void
Plays an animation. Plays an animation.
- Parameters - Parameters
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ---- | ------ | ---- | --------------- | | ---- | ------ | ---- | --------------- |
| name | string | No | Name of the target animation. By default, the value is null.| | name | string | No | Name of the target animation. By default, the value is null.|
...@@ -281,7 +280,7 @@ destroy(name?: string): void ...@@ -281,7 +280,7 @@ destroy(name?: string): void
Destroys an animation. Destroys an animation.
- Parameters - Parameters
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ---- | ------ | ---- | --------------- | | ---- | ------ | ---- | --------------- |
| name | string | No | Name of the target animation. By default, the value is null.| | name | string | No | Name of the target animation. By default, the value is null.|
...@@ -298,7 +297,7 @@ pause(name?: string): void ...@@ -298,7 +297,7 @@ pause(name?: string): void
Pauses an animation. When the **play** interface is called next time, the animation is played from the current frame. Pauses an animation. When the **play** interface is called next time, the animation is played from the current frame.
- Parameters - Parameters
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ---- | ------ | ---- | --------------- | | ---- | ------ | ---- | --------------- |
| name | string | No | Name of the target animation. By default, the value is null.| | name | string | No | Name of the target animation. By default, the value is null.|
...@@ -315,7 +314,7 @@ togglePause(name?: string): void ...@@ -315,7 +314,7 @@ togglePause(name?: string): void
Pauses or plays an animation. This method is equivalent to the switching between **play** and **pause**. Pauses or plays an animation. This method is equivalent to the switching between **play** and **pause**.
- Parameters - Parameters
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ---- | ------ | ---- | --------------- | | ---- | ------ | ---- | --------------- |
| name | string | No | Name of the target animation. By default, the value is null.| | name | string | No | Name of the target animation. By default, the value is null.|
...@@ -332,7 +331,7 @@ stop(name?: string): void ...@@ -332,7 +331,7 @@ stop(name?: string): void
Stops an animation. When the **play** interface is called next time, the animation is played from the first frame. Stops an animation. When the **play** interface is called next time, the animation is played from the first frame.
- Parameters - Parameters
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ---- | ------ | ---- | --------------- | | ---- | ------ | ---- | --------------- |
| name | string | No | Name of the target animation. By default, the value is null.| | name | string | No | Name of the target animation. By default, the value is null.|
...@@ -349,9 +348,9 @@ setSpeed(speed: number): void ...@@ -349,9 +348,9 @@ setSpeed(speed: number): void
Sets the playback speed of an animation. Sets the playback speed of an animation.
- Parameters - Parameters
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ----- | ------ | ---- | ---------------------------------------- | | ----- | ------ | ---- | ---------------------------------------- |
| speed | number | Yes | Playback speed. The value is a floating-point number. If the value is greater than 0, the animation plays forward. If the value is less than 0, the animation plays backward. If the value is 0, the animation is paused.| | speed | number | Yes | Playback speed. The value is a floating-point number. If the value is greater than 0, the animation plays forward. If the value is less than 0, the animation plays backward. If the value is 0, the animation is paused.|If the value is **1.0** or **-1.0**, the animation plays at the normal speed.|
- Example - Example
```ts ```ts
...@@ -405,7 +404,7 @@ goToAndPlay(value: number, isFrame: boolean, name?: string): void ...@@ -405,7 +404,7 @@ goToAndPlay(value: number, isFrame: boolean, name?: string): void
Sets the animation to start from the specified frame or time progress. Sets the animation to start from the specified frame or time progress.
- Parameters - Parameters
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ------- | ------- | ---- | ---------------------------------------- | | ------- | ------- | ---- | ---------------------------------------- |
| value | number | Yes | Frame ID (greater than or equal to 0) or time progress (ms) at which the animation will start. | | value | number | Yes | Frame ID (greater than or equal to 0) or time progress (ms) at which the animation will start. |
| isFrame | boolean | Yes | Whether to set the animation to start from the specified frame. The value **true** means to set the animation to start from the specified frame, and **false** means to set the animation to start from the specified time progress. The default value is **false**.| | isFrame | boolean | Yes | Whether to set the animation to start from the specified frame. The value **true** means to set the animation to start from the specified frame, and **false** means to set the animation to start from the specified time progress. The default value is **false**.|
...@@ -427,7 +426,7 @@ playSegments(segments: AnimationSegment | AnimationSegment[], forceFlag: boolean ...@@ -427,7 +426,7 @@ playSegments(segments: AnimationSegment | AnimationSegment[], forceFlag: boolean
Sets the animation to play only the specified segment. Sets the animation to play only the specified segment.
- Parameters - Parameters
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| --------- | ---------------------------------------- | ---- | ---------------------------------------- | | --------- | ---------------------------------------- | ---- | ---------------------------------------- |
| segments | AnimationSegment = [number, number] \| AnimationSegment[] | Yes | Segment or segment list.<br>If all segments in the segment list are played, only the last segment is played in the next cycle.| | segments | AnimationSegment = [number, number] \| AnimationSegment[] | Yes | Segment or segment list.<br>If all segments in the segment list are played, only the last segment is played in the next cycle.|
| forceFlag | boolean | Yes | Whether the settings take effect immediately. The value **true** means the settings take effect immediately, and **false** means the settings take effect until the current cycle of playback is completed. | | forceFlag | boolean | Yes | Whether the settings take effect immediately. The value **true** means the settings take effect immediately, and **false** means the settings take effect until the current cycle of playback is completed. |
...@@ -477,7 +476,7 @@ setSubframe(useSubFrame: boolean): void ...@@ -477,7 +476,7 @@ setSubframe(useSubFrame: boolean): void
Sets the precision of the **currentFrame** attribute to display floating-point numbers. Sets the precision of the **currentFrame** attribute to display floating-point numbers.
- Parameters - Parameters
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ------------ | ------- | ---- | ---------------------------------------- | | ------------ | ------- | ---- | ---------------------------------------- |
| useSubFrames | boolean | Yes | Whether the **currentFrame** attribute displays floating-point numbers. By default, the attribute displays floating-point numbers.<br>**true**: The **currentFrame** attribute displays floating-point numbers.<br>**false**: The **currentFrame** attribute displays an integer and does not display floating-point numbers.| | useSubFrames | boolean | Yes | Whether the **currentFrame** attribute displays floating-point numbers. By default, the attribute displays floating-point numbers.<br>**true**: The **currentFrame** attribute displays floating-point numbers.<br>**false**: The **currentFrame** attribute displays an integer and does not display floating-point numbers.|
...@@ -494,7 +493,7 @@ getDuration(inFrames?: boolean): void ...@@ -494,7 +493,7 @@ getDuration(inFrames?: boolean): void
Obtains the duration (irrelevant to the playback speed) or number of frames for playing an animation sequence. The settings are related to the input parameter **initialSegment** of the **Lottie.loadAnimation** interface. Obtains the duration (irrelevant to the playback speed) or number of frames for playing an animation sequence. The settings are related to the input parameter **initialSegment** of the **Lottie.loadAnimation** interface.
- Parameters - Parameters
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | ------- | ---- | ---------------------------------------- | | -------- | ------- | ---- | ---------------------------------------- |
| inFrames | boolean | No | Whether to obtain the duration or number of frames.<br>**true**: number of frames.<br>**false**: duration, in ms. The default value is **false**.| | inFrames | boolean | No | Whether to obtain the duration or number of frames.<br>**true**: number of frames.<br>**false**: duration, in ms. The default value is **false**.|
...@@ -511,7 +510,7 @@ addEventListener&lt;T = any&gt;(name: AnimationEventName, callback: AnimationEve ...@@ -511,7 +510,7 @@ addEventListener&lt;T = any&gt;(name: AnimationEventName, callback: AnimationEve
Adds an event listener. After the event is complete, the specified callback function is triggered. This method returns the function object that can delete the event listener. Adds an event listener. After the event is complete, the specified callback function is triggered. This method returns the function object that can delete the event listener.
- Parameters - Parameters
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | ------------------------------- | ---- | ---------------------------------------- | | -------- | ------------------------------- | ---- | ---------------------------------------- |
| name | AnimationEventName | Yes | Animation event type. The available options are as follows:<br>'enterFrame', 'loopComplete', 'complete', 'segmentStart', 'destroy', 'config_ready', 'data_ready', 'DOMLoaded', 'error', 'data_failed', 'loaded_images'| | name | AnimationEventName | Yes | Animation event type. The available options are as follows:<br>'enterFrame', 'loopComplete', 'complete', 'segmentStart', 'destroy', 'config_ready', 'data_ready', 'DOMLoaded', 'error', 'data_failed', 'loaded_images'|
| callback | AnimationEventCallback&lt;T&gt; | Yes | Custom callback. | | callback | AnimationEventCallback&lt;T&gt; | Yes | Custom callback. |
...@@ -535,7 +534,7 @@ removeEventListener&lt;T = any&gt;(name: AnimationEventName, callback?: Animatio ...@@ -535,7 +534,7 @@ removeEventListener&lt;T = any&gt;(name: AnimationEventName, callback?: Animatio
Removes an event listener. Removes an event listener.
- Parameters - Parameters
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | ------------------------------- | ---- | ---------------------------------------- | | -------- | ------------------------------- | ---- | ---------------------------------------- |
| name | AnimationEventName | Yes | Animation event type. The available options are as follows:<br>'enterFrame', 'loopComplete', 'complete', 'segmentStart', 'destroy', 'config_ready', 'data_ready', 'DOMLoaded', 'error', 'data_failed', 'loaded_images'| | name | AnimationEventName | Yes | Animation event type. The available options are as follows:<br>'enterFrame', 'loopComplete', 'complete', 'segmentStart', 'destroy', 'config_ready', 'data_ready', 'DOMLoaded', 'error', 'data_failed', 'loaded_images'|
| callback | AnimationEventCallback&lt;T&gt; | No | Custom callback. By default, the value is null, meaning that all callbacks of the event will be removed. | | callback | AnimationEventCallback&lt;T&gt; | No | Custom callback. By default, the value is null, meaning that all callbacks of the event will be removed. |
......
# Path2D # Path2D
> **NOTE**
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** >
> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. > The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
**Path2D** allows you to describe a path through an existing path. This path can be drawn through the **stroke** API of **Canvas**. **Path2D** allows you to describe a path through an existing path. This path can be drawn through the **stroke** API of **Canvas**.
...@@ -10,18 +10,22 @@ ...@@ -10,18 +10,22 @@
## addPath ## addPath
addPath(path: Object): void addPath(path: path2D, transform?:Matrix2D): void
Adds a path to this path. Adds a path to this path.
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| path | Object | Yes | null | Path to be added to this path. |
- Example | Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- |
``` | path | path2D | Yes| - | Path to be added to this path.|
| transform | Matrix2D | No| null | Transformation matrix of the new path.|
**Example**
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct AddPath { struct AddPath {
...@@ -57,9 +61,10 @@ closePath(): void ...@@ -57,9 +61,10 @@ closePath(): void
Moves the current point of the path back to the start point of the path, and draws a straight line between the current point and the start point. If the shape has already been closed or has only one point, this method does nothing. Moves the current point of the path back to the start point of the path, and draws a straight line between the current point and the start point. If the shape has already been closed or has only one point, this method does nothing.
- Example **Example**
``` ```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct ClosePath { struct ClosePath {
...@@ -96,15 +101,17 @@ moveTo(x: number, y: number): void ...@@ -96,15 +101,17 @@ moveTo(x: number, y: number): void
Moves the current coordinate point of the path to the target point, without drawing a line during the movement. Moves the current coordinate point of the path to the target point, without drawing a line during the movement.
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| x | number | Yes | 0 | X-coordinate of the target point. |
| y | number | Yes | 0 | Y-coordinate of the target point. |
- Example | Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- |
``` | x | number | Yes| 0 | X-coordinate of the target point.|
| y | number | Yes| 0 | Y-coordinate of the target point.|
**Example**
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct MoveTo { struct MoveTo {
...@@ -141,15 +148,17 @@ lineTo(x: number, y: number): void ...@@ -141,15 +148,17 @@ lineTo(x: number, y: number): void
Draws a straight line from the current point to the target point. Draws a straight line from the current point to the target point.
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| x | number | Yes | 0 | X-coordinate of the target point. |
| y | number | Yes | 0 | Y-coordinate of the target point. |
- Example | Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- |
``` | x | number | Yes| 0 | X-coordinate of the target point.|
| y | number | Yes| 0 | Y-coordinate of the target point.|
**Example**
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct LineTo { struct LineTo {
...@@ -187,19 +196,21 @@ bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number, ...@@ -187,19 +196,21 @@ bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number,
Draws a cubic bezier curve on the canvas. Draws a cubic bezier curve on the canvas.
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- | | Name| Type| Mandatory| Default Value| Description|
| cp1x | number | Yes | 0 | X-coordinate of the first parameter of the bezier curve. | | -------- | -------- | -------- | -------- | -------- |
| cp1y | number | Yes | 0 | Y-coordinate of the first parameter of the bezier curve. | | cp1x | number | Yes| 0 | X-coordinate of the first parameter of the bezier curve.|
| cp2x | number | Yes | 0 | X-coordinate of the second parameter of the bezier curve. | | cp1y | number | Yes| 0 | Y-coordinate of the first parameter of the bezier curve.|
| cp2y | number | Yes | 0 | Y-coordinate of the second parameter of the bezier curve. | | cp2x | number | Yes| 0 | X-coordinate of the second parameter of the bezier curve.|
| x | number | Yes | 0 | X-coordinate of the end point on the bezier curve. | | cp2y | number | Yes| 0 | Y-coordinate of the second parameter of the bezier curve.|
| y | number | Yes | 0 | Y-coordinate of the end point on the bezier curve. | | x | number | Yes| 0 | X-coordinate of the end point on the bezier curve.|
| y | number | Yes| 0 | Y-coordinate of the end point on the bezier curve.|
- Example
**Example**
```
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct BezierCurveTo { struct BezierCurveTo {
...@@ -233,17 +244,19 @@ quadraticCurveTo(cpx: number, cpy: number, x: number ,y: number): void ...@@ -233,17 +244,19 @@ quadraticCurveTo(cpx: number, cpy: number, x: number ,y: number): void
Draws a quadratic curve on the canvas. Draws a quadratic curve on the canvas.
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| cpx | number | Yes | 0 | X-coordinate of the bezier curve parameter. |
| cpy | number | Yes | 0 | Y-coordinate of the bezier curve parameter. |
| x | number | Yes | 0 | X-coordinate of the end point on the bezier curve. |
| y | number | Yes | 0 | Y-coordinate of the end point on the bezier curve. |
- Example | Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- |
``` | cpx | number | Yes| 0 | X-coordinate of the bezier curve parameter.|
| cpy | number | Yes| 0 | Y-coordinate of the bezier curve parameter.|
| x | number | Yes| 0 | X-coordinate of the end point on the bezier curve.|
| y | number | Yes| 0 | Y-coordinate of the end point on the bezier curve.|
**Example**
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct QuadraticCurveTo { struct QuadraticCurveTo {
...@@ -274,23 +287,25 @@ Draws a quadratic curve on the canvas. ...@@ -274,23 +287,25 @@ Draws a quadratic curve on the canvas.
## arc ## arc
arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, anticlockwise?: boolean): void arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, counterclockwise?: boolean): void
Draws an arc on the canvas. Draws an arc on the canvas.
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- | | Name| Type| Mandatory| Default Value| Description|
| x | number | Yes | 0 | X-coordinate of the center point of the arc. | | -------- | -------- | -------- | -------- | -------- |
| y | number | Yes | 0 | Y-coordinate of the center point of the arc. | | x | number | Yes| 0 | X-coordinate of the center point of the arc.|
| radius | number | Yes | 0 | Radius of the arc. | | y | number | Yes| 0 | Y-coordinate of the center point of the arc.|
| startAngle | number | Yes | 0 | Start radian of the arc. | | radius | number | Yes| 0 | Radius of the arc.|
| endAngle | number | Yes | 0 | End radian of the arc. | | startAngle | number | Yes| 0 | Start radian of the arc.|
| anticlockwise | boolean | No | false | Whether to draw the arc counterclockwise. | | endAngle | number | Yes| 0 | End radian of the arc.|
| counterclockwise | boolean | No| false | Whether to draw the arc counterclockwise.|
- Example
**Example**
```
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct Arc { struct Arc {
...@@ -323,18 +338,20 @@ arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void ...@@ -323,18 +338,20 @@ arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void
Draws an arc based on the radius and points on the arc. Draws an arc based on the radius and points on the arc.
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| x1 | number | Yes | 0 | X-coordinate of the first point on the arc. |
| y1 | number | Yes | 0 | Y-coordinate of the first point on the arc. |
| x2 | number | Yes | 0 | X-coordinate of the second point on the arc. |
| y2 | number | Yes | 0 | Y-coordinate of the second point on the arc. |
| radius | number | Yes | 0 | Radius of the arc. |
- Example | Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- |
``` | x1 | number | Yes| 0 | X-coordinate of the first point on the arc.|
| y1 | number | Yes| 0 | Y-coordinate of the first point on the arc.|
| x2 | number | Yes| 0 | X-coordinate of the second point on the arc.|
| y2 | number | Yes| 0 | Y-coordinate of the second point on the arc.|
| radius | number | Yes| 0 | Radius of the arc.|
**Example**
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct ArcTo { struct ArcTo {
...@@ -364,25 +381,27 @@ Draws an arc based on the radius and points on the arc. ...@@ -364,25 +381,27 @@ Draws an arc based on the radius and points on the arc.
## ellipse ## ellipse
ellipse(x: number, y: number, radiusX: number, radiusY: number, rotation: number, startAngle: number, endAngle: number, anticlockwise?: number): void ellipse(x: number, y: number, radiusX: number, radiusY: number, rotation: number, startAngle: number, endAngle: number, counterclockwise?: number): void
Draws an ellipse in the specified rectangular region. Draws an ellipse in the specified rectangular region on the canvas.
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| x | number | Yes | 0 | X-coordinate of the ellipse center. |
| y | number | Yes | 0 | Y-coordinate of the ellipse center. |
| radiusX | number | Yes | 0 | Ellipse radius on the x-axis. |
| radiusY | number | Yes | 0 | Ellipse radius on the y-axis. |
| rotation | number | Yes | 0 | Rotation angle of the ellipse, in radians. |
| startAngle | number | Yes | 0 | Angle of the start point for drawing the ellipse, in radians. |
| endAngle | number | Yes | 0 | Angle of the end point for drawing the ellipse, in radians. |
| anticlockwise | number | No | 0 | Whether to draw the ellipse in the counterclockwise direction. The value **0** means to draw the ellipse in the clockwise direction, and **1** means to draw the ellipse in the counterclockwise direction. This parameter is optional. The default value is **0**. |
- Example | Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- |
``` | x | number | Yes| 0 | X-coordinate of the ellipse center.|
| y | number | Yes| 0 | Y-coordinate of the ellipse center.|
| radiusX | number | Yes| 0 | Ellipse radius on the x-axis.|
| radiusY | number | Yes| 0 | Ellipse radius on the y-axis.|
| rotation | number | Yes| 0 | Rotation angle of the ellipse. The unit is radian.|
| startAngle | number | Yes| 0 | Angle of the start point for drawing the ellipse. The unit is radian.|
| endAngle | number | Yes| 0 | Angle of the end point for drawing the ellipse. The unit is radian.|
| counterclockwise | number | No| 0 | Whether to draw the ellipse counterclockwise. The value **0** means to draw the ellipse clockwise, and **1** means to draw the ellipse counterclockwise. This parameter is optional. The default value is **0**. |
**Example**
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct CanvasExample { struct CanvasExample {
...@@ -412,21 +431,23 @@ Draws an ellipse in the specified rectangular region. ...@@ -412,21 +431,23 @@ Draws an ellipse in the specified rectangular region.
## rect ## rect
rect(x: number, y: number, width: number, height: number): void rect(x: number, y: number, w: number, h: number): void
Creates a rectangle. Creates a rectangle on the canvas.
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| x | number | Yes | 0 | X-coordinate of the upper left corner of the rectangle. |
| y | number | Yes | 0 | Y-coordinate of the upper left corner of the rectangle. |
| width | number | Yes | 0 | Width of the rectangle. |
| height | number | Yes | 0 | Height of the rectangle. |
- Example | Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- |
``` | x | number | Yes| 0 | X-coordinate of the upper left corner of the rectangle.|
| y | number | Yes| 0 | Y-coordinate of the upper left corner of the rectangle.|
| w | number | Yes| 0 | Width of the rectangle.|
| h | number | Yes| 0 | Height of the rectangle.|
**Example**
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct CanvasExample { struct CanvasExample {
......
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
> **NOTE** > **NOTE**
> >
> The APIs of this module are supported since API version 9. Updates will be marked with a superscript to indicate their earliest API version. > This component is supported since API version 9. Updates will be marked with a superscript to indicate their earliest API version.
> >
> The APIs of this module are system APIs and cannot be called by third-party applications. > The APIs of this module are system APIs and cannot be called by third-party applications.
......
...@@ -6,10 +6,6 @@ The **\<Indexer>** component can create a logically indexed array of items in a ...@@ -6,10 +6,6 @@ The **\<Indexer>** component can create a logically indexed array of items in a
> >
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
None
## Child Components ## Child Components
...@@ -18,45 +14,52 @@ Not supported ...@@ -18,45 +14,52 @@ Not supported
## APIs ## APIs
AlphabetIndexer(value: {arrayValue : Array&lt;string&gt;, selected : number}) AlphabetIndexer(value: {arrayValue: Array&lt;string&gt;, selected: number})
- Parameters **Parameters**
| Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- |
| arrayValue | Array&lt;string&gt; | Yes| - | Array of strings to be displayed in the alphabetic index bar.|
| selected | number | Yes| - | ID of a selected item.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| arrayValue | Array&lt;string&gt; | Yes| Array of strings to be displayed in the alphabetic index bar.|
| selected | number | Yes | Index of the initially selected item. |
## Attributes ## Attributes
| Name| Type| Description| In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported.
| -------- | -------- | -------- |
| selectedColor | [ResourceColor](../../ui/ts-types.md) | Font color of the selected text.| | Name | Type | Description |
| popupColor | [ResourceColor](../../ui/ts-types.md) | Font color of the pop-up text.| | ----------------------- | --------------- | ----------------------------------------------------------- |
| selectedBackgroundColor | [ResourceColor](../../ui/ts-types.md) | Background color of the selected text.| | color | [ResourceColor](ts-types.md#resourcecolor) | Font color. |
| popupBackground | [ResourceColor](../../ui/ts-types.md) | Background color of the pop-up text.| | selectedColor | [ResourceColor](ts-types.md#resourcecolor) | Font color of the selected text. |
| usingPopup | boolean | Whether to use pop-up text.| | popupColor | [ResourceColor](ts-types.md#resourcecolor) | Font color of the pop-up text. |
| selectedFont | {<br>size?: number,<br>weight?: FontWeight,<br>family?: string,<br>style?: FontStyle<br>} | Font style of the selected text.| | selectedBackgroundColor | [ResourceColor](ts-types.md#resourcecolor) | Background color of the selected item. |
| popupFont | {<br>size?: number,<br>weight?: FontWeight,<br>family?: string,<br>style?: FontStyle<br>} | Font style of the pop-up text.| | popupBackground | [ResourceColor](ts-types.md#resourcecolor) | Background color of the pop-up text. |
| font | {<br>size?: number,<br>weight?: FontWeight,<br>family?: string,<br>style?: FontStyle<br>} | Default font style of the alphabetic index bar.| | usingPopup | boolean | Whether to use pop-up text. |
| itemSize | Length | Size of an item in the alphabetic index bar. The item is a square, and the side length needs to be set.| | selectedFont | [Font](ts-types.md#font) | Font style of the selected text. |
| alignStyle | IndexerAlign | Alignment style of the alphabetic index bar. Left alignment and right alignment are supported. The alignment style affects the position of the pop-up window.| | popupFont | [Font](ts-types.md#font) | Font style of the pop-up text. |
| font | [Font](ts-types.md#font) | Default font style of the alphabetic index bar. |
- IndexerAlign enums | itemSize | string \| number | Size of an item in the alphabetic index bar. The item is a square, and the side length needs to be set. |
| Name| Description| | alignStyle | IndexerAlign | Alignment style of the alphabetic index bar. Left alignment and right alignment are supported.<br>Default value: **IndexerAlign.Right**|
| -------- | -------- | | selected | number | Index of the selected item.|
| Left | The pop-up window is displayed on the right of the alphabetic indexer bar.| | popupPosition | [Position](ts-types.md#position8) | Position of the pop-up window relative to the center of the indexer bar's top border.|
| Right | The pop-up window is displayed on the left of the alphabetic indexer bar.|
## IndexerAlign enums
| Name| Description|
| -------- | -------- |
| Left | The pop-up window is displayed on the right of the alphabetic indexer bar.|
| Right | The pop-up window is displayed on the left of the alphabetic indexer bar.|
## Events ## Events
Only the following events are supported.
| Name| Description| | Name| Description|
| -------- | -------- | | -------- | -------- |
| onSelected(index: number) =&gt; void<sup>(deprecated) </sup>| Invoked when an item in the alphabetic indexer bar is selected.| | onSelected(callback: (index: number) =&gt; void)<sup>(deprecated)</sup> | Invoked when an item in the alphabetic indexer bar is selected. The return value is the index of the selected item. |
| onSelect(index: number) =&gt; void<sup>8+</sup> | Invoked when an item in the alphabetic indexer bar is selected.| | onSelect(callback: (index: number) =&gt; void)<sup>8+</sup> | Invoked when an item in the alphabetic indexer bar is selected. The return value is the index of the selected item. |
| onRequestPopupData(callback: (index: number) =&gt; Array&lt;string&gt;)<sup>8+</sup> | Invoked when a request for displaying content in the index prompt window is sent when an item in the alphabetic indexer bar is selected.<br>The return value is a string array corresponding to the indexes. The string array is displayed vertically in the pop-up window. It can display up to five strings at a time and allows scrolling.| | onRequestPopupData(callback: (index: number) =&gt; Array&lt;string&gt;)<sup>8+</sup> | Invoked when a request for displaying content in the index prompt window is sent after an item in the alphabetic indexer bar is selected.<br>The return value is a string array corresponding to the indexes. The string array is displayed vertically in the pop-up window. It can display up to five strings at a time and allows scrolling.|
| onPopupSelect(callback: (index: number) =&gt; void)<sup>8+</sup> | Invoked when an item in the index pop-up window is selected.| | onPopupSelect(callback: (index: number) =&gt; void)<sup>8+</sup> | Invoked when an item in the index pop-up window is selected. |
## Example ## Example
......
# Badge # Badge
The **\<Badge>** component is a container that can be attached to another component for tagging. The **\<Badge>** component is a container that can be attached to another component for tagging.
> **NOTE** > **NOTE**
> >
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions ## Required Permissions
...@@ -20,46 +19,47 @@ This component supports only one child component. ...@@ -20,46 +19,47 @@ This component supports only one child component.
## APIs ## APIs
Badge(value: {count: number, position?: BadgePosition, maxCount?: number, style?: BadgeStyle}) Method 1: Badge(value: {count: number, position?: BadgePosition, maxCount?: number, style: BadgeStyle})
- Parameters Create a badge.
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| count | number | Yes | - | Number of prompt messages. |
| position | BadgePosition | No | BadgePosition.RightTop | Position to display the badge relative to the parent component. |
| maxCount | number | No | 99 | Maximum number of prompt messages. When the maximum number is reached, only **maxCount+** is displayed. |
| style | BadgeStyle | No | - | Style of the **\<Badge>** component, including the text color, text size, badge color, and badge size. |
Badge(value: {value: string, position?: BadgePosition, style?: BadgeStyle}) **Parameters**
| Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- |
| count | number | Yes| - | Number of notifications.|
| position | BadgePosition | No| BadgePosition.RightTop | Position to display the badge relative to the parent component.|
| maxCount | number | No| 99 | Maximum number of notifications. When the maximum number is reached, only **maxCount+** is displayed.|
| style | BadgeStyle | Yes| - | Style of the **<Badge>** component, including the text color, text size, badge color, and badge size.|
Creates a **\<Badge>** component based on the string. Method 2: Badge(value: {value: string, position?: BadgePosition, style: BadgeStyle})
Creates a badge based on the given string.
- Parameters - Parameters
| Name | Type | Mandatory | Default Value | Description | | Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| value | string | Yes | - | String of the content to prompt. | | value | string | Yes| - | Prompt content.|
| position | BadgePosition | No | BadgePosition.RightTop | Display position of the badge. | | position | BadgePosition | No| BadgePosition.RightTop | Position to display the badge relative to the parent component.|
| style | BadgeStyle | No | - | Style of the **\<Badge>** component, including the text color, text size, badge color, and badge size. | | style | BadgeStyle | Yes| - | Style of the **<Badge>** component, including the text color, text size, badge color, and badge size.|
- BadgeStyle - BadgeStyle
| Name | Type | Mandatory | Default Value | Description | | Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| color | [ResourceColor](../../ui/ts-types.md) | No | Color.White | Text color. | | color | [ResourceColor](ts-types.md#resourcecolor) | No| Color.White | Text color.|
| fontSize | number \| string | No | 10 | Text size. | | fontSize | number \| string | No| 10 | Text size.|
| badgeSize | number \| string | Yes | - | Size of the badge. | | badgeSize | number \| string | Yes| - | Badge size.|
| badgeColor | [ResourceColor](../../ui/ts-types.md) | No | Color.Red | Color of the badge. | | badgeColor | [ResourceColor](ts-types.md#resourcecolor) | No| Color.Red | Badge color.|
- BadgePosition enums - BadgePosition enums
| Name | Description | | Name| Description|
| -------- | -------- | | -------- | -------- |
| Right | The badge is vertically centered on the right of the parent component. | | RightTop | The badge is displayed in the upper right corner of the parent component.|
| RightTop | The badge is displayed in the upper right corner of the parent component. | | Right | The badge is vertically centered on the right of the parent component.|
| Left | The badge is vertically centered on the left of the parent component. | | Left | The badge is vertically centered on the left of the parent component.|
## Example ## Example
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
...@@ -93,7 +93,7 @@ struct BadgeExample { ...@@ -93,7 +93,7 @@ struct BadgeExample {
Badge({ Badge({
value: ' ', value: ' ',
position: 1, position: BadgePosition.Right,
style: { badgeSize: 6, badgeColor: Color.Red } style: { badgeSize: 6, badgeColor: Color.Red }
}) { }) {
Text('message') Text('message')
......
# ColumnSplit # ColumnSplit
> **NOTE**<br> The **\<ColumnSplit>** lays out child components vertically and inserts a horizontal divider between every two child components.
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
> **NOTE**
The **&lt;ColumnSplit&gt;** component lays out child components vertically and inserts a horizontal divider between every two child components. >
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions ## Required Permissions
...@@ -15,7 +15,7 @@ None ...@@ -15,7 +15,7 @@ None
## Child Components ## Child Components
This component can contain child components. Supported
## APIs ## APIs
...@@ -25,18 +25,19 @@ ColumnSplit() ...@@ -25,18 +25,19 @@ ColumnSplit()
## Attributes ## Attributes
| Name | Type | Description | | Name| Type| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| resizeable | boolean | Whether the divider can be dragged. The default value is **false**. | | resizeable | boolean | Whether the divider can be dragged. The default value is **false**.|
> **NOTE**<br> > **NOTE**
> Similar to **&lt;RowSplit&gt;**, the divider of **&lt;ColumnSplit&gt;** can be dragged to a position that just fully holds a component. >
> Similar to **\<RowSplit>**, the divider of **\<ColumnSplit>** can be dragged to a position that just fully holds a component.
## Example ## Example
```ts
``` // xxx.ets
@Entry @Entry
@Component @Component
struct ColumnSplitExample { struct ColumnSplitExample {
......
# Counter # Counter
> **NOTE**
>
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
> **NOTE**<br>
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
The **\<Counter>** component provides an operation to increase or decrease the number.
The **&lt;Counter&gt;** component provides an operation to increase or decrease the number.
## Required Permissions ## Required Permissions
...@@ -15,7 +15,7 @@ None ...@@ -15,7 +15,7 @@ None
## Child Components ## Child Components
This component can contain child components. Supported
## APIs ## APIs
...@@ -25,18 +25,18 @@ Counter() ...@@ -25,18 +25,18 @@ Counter()
## Events ## Events
Except the events listed below, other events, including universal events, are not supported. The universal events and gestures are not supported. Only the following events are supported.
| Name | Description | | Name| Description|
| -------- | -------- | | -------- | -------- |
| onInc(event: () =&gt; void) | Event indicating that the number of monitored objects is increased. | | onInc(event: () =&gt; void) | Invoked when the number of monitored objects is increased. |
| onDec(event: () =&gt; void) | Event indicating that the number of monitored objects is decreased. | | onDec(event: () =&gt; void) | Invoked when the number of monitored objects is decreased. |
## Example ## Example
```ts
``` // xxx.ets
@Entry @Entry
@Component @Component
struct CounterExample { struct CounterExample {
......
# Grid # Grid
The **\<Grid>** component consists of cells formed by rows and columns. You can specify the cells where items are located to form various layouts.
> **NOTE** > **NOTE**
> >
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
The **\<Grid>** component consists of cells formed by rows and columns. You can specify the cells where items are located to form various layouts.
## Required Permissions
None
## Child Components ## Child Components
This component contains the child component **[\<GridItem>](ts-container-griditem.md)**. This component contains the child component **[\<GridItem>](ts-container-griditem.md)**.
## APIs ## Interface
Grid(value:{scroller?: Scroller})
- Parameters Grid(scroller?: Scroller)
| Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- |
| scroller | [Scroller](ts-container-scroll.md#scroller) | Yes| - | Scroller, which can be bound to scrollable components.|
**Parameters**
| Name | Type | Mandatory | Description |
| --------- | ---------------------------------------- | ---- | ----------------------- |
| scroller | [Scroller](ts-container-scroll.md#scroller) | No | Scroller, which can be bound to scrollable components.|
## Attributes ## Attributes
| Name| Type| Default Value| Description| In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported.
| -------- | -------- | -------- | -------- |
| columnsTemplate | string | '1fr' | Number of columns in the current grid layout. If this parameter is not set, one column is used by default. For example, **'1fr 1fr 2fr'** divides the component into three columns, with four equal parts. The first column occupies one part, the second column occupies one part, and the third column occupies two parts.| | Name| Type| Description|
| rowsTemplate | string | '1fr' | Number of rows in the current grid layout. If this parameter is not set, one row is used by default. For example, **'1fr 1fr 2fr'** divides the component into three rows. The width allowed by the parent component is divided into four equal parts. The first row occupies one part, the second row occupies one part, and the third row occupies two parts.| | -------- | -------- | -------- |
| columnsGap | Length | 0 | Spacing between columns.| | columnsTemplate | string | Number of columns in the current grid layout. If this attribute is not set, one column is used by default.<br>For example, **'1fr 1fr 2fr'** indicates three columns, with the first column taking up 1/4 of the parent component's full width, the second column 1/4, and the third column 2/4. This attribute supports [auto-fill] (#auto-fill description).<br>Default value: **'1fr'**|
| rowsGap | Length | 0 | Spacing between rows.| | rowsTemplate | string | Number of rows in the current grid layout. If this attribute is not set, one row is used by default.<br>For example, **'1fr 1fr 2fr'** indicates three rows, with the first row taking up 1/4 of the parent component's full height, the second row 1/4, and the third row 2/4. This attribute supports [auto-fill] (#auto-fill description).<br>Default value: **'1fr'**|
| editMode<font color=ff0000><sup>8+</sup></font> | boolean | false | Whether to enter editing mode. In editing mode, you can drag the **\<[GridItem](ts-container-griditem.md)>** in the **\<Grid>** component.| | columnsGap | Length | Gap between columns.<br>Default value: **0**|
| layoutDirection<font color=ff0000><sup>8+</sup></font> | number | 0 |Main axis direction of the layout. The options are as follows:<br>- **0**: Horizontal layout, where the child components are arranged in the same direction as the main axis runs along the rows.<br>- **1**: Vertical layout, where the child components are arranged in the same direction as the main axis runs down the columns.| | rowsGap | Length | Gap between rows.<br>Default value: **0**|
| maxCount<font color=ff0000><sup>8+</sup></font> | number | 1 | When **layoutDirection** is **Row**: maximum number of rows that can be displayed.<br>When **layoutDirection** is **Column**: maximum number of columns that can be displayed.| | scrollBar | [BarState](ts-appendix-enums.md#barstate) | Scrollbar status.<br>Default value: **BarState.Off**|
| minCount<font color=ff0000><sup>8+</sup></font> | number | 1 | When **layoutDirection** is **Row**: minimum number of rows that can be displayed.<br>When **layoutDirection** is **Column**: minimum number of columns that can be displayed.| | scrollBarColor | string \| number \| Color | Color of the scrollbar.|
| cellLength<font color=ff0000><sup>8+</sup></font> | number | 0 | When **layoutDirection** is **Row**: fixed height per row.<br>When **layoutDirection** is **Column**: fixed width per column.| | scrollBarWidth | string \| number | Width of the scrollbar.|
| multiSelectable<font color=ff0000><sup>8+</sup></font> | boolean | false | Whether to enable mouse frame selection.<br>- **false**: The mouse frame selection is disabled.<br>- **true**: The mouse frame selection is enabled.| | cachedCount | number | Number of grid items to be preloaded. For details, see [Minimizing White Blocks During Swiping](../../ui/ts-performance-improvement-recommendation.md#minimizing-white-blocks-during-swiping).<br>Default value: **1**|
| supportAnimation<font color=ff0000><sup>8+</sup></font> | boolean | false | Whether the grid layout supports animation.| | editMode <sup>8+</sup> | boolean | Whether to enter editing mode. In editing mode, the user can drag the **\<[GridItem](ts-container-griditem.md)>** in the **\<Grid>** component.<br>Default value: **false**|
| layoutDirection<sup>8+</sup> | [GridDirection](#griddirection8) | Main axis direction of the grid.<br>Default value: **GridDirection.Row**|
| maxCount<sup>8+</sup> | number | When **layoutDirection** is **Row** or **RowReverse**: maximum number of rows that can be displayed.<br>When **layoutDirection** is **Column** or **ColumnReverse**: maximum number of columns that can be displayed.<br>Default value: **1**|
| minCount<sup>8+</sup> | number | When **layoutDirection** is **Row** or **RowReverse**: minimum number of rows that can be displayed.<br>When **layoutDirection** is **Column** or **ColumnReverse**: minimum number of columns that can be displayed.<br>Default value: **1**|
| cellLength<sup>8+</sup> | number | When **layoutDirection** is **Row** or **RowReverse**: fixed height per row.<br>When **layoutDirection** is **Column** or **ColumnReverse**: fixed width per column.<br>Default value: **0**|
| multiSelectable<sup>8+</sup> | boolean | Whether to enable mouse frame selection.<br>Default value: **false**<br>- **false**: The mouse frame selection is disabled.<br>- **true**: The mouse frame selection is enabled.|
| supportAnimation<sup>8+</sup> | boolean | Whether to enable animation.<br>Default value: **false**|
## GridDirection<sup>8+</sup>
| Name | Description |
| ------ | -------------------------------------- |
| Row | Horizontal layout, where the child components are arranged from left to right as the main axis runs along the rows.|
| Column | Vertical layout, where the child components are arranged from top to bottom as the main axis runs down the columns.|
| RowReverse | Reverse horizontal layout, where the child components are arranged from right to left as the main axis runs along the rows.|
| ColumnReverse | Reverse vertical layout, where the child components are arranged from bottom up as the main axis runs down the columns.|
## Events ## Events
In addition to the [universal events](ts-universal-events-click.md), the following events are supported.
| Name| Description| | Name| Description|
| -------- | -------- | | -------- | -------- |
| onScrollIndex(first: number) =&gt; void | Triggered when the start item of the grid changes. | | onScrollIndex(event: (first: number) => void) | Triggered when the start item of the grid changes.<br>- **first**: index of the start item of the grid.|
| onItemDragStart(event: (event: ItemDragInfo, itemIndex: number) => (() => any) \| void) | Triggered when a grid item starts to be dragged.<br>- **event**: See [ItemDragInfo](#itemdraginfo).<br>- **itemIndex**: index of the dragged element.|
| onItemDragEnter(event: (event: ItemDragInfo) => void) | Triggered when the dragged item enters the drop target of the grid.<br>- **event**: See [ItemDragInfo](#itemdraginfo).|
| onItemDragMove(event: (event: ItemDragInfo, itemIndex: number, insertIndex: number) => void) | Triggered when the dragged item moves over the drop target of the grid.<br>- **event**: See [ItemDragInfo](#itemdraginfo).<br>- **itemIndex**: initial position of the dragged item.<br>- **insertIndex**: index of the position to which the dragged item will be dropped.|
| onItemDragLeave(event: (event: ItemDragInfo, itemIndex: number) => void) | Triggered when the dragged item exits the drop target of the grid.<br>- **event**: See [ItemDragInfo](#itemdraginfo).<br>- **itemIndex**: index of the dragged item.|
| onItemDrop(event: (event: ItemDragInfo, itemIndex: number, insertIndex: number, isSuccess: boolean) => void) | Triggered when the dragged item is dropped on the drop target of the grid.<br>- **event**: See [ItemDragInfo](#itemdraginfo).<br>- **itemIndex**: initial position of the dragged item.<br>- **insertIndex**: index of the position to which the dragged item will be dropped.<br>- **isSuccess**: whether the dragged item is successfully dropped.|
## Notes About auto-fill
In the **columnsTemplate** and **rowsTemplate** attributes of the **\<Grid>** component, **auto-fill** supports only the following formats:
```css
repeat(auto-fill, track-size)
```
The keywords **repeat** and **auto-fill** are used. **track-size** indicates the row height or column width, which can be in the unit of px, vp, %, or valid digits. The value must contain at least one valid row height or column width.
## ItemDragInfo
| Name | Type | Description |
| ---------- | ---------- | ---------- |
| x | number | X-coordinate of the dragged item. |
| y | number | Y-coordinate of the dragged item. |
## Example ## Example
...@@ -114,5 +144,51 @@ struct GridExample { ...@@ -114,5 +144,51 @@ struct GridExample {
} }
``` ```
![en-us_image_0000001212218434](figures/en-us_image_0000001212218434.gif) ![zh-cn_image_0000001219744183](figures/zh-cn_image_0000001219744183.gif)
**Example of auto-fill**
```ts
// grid-autofill.ets
@Entry
@Component
struct Index {
@State gridItemWidth: string = "100%"
@State gridItemHeight: string = "100%"
@State gridWidth: string = "100%"
@State gridHeight: string = "100%"
@State itemList: string[] = []
build() {
Column() {
Grid() {
ForEach(this.itemList, (item) => {
GridItem() {
Text(item.toString())
.fontSize(16)
.width('100%')
.textAlign(TextAlign.Center)
}
.width(this.gridItemWidth)
.height(this.gridItemHeight)
.backgroundColor(0xF9CF93)
}, item => item)
}
.columnsGap(1)
.rowsGap(1)
.border({ width: 4, color: 0xffdb7093, style: BorderStyle.Dashed, radius: 5 })
.width(this.gridWidth)
.height(this.gridHeight)
.columnsTemplate("15% repeat(auto-fill, 10% 50px 20%) 50px")
.rowsTemplate("150px repeat(auto-fill, 20% 25%)")
}.margin(5)
}
aboutToAppear() {
for(var i = 1; i < 50; i++) {
this.itemList.push(i.toString())
}
}
}
```
![grid-autofill](figures/grid-autofill.png)
# GridCol
The **\<GridCol>** component must be used as a child component of the [GridRow](ts-container-gridrow.md) container.
> **NOTE**
>
> This component is supported since API version 9. Updates will be marked with a superscript to indicate their earliest API version.
## Child Components
This component can contain only one child component.
## APIs
GridCol(option?:{span?: number | GridColColumnOption, offset?: number | GridColColumnOption, order?: number | GridColColumnOption})
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ----------------------------- | ---- | ------------------------------------------------------------ |
| span | number \| GridColColumnOption | No | Number of occupied columns. If it is set to **0**, the element is not involved in layout calculation, that is, the element is not rendered.<br>Default value: **1**|
| offset | number \| GridColColumnOption | No | Number of offset columns relative to the previous child component of the grid<br>Default value: **0** |
| order | number \| GridColColumnOption | No | Sequence number of the element. Child components of the grid are sorted in ascending order based on their sequence numbers.<br>Default value: **0**|
## Attributes
| Name| Type | Mandatory| Description |
| ------ | ----------------------------- | ---- | ------------------------------------------------------------ |
| span | number \| GridColColumnOption | No | Number of occupied columns. If it is set to **0**, the element is not involved in layout calculation, that is, the element is not rendered.<br>Default value: **1**|
| offset | number \| GridColColumnOption | No | Number of offset columns relative to the previous child component of the grid<br>Default value: **0** |
| order | number \| GridColColumnOption | No | Sequence number of the element. Child components of the grid are sorted in ascending order based on their sequence numbers.<br>Default value: **0**|
## GridColColumnOption
| Name | Type | Mandatory | Description |
| ----- | ------ | ---- | ---------------------------------------- |
| xs | number | No | Device of the minimum size. |
| sm | number | No | Small-sized device. |
| md | number | No | Medium-sized device. |
| lg | number | No | Large-sized device. |
| xl | number | No | Extra-large-sized device. |
| xxl | number | No | Ultra-large-sized device. |
The values of `span`, `offset`, and `order` attributes are inherited in the sequence of `xs`, `sm`, `md`, `lg`, `xl`, and `xxl`. If no value is set for a breakpoint, the value is obtained from the previous breakpoint.
|Parameter\Breakpoint|xs|sm|md|lg|xl|xxl|
|---|---|---|---|---|---|---|
|span |2 |2 |3 |3 |4 |4 |
|offset |2 |2 |3 |5 |5 |5 |
|order |20 |20 |20 |3 |3 |3 |
## Example
See [GridRow](ts-container-gridrow.md#example).
# GridContainer # GridContainer
The **\<GridContainer>** component lays out components vertically. It is used only in the grid layout.
> **NOTE**<br> > **NOTE**
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. >
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
The **<GridContainer\>** component lays out components vertically. It is used only in the grid layout.
## Required Permissions
None
## Child Components ## Child Components
This component can contain child components. Supported
## APIs ## APIs
GridContainer(options?: { columns?: number | 'auto', sizeType?: SizeType, gutter?: Length, margin?: Length}) GridContainer(value?: { columns?: number | 'auto', sizeType?: SizeType, gutter?: number | string, margin?: number | string})
- Parameter **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| columns | number \| 'auto' | No | 'auto' | Total number of columns in the current layout. |
| sizeType | SizeType | No | SizeType.Auto | Device size type. |
| gutter | Length | No | - | Gutter of the grid layout. |
| margin | Length | No | - | Margin of the grid layout. |
- SizeType enums | Name| Type| Mandatory| Description|
| Name | Description | | -------- | -------- | -------- | -------- |
| -------- | -------- | | columns | number \| 'auto' | No| Total number of columns in the current layout.<br>Default value: **'auto'**|
| XS | Minimum-sized device. | | sizeType | SizeType | No| Device size type.<br>Default value: **SizeType.Auto**|
| SM | Small-sized device. | | gutter | number \| string | No| Gutter of the grid layout.|
| MD | Medium-sized device. | | margin | number \| string | No| Margin of the grid layout.|
| LG | Large-sized device. |
| Auto | Auto. The size type is selected based on the device type. | ## SizeType
| Name| Description|
| -------- | -------- |
| XS | Device of the minimum size.|
| SM | Small-sized device.|
| MD | Medium-sized device.|
| LG | Large-sized device.|
| Auto | Auto. The size type is selected based on the device type.|
## Attributes ## Attributes
Universal attributes and [attributes](ts-container-column.md#attributes) of the **<Column\>** component are supported. The universal attributes and attributes of the **[<Column\>](ts-container-column.md#attributes)** component are supported.
## Events ## Events
Universal events are supported. The universal events are supported.
## Example ## Example
```ts
``` // xxx.ets
@Entry @Entry
@Component @Component
struct GridContainerExample { struct GridContainerExample {
......
# GridItem # GridItem
The **\<GridItem>** component provides a single item in a grid.
> **NOTE**<br> > **NOTE**
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. >
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
The **&lt;GridItem&gt;** component provides a single item in a grid.
## Required Permissions
None
## Child Components ## Child Components
This component can contain child components. Supported
## APIs ## APIs
...@@ -25,27 +19,27 @@ GridItem() ...@@ -25,27 +19,27 @@ GridItem()
## Attributes ## Attributes
| Name | Type | Default Value | Description | | Name| Type| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- |
| rowStart | number | - | Start row number of the component. | | rowStart | number | Start row number of the component.|
| rowEnd | number | - | End row number of the component. | | rowEnd | number | End row number of the component.|
| columnStart | number | - | Start column number of the component. | | columnStart | number | Start column number of the component.|
| columnEnd | number | - | End column number of the component. | | columnEnd | number | End column number of the component.|
| forceRebuild | boolean | false | Whether to re-create this node when the component is being built. | | forceRebuild | boolean | Whether to re-create the component when it is being built.<br>Default value: **false**|
| selectable<sup>8+</sup> | boolean | true | Whether the current **&lt;GridItem&gt;** is selectable by the mouse.<br/>**NOTE**<br/>This attribute takes effect only when mouse frame selection is enabled for the parent **&lt;Grid&gt;** container. | | selectable<sup>8+</sup> | boolean | Whether the current grid item is selectable by the mouse.<br>> **NOTE**<br>> This attribute takes effect only when mouse frame selection is enabled for the parent **\<Grid>** container.<br>Default value: **true**|
## Events ## Events
| Name | Description | | Name| Description|
| -------- | -------- | | -------- | -------- |
| onSelect(callback: (isSelected: boolean) =&gt; any)<sup>8+</sup> | Triggered when the selected state of the **&lt;GridItem&gt;** changes.<br/>**isSelected**: Returns **true** if the **&lt;GridItem&gt;** is selected by the mouse; returns **false** otherwise. | | onSelect(event: (isSelected: boolean) =&gt; void)<sup>8+</sup> | Triggered when the selected state of the grid item changes.<br>**isSelected**: Returns **true** if the grid item is selected by the mouse; returns **false** otherwise.|
## Example ## Example
```ts
``` // xxx.ets
@Entry @Entry
@Component @Component
struct GridItemExample { struct GridItemExample {
......
# GridRow
The **\<GridRow>** component is used in a grid layout, together with its child component **[\<GridCol>](ts-container-gridcol.md)**.
> **NOTE**
>
> This component is supported since API version 9. Updates will be marked with a superscript to indicate their earliest API version.
## Child Components
This component can contain the **\<GridCol>** child component.
## APIs
GridRow(option?: {columns?: number | GridRowColumnOption, gutter?: Length | GutterOption, breakpoints?: BreakPoints, direction?: GridRowDirection})
**Parameters**
| Name|Type|Mandatory|Description|
|-----|-----|----|----|
|gutter|Length \| GutterOption| No |Gutter of the grid layout. **x** indicates the horizontal direction.|
|columns| number \| GridRowColumnOption | No |Number of columns in the grid layout.|
|breakpoints|BreakPoints| No |Array of breakpoints for the breakpoint value and the corresponding reference based on the window or container size.|
|direction|GridRowDirection| No |Arrangement direction of the grid layout.|
## GutterOption
| Name | Type | Mandatory | Description |
| ----- | ------ | ---- | ---------------------------------------- |
| x | Length \| GridRowSizeOption | No | Gutter in the horizontal direction. |
| y | Length \| GridRowSizeOption | No | Gutter in the vertical direction. |
## GridRowColumnOption
Describes the numbers of grid columns for different device width types.
| Name | Type | Mandatory | Description |
| ----- | ------ | ---- | ---------------------------------------- |
| xs | number | No | Device of the minimum size. |
| sm | number | No | Small-sized device. |
| md | number | No | Medium-sized device. |
| lg | number | No | Large-sized device. |
| xl | number | No | Extra-large-sized device. |
| xxl | number | No | Ultra-large-sized device. |
## GridRowSizeOption
Describes the gutter sizes for different device width types.
| Name | Type | Mandatory | Description |
| ----- | ------ | ---- | ---------------------------------------- |
| xs | Length | No | Device of the minimum size. |
| sm | Length | No | Small-sized device. |
| md | Length | No | Medium-sized device. |
| lg | Length | No | Large-sized device. |
| xl | Length | No | Extra-large-sized device. |
| xxl | Length | No | Ultra-large-sized device. |
## BreakPoints
| Name | Type | Mandatory | Description |
| ----- | ------ | ---- | ---------------------------------------- |
| value | Array&lt;string&gt; | No | Array of monotonically increasing breakpoints.<br>Default value: **["320vp", "520vp", "840vp"]** |
| reference | BreakpointsReference | No | Breakpoint switching reference.|
```ts
// Enable the xs, sm, and md breakpoints.
breakpoints: {value: ["100vp", "200vp"]}
// Enable four breakpoints: xs, sm, md, and lg. The breakpoint range must be monotonically increasing.
breakpoints: {value: ["320vp", "520vp", "840vp"]}
// Enable five breakpoints: xs, sm, md, lg, and xl. The number of breakpoint ranges cannot exceed the number of breakpoints minus 1.
breakpoints: {value: ["320vp", "520vp", "840vp", "1080vp"]}
```
## BreakpointsReference
| Name| Description|
| -------- | -------- |
| WindowSize | The window is used as a reference.|
| ComponentSize | The container is used as a reference.|
## GridRowDirection
| Name| Description|
| -------- | -------- |
| Row | Grid elements are arranged in the row direction.|
| RowReverse | Grid elements are arranged in the reverse row direction.|
A grid supports a maximum of six breakpoints: xs, sm, md, lg, xl and xxl, whose names cannot be changed. Assume that the input array is [n0, n1, n2, n3, n4], then the value ranges of breakpoints are as follows.
|Breakpoint|Value Range|
|---|-----------|
|xs |[0, n0) |
|sm |[n0, n1) |
|md |[n1, n2) |
|lg |[n2, n3) |
|xl |[n3, n4) |
|xxl|[n4, INF) |
**NOTE**
* Grid elements can be arranged only in the **Row** or **RowReverse** direction, but not in the **Column** or **ColumnReverse** direction.
* The location and size of a grid child component can be calculated only based on **span** and **offset**. If the **span** values of child components add up to a number greater than the allowed number of columns, the grid will automatically wraps lines.
* If the **span** value of a single child component exceeds the maximum number of columns, the maximum number of columns is used.
* If a child component takes up more than the total number of columns according to its **offset** and **span** settings, it will be placed in a new row.
* Below is the display effect of **Item1: GridCol({span: 6}), Item2: GridCol({ span: 8, offset:11})**.
|1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 |
| ----- | ------ | ---- | ---- | -----|-----|---------|--------|------|------- |------- |------- |
| $\circ$ | $\circ$ | $\circ$ | $\circ$ | $\circ$|$\circ$| - | - | - | - | - | - |
| - | - | - | - | - | | | | | | | |
| $\circ$ | $\circ$ | $\circ$ | $\circ$ | $\circ$|$\circ$|$\circ$|$\circ$| | | | |
## Attributes
The [universal attributes](ts-universal-attributes-size.md) are supported.
## Events
### onBreakpointChange
onBreakpointChange(callback: (breakpoints: string) => void)
**Parameters**
| Name | Type | Mandatory | Description |
| ----- | ------ | ---- | ---------------------------------------- |
|breakpoints| string |Yes|Breakpoint change.<br>The value can be `"xs"`, `"sm"`, `"md"`, `"lg"`, `"xl"`, or `"xxl"`.|
## Example
```ts
// xxx.ets
@Entry
@Component
struct GridRowExample {
@State bgColors: Color[] = [Color.Red, Color.Orange, Color.Yellow, Color.Green, Color.Pink, Color.Grey, Color.Blue, Color.Brown]
@State currentBp: string = 'unknown'
build() {
Column() {
GridRow({
columns: 5,
gutter: {x:5, y:10},
breakpoints: {value:["400vp", "600vp", "800vp"],
reference: BreakpointsReference.WindowSize},
direction: GridRowDirection.Row
}) {
ForEach(this.bgColors, (color)=>{
GridCol({ span: {xs:1, sm:2, md:3, lg:4}}) {
Row().width("100%").height("20vp")
}.borderColor(color).borderWidth(2)
})
}.width("100%").height("100%")
.onBreakpointChange((breakpoint) => {
this.currentBp = breakpoint
})
}.width('80%').margin({ left: 10,top: 5, bottom:5 }).height(200)
.border({color:Color.Blue, width:2})
}
}
```
![figures/gridrow.png](figures/gridrow.png)
# List # List
The **\<list>** component provides a list container that presents a series of list items arranged in a column with the same width. It supports presentations of the same type of data in a multiple and coherent row style, for example, images or text.
> **NOTE** > **NOTE**
> >
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > - This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
> - This component can produce a bounce effect only when there is more than one screen of content.
The **\<List>** component provides a list container that presents a series of list items arranged in columns with the same width. It supports presentation of the same type of data, for example, images or text, in a multiple and coherent row style. ## Child Components
This component supports the [\<ListItem]>(ts-container-listitem.md) and [\<ListItemGroup>](ts-container-listitemgroup.md) child components.
## Required Permissions
None ## APIs
List(value?:{space?: number | string, initialIndex?: number, scroller?: Scroller})
## Child Components **Parameters**
This component contains the child component [\<ListItem>](ts-container-listitem.md). | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| space | number \| string | No| Spacing between list items.<br>Default value: **0**|
| initialIndex | number | No| Item displayed at the beginning of the viewport when the current list is loaded for the first time, that is, the first item to be displayed. If the value set is greater than the sequence number of the last item, the setting does not take effect.<br>Default value: **0**|
| scroller | [Scroller](ts-container-scroll.md#scroller) | No| Controller bound to the list to control the scrolling.|
## Attributes
## APIs In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported.
List(value:{space?: number | string, initialIndex?: number, scroller?: Scroller}) | Name| Type| Description|
| -------- | -------- | -------- |
| listDirection | [Axis](ts-appendix-enums.md#axis) | Direction in which the list items are arranged.<br>Default value: **Axis.Vertical**|
| divider | {<br>strokeWidth: [Length](ts-types.md#length),<br>color?:[ResourceColor](ts-types.md#resourcecolor),<br>startMargin?: Length,<br>endMargin?: Length<br>} \| null | Style of the divider for the list items. By default, there is no divider.<br>- **strokeWidth**: stroke width of the divider.<br>- **color**: color of the divider.<br>- **startMargin**: distance between the divider and the start edge of the list.<br>- **endMargin**: distance between the divider and the end edge of the list.|
| scrollBar | [BarState](ts-appendix-enums.md#barstate) | Scrollbar status.<br>Default value: **BarState.Off**|
| cachedCount | number | Number of list items to be preloaded. For details, see [Minimizing White Blocks During Swiping](../../ui/ts-performance-improvement-recommendation.md#minimizing-white-blocks-during-swiping).<br>Default value: **1**|
| editMode | boolean | Whether to enter editing mode.<br>Default value: **false**|
| edgeEffect | [EdgeEffect](ts-appendix-enums.md#edgeeffect) | Scroll effect.<br>Default value: **EdgeEffect.Spring**|
| chainAnimation | boolean | Whether to display chained animations on this list when it slides or its top or bottom is dragged. The list items are separated with even space, and one item animation starts after the previous animation during basic sliding interactions. The chained animation effect is similar with spring physics.<br>Default value: **false**<br>- **false**: No chained animations are displayed.<br>- **true**: Chained animations are displayed.|
| multiSelectable<sup>8+</sup> | boolean | Whether to enable mouse frame selection.<br>Default value: **false**<br>- **false**: The mouse frame selection is disabled.<br>- **true**: The mouse frame selection is enabled.|
| lanes<sup>9+</sup> | number \| [LengthConstrain](ts-types.md#lengthconstrain) | In the following description, **listDirection** is set to **Axis.Vertical**:<br>Number of columns in which the list items are arranged along the cross axis.<br>Default value: **1**<br>The rules are as follows:<br>- If the value is set to a number, the column width is determined based on the specified number and the cross-axis width of the **\<List>** component.<br>- If the value is set to {minLength, maxLength}, the number of columns is adjusted adaptively based on the width of the **\<List>** component, ensuring that the width respects the {minLength, maxLength} constraints during adaptation. The **minLength** constraint is prioritized. For example, if **lanes** is set to **{minLength: 40vp, maxLength: 60vp}** and the width of the **\<List>** component is 70 vp, the list items are arranged in one column with their alignment compliant with the **alignListItem** settings. If the width of the **\<List>** component is changed to 80 vp, which is twice the value of **minLength**, the list items are arranged in two columns.|
| alignListItem<sup>9+</sup> | ListItemAlign | Alignment mode of list items along the cross axis when: Cross-axis width of the **\<List>** component > Cross-axis width of list items x Value of **lanes**.<br>Default value: **ListItemAlign.Start**|
| sticky<sup>9+</sup> | StickyStyle | Whether to pin the header to the top or the footer to the bottom in the **\<ListItemGroup>** component. This attribute is used together with the **\<ListItemGroup>** component.<br>Default value: **StickyStyle.None**<br>**NOTE**<br>The **sticky** attribute can be set to **StickyStyle.Header** or **StickyStyle.Footer** to support both the pin-to-top and pin-to-bottom features. |
- Parameters ## ListItemAlign<sup>9+</sup>
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| space | number&nbsp;\|&nbsp;string | No | 0 | Spacing between list items. |
| initialIndex | number | No | 0 | Item displayed at the beginning of the viewport when the current list is loaded for the first time, that is, the first item to be displayed. If the value set is greater than the sequence number of the last item, the setting does not take effect. |
| scroller | [Scroller](ts-container-scroll.md#scroller) | No | - | Controller bound to the list to control the scrolling. |
| Name | Description |
| ------ | -------------------------------------- |
| Start | The list items are packed toward the start edge of the **\<List>** component along the cross axis.|
| Center | The list items are centered in the **\<List>** component along the cross axis.|
| End | The list items are packed toward the end edge of the **\<List>** component in the cross axis.|
## Attributes ## StickyStyle<sup>9+</sup>
| Name | Description |
| ------ | -------------------------------------- |
| None | In the **\<ListItemGroup>** component, the header is not pinned to the top, and the footer is not pinned to the bottom.|
| Header | In the **\<ListItemGroup>** component, the header is pinned to the top.|
| Footer | In the **\<ListItemGroup>** component, the footer is pinned to the bottom.|
| Name | Type | Default Value | Description |
| -------- | -------- | -------- | -------- |
| listDirection | [Axis](ts-appendix-enums.md#axis-enums) | Vertical | Direction in which the list items are arranged. For details, see **Axis** enums. |
| divider | {<br>strokeWidth: Length,<br>color?:Color,<br>startMargin?: Length,<br>endMargin?: Length<br>} | - | Style of the divider for the list items. By default, there is no divider.<br>**strokeWidth**: stroke width of the divider.<br>**color**: color of the divider.<br>**startMargin**: distance between the divider and the start of the list.<br>**endMargin**: distance between the divider and the end of the list. |
| editMode | boolean | false | Whether the **\<List>** component is in editable mode. |
| edgeEffect | EdgeEffect | EdgeEffect.Spring | Sliding effect. For details, see **EdgeEffect enums**. |
| chainAnimation | boolean | false | Whether to display chained animations on this list when it slides or its top and bottom are dragged. The list items are separated with even space, and one item animation starts after the previous animation during basic sliding interactions. The chained animation effect is similar with spring physics.<br>- **false**: No chained animations are displayed.<br>- **true**: Chained animations are displayed. |
| multiSelectable<sup>8+</sup> | boolean | false | Whether to enable mouse frame selection.<br>- **false**: The mouse frame selection is disabled.<br>- **true**: The mouse frame selection is enabled. |
| restoreId<sup>8+</sup> | number | - | Migration ID of the component. During application migration, the status of the component is migrated to the component with the same migration ID on the peer end.<br>For a **<\List>** component, the status includes the item serial number displayed at the start position. |
| lanes<sup>9+</sup> | number \|<br>{<br>minLength: Length,<br>maxLength: Length<br>} | 1 | In the following description, **listDirection** is set to **Axis.Vertical**:<br>Number of columns in which the list items are arranged along the cross axis.<br>- If the value type is number, the column width is determined based on the specified number and the cross-axis width of the **\<List>** component.<br>- If the value type is {minLength, maxLength}, the number of columns is adjusted adaptively based on the width of the **\<List>** component, ensuring that the width respects the {minLength, maxLength} constraints during adaptation. The **minLength** constraint is prioritized. For example, if **lanes** is set to **{minLength: 40vp, maxLength: 60vp}** and the width of the **\<List>** component is 70 vp, the list items are arranged in one column with their alignment compliant with the **alignListItem** settings. If the width of the **\<List>** component is changed to 80 vp, which is twice the value of **minLength**, the list items are arranged in two columns.|
| alignListItem<sup>9+</sup> | ListItemAlign | ListItemAlign.Center | Alignment mode of list items along the cross axis when: Cross-axis width of the **\<List>** component > Cross-axis width of list items x Value of **lanes**.|
- EdgeEffect enums
| Name | Description |
| -------- | -------- |
| Spring | Similar to the physical dynamic effect of a spring. After scrolling to the edge, the user can continue to scroll for a distance based on the initial speed or by touching the knob of the scrollbar. After the user releases their hand, the knob is rebounded. |
| None | No effect when the list is scrolled to the edge. |
- ListItemAlign enums
| Name | Description |
| ------ | -------------------------------------- |
| Start | The list items are packed toward the start edge of the **\<List>** component along the cross axis.|
| Center | The list items are centered in the **\<List>** component along the cross axis.|
| End | The list items are packed toward the end edge of the **\<List>** component in the cross axis.|
## Events ## Events
| Name | Description | | Name| Description|
| -------- | -------- | | -------- | -------- |
| onItemDelete(index: number) =&gt; boolean | Triggered when a list item is deleted. | | onItemDelete(event: (index: number) => boolean) | Triggered when a list item is deleted.<br>- **index**: index of the deleted list item.|
| onScrollBegin<sup>9+</sup>(dx: number, dy: number)&nbsp;=&gt;&nbsp;{ dxRemain: number, dyRemain: number } | Triggered when scrolling starts.<br/>Parameters:<br/>- **dx**: amount by which the list will scroll in the horizontal direction.<br/>- **dy**: amount by which the list will scroll in the vertical direction.<br/>Return value:<br/>- **dxRemain**: remaining amount by which the list can scroll in the horizontal direction.<br/>- **dyRemain**: remaining amount by which the list can scroll in the vertical direction. | | onScroll(event: (scrollOffset: number, scrollState: ScrollState) => void) | Triggered when the list scrolls.<br>- **scrollOffset**: scroll offset.<br>- **[scrollState](#scrollstate)**: current scroll state. |
| onScrollIndex(firstIndex:&nbsp;number,&nbsp;lastIndex:&nbsp;number)&nbsp;=&gt;&nbsp;void | Triggered when the start position and end position of the current list are changed. | | onScrollIndex(event: (start: number, end: number) => void) | Triggered when scrolling starts.<br>When calculating the index value, the **\<ListItemGroup>** accounts for one index value as a whole, and the index values of the list items within are not calculated.<br>- **start**: index of the scroll start position.<br>- **end**: index of the scroll end position.|
| onReachStart(event: () => void) | Triggered when the list reaches the start position.|
> **NOTE** | onReachEnd(event: () => void) | Triggered when the list reaches the end position.|
| onScrollBegin<sup>9+</sup>(event: (dx: number, dy: number) => { dxRemain: number, dyRemain: number }) | Triggered when the list starts to scroll.<br>- **dx**: amount by which the list will scroll in the horizontal direction.<br>- **dy**: amount by which the list will scroll in the vertical direction.<br>- **dxRemain**: remaining amount by which the list can scroll in the horizontal direction.<br>- **dyRemain**: remaining amount by which the list can scroll in the vertical direction.|
| onScrollStop(event: () => void) | Triggered when the list stops scrolling.|
| onItemMove(event: (from: number, to: number) => boolean) | Triggered when a list item moves.<br>- **from**: index of the item before moving.<br>- **to**: index of the item after moving.|
| onItemDragStart(event: (event: ItemDragInfo, itemIndex: number) => ((() => any) \| void) | Triggered when a list element starts to be dragged.<br>- **event**: See [ItemDragInfo](ts-container-grid.md#itemdraginfo).<br>- **itemIndex**: index of the dragged list element.|
| onItemDragEnter(event: (event: ItemDragInfo) => void) | Triggered when the dragged item enters the drop target of the list.<br>- **event**: See [ItemDragInfo](ts-container-grid.md#itemdraginfo).|
| onItemDragMove(event: (event: ItemDragInfo, itemIndex: number, insertIndex: number) => void) | Triggered when the dragged item moves over the drop target of the list.<br>- **event**: See [ItemDragInfo](ts-container-grid.md#itemdraginfo).<br>- **itemIndex**: initial position of the dragged item.<br>- **insertIndex**: index of the position to which the dragged item will be dropped.|
| onItemDragLeave(event: (event: ItemDragInfo, itemIndex: number) => void) | Triggered when the dragged item exits the drop target of the list.<br>- **event**: See [ItemDragInfo](ts-container-grid.md#itemdraginfo).<br>- **itemIndex**: index of the list item.|
| onItemDrop(event: (event: ItemDragInfo, itemIndex: number, insertIndex: number, isSuccess: boolean) => void) | Triggered when the dragged item is dropped on the drop target of the list.<br>- **event**: See [ItemDragInfo](ts-container-grid.md#itemdraginfo).<br>- **itemIndex**: initial position of the dragged item.<br>- **insertIndex**: index of the position to which the dragged item will be dropped.<br>- **isSuccess**: whether the dragged item is successfully dropped.|
## ScrollState
| Name | Description |
| ------ | ------------------------- |
| Idle | Not scrolling. |
| Scroll | Inertial scrolling. |
| Fling | Finger dragging. |
> **NOTE**
> >
> To enable the editable mode for a list, the following conditions must be met: > To enable the editable mode for a list, the following conditions must be met:
> >
> - **editMode** is set to **true**. > - **editMode** is set to **true**.
> >
> - The list is bound to the **onItemDelete** event, and the event returns **true** through a callback. > - The list is bound to the **onItemDelete** event and the event returns **true** in the event callback.
> >
> - The **editable** attribute of **ListItem** is set to **true**. > - The **editable** attribute of **ListItem** is set to **true**.
> >
> To enable dragging for a list item, the following conditions must be met: > To enable dragging for a list item, the following conditions must be met:
> >
> - **editMode** is set to **true**. > - **editMode** is set to **true**.
> >
> - The list item is bound to the **onDragStart** event, and the event returns a floating UI through a callback. > - The list item is bound to the **onDragStart** event and the event returns a floating UI during event callback.
## Example ## Example
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
...@@ -108,9 +126,9 @@ struct ListExample { ...@@ -108,9 +126,9 @@ struct ListExample {
}.editable(true) }.editable(true)
}, item => item) }, item => item)
} }
.listDirection(Axis.Vertical) // Direction in which the list items are arranged. .listDirection(Axis.Vertical) // Arrangement direction
.divider({ strokeWidth: 2, color: 0xFFFFFF, startMargin: 20, endMargin: 20 }) // Style of the divider for the list items. .divider({ strokeWidth: 2, color: 0xFFFFFF, startMargin: 20, endMargin: 20 }) // Divider
.edgeEffect(EdgeEffect.None) // No effect when the list is scrolled to the edge. .edgeEffect(EdgeEffect.None) // No effect when the list scrolls to the edge.
.chainAnimation(false) // Chained animations are disabled. .chainAnimation(false) // Chained animations are disabled.
.onScrollIndex((firstIndex: number, lastIndex: number) => { .onScrollIndex((firstIndex: number, lastIndex: number) => {
console.info('first' + firstIndex) console.info('first' + firstIndex)
...@@ -168,7 +186,7 @@ struct ListLanesExample { ...@@ -168,7 +186,7 @@ struct ListLanesExample {
.lanes({ minLength: 40, maxLength: 60 }) .lanes({ minLength: 40, maxLength: 60 })
.alignListItem(this.alignListItem) .alignListItem(this.alignListItem)
Button("Change alignListItem:" + this.alignListItem).onClick(() => { Button("Change alignListItem: "+ this.alignListItem).onClick(() => {
if (this.alignListItem == ListItemAlign.Start) { if (this.alignListItem == ListItemAlign.Start) {
this.alignListItem = ListItemAlign.Center this.alignListItem = ListItemAlign.Center
} else if (this.alignListItem == ListItemAlign.Center) { } else if (this.alignListItem == ListItemAlign.Center) {
...@@ -181,4 +199,3 @@ struct ListLanesExample { ...@@ -181,4 +199,3 @@ struct ListLanesExample {
} }
} }
``` ```
# ListItem # ListItem
The **\<ListItem>** component displays specific items in the list. Its width occupies the **\<List>** component by default and must be used together with **\<List>**.
> **NOTE**<br> > **NOTE**
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. >
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
The **&lt;ListItem&gt;** component displays specific items in the list. Its width occupies the **&lt;List&gt;** component by default and must be used together with **&lt;List&gt;**.
## Required Permissions
None
## Child Components ## Child Components
...@@ -20,35 +14,51 @@ This component can contain a single child component. ...@@ -20,35 +14,51 @@ This component can contain a single child component.
## APIs ## APIs
ListItem() ListItem(value?: string)
## Attributes ## Attributes
| Name | Type | Default Value | Description | In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported.
| -------- | -------- | -------- | -------- |
| sticky | Sticky | Sticky.None | Sticky effect of the list item. For details, see **Sticky** enums. | | Name| Type| Description|
| editable | boolean | false | Whether the list item is editable. A list item can be deleted in editing mode. | | -------- | -------- | -------- |
| selectable<sup>8+</sup> | boolean | true | Whether the current **ListItem;** is selectable by the mouse.<br/>**NOTE**<br/>This attribute takes effect only when mouse frame selection is enabled for the parent **&lt;List&gt;** container. | | sticky | [Sticky](#sticky)| Sticky effect of the list item.<br>Default value: **Sticky.None**|
| editable | boolean \| [EditMode](#editmode)| Whether to enter editing mode, where the list item can be deleted or moved.<br>Default value: **false**|
| selectable<sup>8+</sup> | boolean | Whether the current list item is selectable by mouse drag.<br>**NOTE**<br>This attribute takes effect only when mouse frame selection is enabled for the parent **\<List>** container.<br>Default value: **true**|
| swipeAction<sup>9+</sup> | {<br>start?: CustomBuilder,<br>end?:CustomBuilder,<br>edgeEffect?: [SwipeEdgeEffect](#swipeedgeeffect9),<br>} | Component displayed when the list item is swiped out from the screen edge.<br>- **start**: component on the left of the list item when the item is swiped to the right (in vertical list layout) or component above the list item when the item is swiped down (in horizontal list layout).<br>- **end**: component on the right of the list item when the item is swiped to the left (in vertical list layout) or component below the list item when the item is swiped up (in horizontal list layout).<br>- **edgeEffect**: scroll effect.<br>|
- Sticky enums ## Sticky
| Name | Description | | Name| Description|
| -------- | -------- | | -------- | -------- |
| None | No sticky. | | None | The list item is not sticky.|
| Normal | The list item is sticky. | | Normal | The list item is sticky with no special effects.|
| Opacity | The list item is sticky with opacity changes.|
## EditMode
| Name | Description |
| ------ | --------- |
| None | The editing operation is not restricted. |
| Deletable | The list item can be deleted.|
| Movable | The list item can be moved.|
## SwipeEdgeEffect<sup>9+</sup>
| Name| Description|
| -------- | -------- |
| Spring | When the list item scrolls to the edge of the list, it can continue to scroll for a distance and rebound after being released.|
| None | The list item cannot scroll beyond the edge of the list|
## Events ## Events
| Name | Description | | Name| Description|
| -------- | -------- | | -------- | -------- |
| onSelect(callback: (isSelected: boolean) =&gt; any)<sup>8+</sup> | Triggered when the selected state of the **&lt;ListItem&gt;** changes.<br/>**isSelected**: Returns **true** if the **&lt;ListItem&gt;** is selected by the mouse; returns **false** otherwise. | | onSelect(event: (isSelected: boolean) =&gt; void)<sup>8+</sup> | Triggered when the selected state of the **\<ListItem>** changes.<br>**isSelected**: Returns **true** if the **\<ListItem>** is selected by mouse drag; returns **false** otherwise.|
## Example ## Example
```ts
``` // xxx.ets
@Entry @Entry
@Component @Component
struct ListItemExample { struct ListItemExample {
...@@ -88,3 +98,54 @@ struct ListItemExample { ...@@ -88,3 +98,54 @@ struct ListItemExample {
``` ```
![en-us_image_0000001257138339](figures/en-us_image_0000001257138339.gif) ![en-us_image_0000001257138339](figures/en-us_image_0000001257138339.gif)
```ts
// xxx.ets
@Entry
@Component
struct ListItemExample2 {
@State message: string = 'Hello World'
@Builder itemEnd() {
Row () {
Button("Del").margin("4vp")
Button("Set").margin("4vp")
}.padding("4vp").justifyContent(FlexAlign.SpaceEvenly)
}
build() {
Column() {
List({space:10}) {
ListItem() {
Text(this.message) {
}
.width('100%')
.height(100)
.fontSize(16)
.textAlign(TextAlign.Center)
.borderRadius(10)
.backgroundColor(0xFFFFFF)
}
.swipeAction({ end:this.itemEnd})
ListItem() {
Text(this.message) {
}
.width('100%')
.height(100)
.fontSize(16)
.textAlign(TextAlign.Center)
.borderRadius(10)
.backgroundColor(0xFFFFFF)
}
.swipeAction({ start:this.itemEnd})
}
}
.padding(10)
.backgroundColor(0xDCDCDC)
.width('100%')
.height('100%')
}
}
```
![en-us_image_1501929990650](figures/en-us_image_1501929990650.jpg)
# ListItemGroup
The **\<ListItemGroup>** component is used to display list item groups. It must be used with the **[\<List>](ts-container-list.md)** and, if not otherwise specified, takes up the entire width of the **\<List>** component.
> **NOTE**
>
> This component is supported since API version 9. Updates will be marked with a superscript to indicate their earliest API version.
## Usage Guidelines
If the **listDirection** attribute of the parent **\<List>** component is set to **Axis.Vertical**, the **height** attribute of the **\<ListItemGroup>** component cannot be set. The height of a **\<ListItemGroup>** component is the sum of its header height, footer height, and total height of the list items. If the **listDirection** attribute of the parent **\<List>** component is set to **Axis.Horizontal**, the **width** attribute of the **\<ListItemGroup>** component cannot be set. The width of a **\<ListItemGroup>** component is the sum of its header width, footer width, and total width of the list items.
Currently, the list items in the **\<ListItemGroup>** component cannot be edited, selected, or dragged. That is, the **editable** and **selectable** attributes of these list items do not take effect.
## Child Components
This component supports the **[\<ListItem>](ts-container-listitem.md)** child component.
## APIs
ListItemGroup(options?: {header?: CustomBuilder, footer?: CustomBuilder, space?: number | string})
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| header | [CustomBuilder](ts-types.md#custombuilder8) | No| Header of the **\<ListItemGroup>** component.|
| footer | [CustomBuilder](ts-types.md#custombuilder8) | No| Footer of the **\<ListItemGroup>** component.|
| space | number \| string | No| Spacing between list items. This parameter is valid only between list items, but not between a header and list item or between a footer and list item.|
## Attributes
| Name| Type| Description|
| -------- | -------- | -------- |
| divider | {<br>strokeWidth: [Length](ts-types.md#length),<br>color?: [ResourceColor](ts-types.md#resourcecolor),<br>startMargin?: [Length](ts-types.md#length),<br>endMargin?: [Length](ts-types.md#length)<br>} \| null | Style of the divider for the list items. By default, there is no divider.<br>- **strokeWidth**: stroke width of the divider.<br>- **color**: color of the divider.<br>**startMargin**: distance between the divider and the start of the list.<br>**endMargin**: distance between the divider and the end of the list.|
## Example
```ts
// xxx.ets
function itemHeadBuilder(text: string) {
@Builder function itemHead() {
Text(text)
.fontSize(20)
.backgroundColor(0xAABBCC)
.width("100%")
.padding(10)
}
return itemHead
}
function itemFootBuilder(num: number) {
@Builder function itemFoot() {
Text('' + num + " lessons in total ")
.fontSize(16)
.backgroundColor(0xAABBCC)
.width("100%")
.padding(5)
}
return itemFoot
}
@Entry
@Component
struct ListItemGroupExample {
private timetable: any = [
{
title: 'Monday',
projects: ['Language', 'Math', 'English']
},
{
title: 'Tuesday',
projects: ['Physics', 'Chemistry', 'Biologics']
},
{
title: 'Wednesday',
projects: ['History', 'Geography', 'Politics']
},
{
title: 'Thursday',
projects: ['Art', 'Music', 'Sports']
}
]
build() {
Column() {
List({ space: 20 }) {
ForEach(this.timetable, (item) => {
ListItemGroup({ header:itemHeadBuilder(item.title), footer:itemFootBuilder(item.projects.length) }) {
ForEach(item.projects, (project) => {
ListItem() {
Text(project)
.width("100%").height(100).fontSize(20)
.textAlign(TextAlign.Center).backgroundColor(0xFFFFFF)
}
}, item => item)
}
.borderRadius(20)
.divider({ strokeWidth: 1, color: 0xDCDCDC }) // Divider between lines
})
}
.width('90%')
.sticky(StickyStyle.Header|StickyStyle.Footer)
}.width('100%').height('100%').backgroundColor(0xDCDCDC).padding({ top: 5 })
}
}
```
# Navigator # Navigator
The **\<Navigator>** component provides redirection.
> **NOTE** > **NOTE**
> >
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
The **\<Navigator>** component provides redirection to the target page.
## Required Permissions
None
## Child Components ## Child Components
This component can contain child components. Supported
## APIs ## APIs
Navigator(value?: {target: string, type?: NavigationType}) Navigator(value?: {target: string, type?: NavigationType})
Creates a navigator. **Parameters**
| Name| Type | Mandatory| Description |
| ------ | -------------- | ---- | ---------------------------------------------- |
| target | string | Yes | Path of the target page to be redirected to. |
| type | NavigationType | No | Navigation type.<br>Default value: **NavigationType.Push**|
- Parameters ## NavigationType
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| target | string | Yes | - | Path of the target page to be redirected to. |
| type | NavigationType | No | NavigationType.Push | Navigation type. |
- NavigationType enums | Name | Description |
| Name | Description | | ------- | -------------------------- |
| -------- | -------- | | Push | Navigates to a specified page in the application. |
| Push | Navigates to a specified page in the application. | | Replace | Replaces the current page with another one in the application and destroys the current page.|
| Replace | Replaces the current page with another one in the application and destroys the current page. | | Back | Returns to the previous page or a specified page. |
| Back | Returns to the previous page or a specified page. |
## Attributes ## Attributes
| Name | Parameters | Default Value | Description | | Name | Parameter | Description |
| -------- | -------- | -------- | -------- | | ------ | ------- | ------------------------------------------------------------ |
| active | boolean | - | Whether the **\<Navigator>** component is activated. If the component is activated, the corresponding navigation takes effect. | | active | boolean | Whether the **\<Navigator>** component is activated. If the component is activated, the corresponding navigation takes effect.|
| params | Object | undefined | Data that needs to be passed to the target page during redirection. You can use **router.getParams()** to obtain the data on the target page. | | params | object | Data that needs to be passed to the target page during redirection. You can use **router.getParams()** to obtain the data on the target page.|
| target | string | Path of the target page to be redirected to. |
| type | NavigationType | Navigation mode.<br>Default value: **NavigationType.Push**|
## Example ## Example
```ts ```ts
// Navigator.ets // Navigator.ets
@Entry @Entry
...@@ -76,7 +70,6 @@ struct NavigatorExample { ...@@ -76,7 +70,6 @@ struct NavigatorExample {
} }
``` ```
```ts ```ts
// Detail.ets // Detail.ets
import router from '@system.router' import router from '@system.router'
......
...@@ -2,68 +2,66 @@ ...@@ -2,68 +2,66 @@
The **<Panel\>** component is a slidable panel that presents lightweight content with flexible sizes. The **<Panel\>** component is a slidable panel that presents lightweight content with flexible sizes.
> **NOTE** > **NOTE**
> >
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
None
## Child Components ## Child Components
This component can contain child components. Supported
## APIs ## APIs
Panel(value:{show:boolean}) Panel(show: boolean)
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- | | Name| Type| Mandatory| Description|
| show | boolean | Yes | - | Whether to show or hide the panel. | | -------- | -------- | -------- | -------- |
| show | boolean | Yes| Whether the panel is shown or hidden.|
## Attributes ## Attributes
| Name | Type | Default Value | Description | | Name| Type| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- |
| type | PanelType | PanelType.Foldable | Type of the panel. | | type | PanelType | Type of the panel.<br>Default value: **PanelType.Foldable**|
| mode | PanelMode | - | Initial status of the panel. | | mode | PanelMode | Initial status of the panel.|
| dragBar | boolean | true | Whether to enable a drag bar. The value **true** means to display the drag bar, and **false** means the opposite. | | dragBar | boolean | Whether to enable a drag bar. The value **true** means that the drag bar will be displayed, and **false** means the opposite.<br>Default value: **true**|
| fullHeight | Length | - | Panel height in the **PanelMode.Full** mode. | | fullHeight | string \| number | Panel height in the **PanelMode.Full** mode.|
| halfHeight | Length | - | Panel height in the **PanelMode.Half** mode. The default value is half of the screen height. | | halfHeight | string \| number | Panel height in the **PanelMode.Half** mode. The default value is half of the screen height.|
| miniHeight | Length | - | Panel height in the **PanelMode.Mini** mode. | | miniHeight | string \| number | Panel height in the **PanelMode.Mini** mode.|
| backgroundMask<sup>9+</sup>|(color: ResourceColor)| - |Background mask of the panel.| | show | boolean | Whether to show the panel.|
| backgroundMask<sup>9+</sup>|[ResourceColor](ts-types.md#resourcecolor)|Background mask of the panel.|
- PanelType enums
| Name | Description | ## PanelType
| -------- | -------- |
| Minibar | A minibar panel that displays content in the minibar area or a large (fullscreen-like) area. | | Name| Description|
| Foldable | A foldable panel that displays permanent content in a large (fullscreen-like), medium-sized (halfscreen-like), or small area. | | -------- | -------- |
| Temporary | A temporary panel that displays content in a large (fullscreen-like) or medium-sized (halfscreen-like) area. | | Minibar | A minibar panel displays content in the minibar area or a large (fullscreen-like) area.|
| Foldable | A foldable panel displays permanent content in a large (fullscreen-like), medium-sized (halfscreen-like), or small area.|
- PanelMode enums | Temporary | A temporary panel displays content in a large (fullscreen-like) or medium-sized (halfscreen-like) area.|
| Name | Description |
| -------- | -------- | ## PanelMode
| Mini | Display of a minibar or foldable panel in its minimum size. This attribute does not take effect for **temporary** panels. |
| Half | Display of a foldable or temporary panel in a medium-sized (halfscreen-like) area. This attribute does not take effect for **minibar** panels. | | Name| Description|
| Full | Display of a panel in a large (fullscreen-like) area. | | -------- | -------- |
| Mini | Displays a **minibar** or **foldable** panel in its minimum size. This attribute does not take effect for **temporary** panels.|
| Half | Displays a **foldable** or **temporary** panel in a medium-sized (halfscreen-like) area. This attribute does not take effect for **minibar** panels.|
| Full | Displays a panel in a large (fullscreen-like) area.|
## Events ## Events
| Name | Description | | Name| Description|
| -------- | -------- | | -------- | -------- |
| onChange(callback: (width: number, height: number, mode: PanelMode) =&gt; void) | Triggered when the panel status changes. The returned **height** value is the height of the content area. When the value of **dragbar** is **true**, the panel height is the height of the drag bar plus the height of the content area. | | onChange(event: (width: number, height: number, mode: PanelMode) =&gt; void) | Triggered when the status of the panel changes. The returned height value is the height of the content area. When the value of **dragBar** is **true**, the height of the panel is the **dragBar** height plus the height of the content area.|
| onHeightChange(callback: (value: number) => void)<sup>9+</sup> |Triggered when the panel height changes. The returned **height** value is the height of the content area. When the value of **dragbar** is **true**, the panel height is the height of the drag bar plus the height of the content area. For user experience purposes, the panel can be slid to only this height: **fullHeight** - 8 vp. | | onHeightChange(callback: (value: number) => void)<sup>9+</sup> |Triggered when the status of the panel changes. The returned height value is the height of the content area. When the value of **dragBar** is **true**, the height of the panel is the **dragBar** height plus the height of the content area. For user experience purposes, the panel can be slid to only this height: **fullHeight** - 8 vp.|
## Example ## Example
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
...@@ -79,7 +77,7 @@ struct PanelExample { ...@@ -79,7 +77,7 @@ struct PanelExample {
.onClick(() => { .onClick(() => {
this.show = !this.show this.show = !this.show
}) })
Panel(this.show) { // Display the agenda. Panel(this.show) { // Display the agenda.
Column() { Column() {
Text('Today Calendar') Text('Today Calendar')
Divider() Divider()
...@@ -87,8 +85,8 @@ struct PanelExample { ...@@ -87,8 +85,8 @@ struct PanelExample {
} }
} }
.type(PanelType.Foldable).mode(PanelMode.Half) .type(PanelType.Foldable).mode(PanelMode.Half)
.dragBar(true) // The drag bar is enabled by default. .dragBar(true) // The dragbar is enabled by default.
.halfHeight(500) // The default value is half of the screen height. .halfHeight(500) // The panel height is half of the screen height by default.
.onChange((width: number, height: number, mode: PanelMode) => { .onChange((width: number, height: number, mode: PanelMode) => {
console.info(`width:${width},height:${height},mode:${mode}`) console.info(`width:${width},height:${height},mode:${mode}`)
}) })
......
...@@ -6,25 +6,21 @@ ...@@ -6,25 +6,21 @@
> >
> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. > This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
None
## Child Components ## Child Components
This component supports only one child component. This component supports only one child component.
## APIs ## APIs
Refresh\(value: \{ refreshing: boolean, offset?: Length, friction?: number | string \}\) Refresh\(value: \{ refreshing: boolean, offset?: number | string , friction?: number | string \}\)
- Parameters **Parameters**
| Name| Value Type| Mandatory| Default Value| Description| | Name| Value Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| refreshing | boolean | Yes| - | Whether the current component is being refreshed.<br/>This parameter can be used with [$$](../../ui/ts-syntactic-sugar.md) for two-way binding of variables. | | refreshing | boolean | Yes| Whether the current component is being refreshed.<br>This parameter can be used with [$$](../../ui/ts-syntactic-sugar.md) for two-way binding of variables.|
| offset | Length | No| 16 | Distance to the top of the parent component from the **<Refresh\>** component that comes to rest after a successful pull-down gesture.| | offset | string \| number | No| Distance to the top of the parent component from the **<Refresh\>** component that comes to rest after a successful pull-down gesture.<br>Default value: **16**, in vp|
| friction | number&nbsp;\|&nbsp;string | No| 62 | Coefficient of friction, which indicates the **<Refresh\>** component's sensitivity to the pull-down gesture. The value ranges from 0 to 100.<br>- **0** indicates that the **\<Refresh>** component is not sensitive to the pull-down gesture.<br>- **100** indicates that the **\<Refresh>** component is highly sensitive to the pull-down gesture.<br>- A larger value indicates a more sensitive response of the **\<Refresh>** component to the pull-down gesture.| | friction | number \| string | No| Coefficient of friction, which indicates the **<Refresh\>** component's sensitivity to the pull-down gesture. The value ranges from 0 to 100.<br>Default value: **62**<br>- **0** indicates that the **\<Refresh>** component is not sensitive to the pull-down gesture.<br>- **100** indicates that the **\<Refresh>** component is highly sensitive to the pull-down gesture.<br>- A larger value indicates a more sensitive response of the **\<Refresh>** component to the pull-down gesture.|
...@@ -33,18 +29,18 @@ Refresh\(value: \{ refreshing: boolean, offset?: Length, friction?: number | str ...@@ -33,18 +29,18 @@ Refresh\(value: \{ refreshing: boolean, offset?: Length, friction?: number | str
| Name| Description| | Name| Description|
| -------- | -------- | | -------- | -------- |
| onStateChange(callback: (state: RefreshStatus) => void)| Triggered when the refresh status changes.<br>**state**: refresh status.| | onStateChange(callback: (state: RefreshStatus) => void)| Triggered when the refresh status changes.<br>- **state**: refresh status.|
| onRefreshing(callback: () => void)| Triggered when the component enters the refresh state.| | onRefreshing(callback: () => void)| Triggered when the component enters the refresh state.|
- RefreshStatus enums ## RefreshStatus enums
| Name| Description| | Name| Description|
| -------- | -------- | | -------- | -------- |
| Inactive | The component is not pulled down. This is the default value.| | Inactive | The component is not pulled down. This is the default value.|
| Drag | The component is being pulled down, but the pulled distance is shorter than the minimum length required to trigger the refresh.| | Drag | The component is being pulled down, but the pulled distance is shorter than the minimum length required to trigger the refresh.|
| OverDrag | The component is being pulled down, and the pulled distance exceeds the minimum length required to trigger the refresh.| | OverDrag | The component is being pulled down, and the pulled distance exceeds the minimum length required to trigger the refresh.|
| Refresh | The pull-down ends, and the component rebounds to the minimum length required to trigger the refresh and enters the refresh state.| | Refresh | The pull-down ends, and the component rebounds to the minimum length required to trigger the refresh and enters the refresh state.|
| Done | The refresh is complete, and the component returns to the initial state (top).| | Done | The refresh is complete, and the component returns to the initial state (top).|
## Example ## Example
......
...@@ -6,8 +6,6 @@ The **\<RelativeContainer>** component is used for element alignment in complex ...@@ -6,8 +6,6 @@ The **\<RelativeContainer>** component is used for element alignment in complex
> >
> This component is supported since API version 9. Updates will be marked with a superscript to indicate their earliest API version. > This component is supported since API version 9. Updates will be marked with a superscript to indicate their earliest API version.
## Rules ## Rules
* Components in a container are aligned horizontally or vertically. * Components in a container are aligned horizontally or vertically.
......
# Row # Row
> **NOTE**
>
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
The **<Row\>** component lays out child components horizontally. The **<Row\>** component lays out child components horizontally.
> **NOTE**
## Required Permissions >
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
None
## Child Components ## Child Components
...@@ -20,20 +14,21 @@ Supported ...@@ -20,20 +14,21 @@ Supported
## APIs ## APIs
Row(value?:{space?: Length}) Row(value?:{space?: number | string })
**Parameters**
- Parameters | Name| Type| Mandatory| Description|
| Name| Type| Mandatory| Default Value| Description| | -------- | -------- | -------- | -------- |
| -------- | -------- | -------- | -------- | -------- | | space | string \| number | No| Space between two adjacent child components in the horizontal layout.<br>Default value: **0**|
| space | Length | No| 0 | Space between two adjacent child components in the horizontal layout.|
## Attributes ## Attributes
| Name| Type| Default Value| Description| | Name| Type| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- |
| alignItems | [VerticalAlign](ts-appendix-enums.md#verticalalign) | VerticalAlign.Center | Alignment mode of the child components in the vertical direction.| | alignItems | [VerticalAlign](ts-appendix-enums.md#verticalalign) | Alignment mode of child components in the vertical direction.<br>Default value: **VerticalAlign.Center**|
| justifyContent<sup>8+</sup> | [FlexAlign](ts-appendix-enums.md#flexalign) | FlexAlign.Start | Alignment mode of the child components in the horizontal direction.| | justifyContent<sup>8+</sup> | [FlexAlign](ts-appendix-enums.md#flexalign) | Alignment mode of the child components in the horizontal direction.<br>FlexAlign.Start |
## Example ## Example
...@@ -79,4 +74,4 @@ struct RowExample { ...@@ -79,4 +74,4 @@ struct RowExample {
} }
``` ```
![en-us_image_0000001174422908](figures/row.png) ![en_us_image_0000001174422908](figures/row.png)
# RowSplit # RowSplit
> **NOTE**
> **NOTE**<br>
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
The **<RowSplit\>** component lays out child components horizontally and inserts a vertical divider between every two child components. The **\<RowSplit>** lays out child components horizontally and inserts a vertical divider between every two child components.
## Required Permissions ## Required Permissions
...@@ -15,7 +14,7 @@ None ...@@ -15,7 +14,7 @@ None
## Child Components ## Child Components
This component can contain child components. Supported
## APIs ## APIs
...@@ -25,18 +24,18 @@ RowSplit() ...@@ -25,18 +24,18 @@ RowSplit()
## Attributes ## Attributes
| Name | Type | Description | | Name| Type| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| resizeable | boolean | Whether the divider is draggable. The default value is **false**. | | resizeable | boolean | Whether the divider can be dragged. The default value is **false**.|
> **NOTE**<br> > **NOTE**
> Similar to **<RowSplit\>**, the divider of **<RowSplit\>** can be dragged to a position that just fully holds a component. > Similar to **\<RowSplit>**, the divider of **\<RowSplit>** can be dragged to a position that just fully holds a component.
## Example ## Example
```ts
``` // xxx.ets
@Entry @Entry
@Component @Component
struct RowSplitExample { struct RowSplitExample {
......
# Scroll # Scroll
The **\<Scroll>** component scrolls the content when the layout size of a component exceeds the size of its parent component.
> **NOTE** > **NOTE**
> - This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > - This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
> - When nesting a **\<List>** within this component, specify the width and height for the **\<List>** under scenarios where consistently high performance is required. If the width and height are not specified, this component will load all content of the **\<List>**. > - When nesting a **\<List>** within this component, specify the width and height for the **\<List>** under scenarios where consistently high performance is required. If the width and height are not specified, this component will load all content of the **\<List>**.
> - This component can produce a bounce effect only when there is more than one screen of content. > - This component can scroll only when the size on the main axis is less than the content size.
> - The prerequisite for the component to rebound is that the component is scrolled.
The **\<Scroll>** component scrolls the content when the layout size of a component exceeds the viewport of its parent component.
## Required Permissions
None.
## Child Components ## Child Components
...@@ -23,47 +18,42 @@ This component supports only one child component. ...@@ -23,47 +18,42 @@ This component supports only one child component.
Scroll(scroller?: Scroller) Scroll(scroller?: Scroller)
## Attributes ## Attributes
| Name | Type | Default Value | Description | In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported.
| -------------- | ---------------------------------------- | ------------------------ | --------- |
| scrollable | ScrollDirection | ScrollDirection.Vertical | Scroll method. |
| scrollBar | [BarState](ts-appendix-enums.md#barstate) | BarState.Off | Scrollbar status. |
| scrollBarColor | string&nbsp;\|&nbsp;number&nbsp;\|&nbsp;Color | - | Color of the scrollbar.|
| scrollBarWidth | Length | - | Width of the scrollbar.|
| edgeEffect | EdgeEffect | EdgeEffect.Spring | Scroll effect. For details, see **EdgeEffect**.|
## ScrollDirection | Name | Type | Description |
| Name | Description | | -------------- | ---------------------------------------- | --------- |
| ---------- | ---------- | | scrollable | ScrollDirection | Scroll direction.<br>Default value: **ScrollDirection.Vertical**|
| Horizontal | Only horizontal scrolling is supported.| | scrollBar | [BarState](ts-appendix-enums.md#barstate) | Scrollbar status.<br>Default value: **BarState.Off**|
| Vertical | Only vertical scrolling is supported.| | scrollBarColor | string \| number \| Color | Color of the scrollbar.|
| None | Scrolling is disabled. | | scrollBarWidth | string \| number | Width of the scrollbar.|
| edgeEffect | [EdgeEffect](ts-appendix-enums.md#edgeeffect) | Scroll effect. For details, see **EdgeEffect**.<br>Default value: **EdgeEffect.Spring**|
## EdgeEffect ## ScrollDirection
| Name | Description |
| Name | Description | | ---------- | ------------------------ |
| ------ | ---------------------------------------- | | Horizontal | Only horizontal scrolling is supported. |
| Spring | Spring effect. When at one of the edges, the component can move beyond the bounds through touches, and produces a bounce effect when the user releases their finger.| | Vertical | Only vertical scrolling is supported. |
| Fade | Fade effect. When at one of the edges, the component produces a fade effect. | | None | Scrolling is disabled. |
| None | No effect when the component is at one of the edges. | | Free<sup>(deprecated) </sup> | Vertical or horizontal scrolling is supported.<br> This API is deprecated since API version 9.|
## Events ## Events
| Name | Description | | Name | Description |
| ---------------------------------------- | ----------------------------- | | ------------------------------------------------------------ | ------------------------------------------------------------ |
| onScrollBegin<sup>9+</sup>(dx: number, dy: number)&nbsp;=&gt;&nbsp;{ dxRemain: number, dyRemain: number } | Invoked when scrolling starts.<br>Parameters:<br>- **dx**: amount to scroll by in the horizontal direction.<br>- **dy**: amount to scroll by in the vertical direction.<br>Return value:<br>- **dxRemain**: remaining amount to scroll by in the horizontal direction.<br>- **dyRemain**: remaining amount to scroll by in the vertical direction.| | onScrollBegin<sup>9+</sup>(event: (dx: number, dy: number) => { dxRemain: number, dyRemain: number }) | Invoked when scrolling starts.<br>Parameters:<br>- **dx**: amount to scroll by in the horizontal direction.<br>- **dy**: amount to scroll by in the vertical direction.<br>Return value:<br>- **dxRemain**: remaining amount to scroll by in the horizontal direction.<br>- **dyRemain**: remaining amount to scroll by in the vertical direction.|
| onScroll(event: (xOffset: number, yOffset: number) => void) | Invoked to return the horizontal and vertical offsets during scrolling when the specified scroll event occurs.| | onScroll(event: (xOffset: number, yOffset: number) => void) | Invoked to return the horizontal and vertical offsets during scrolling when the specified scroll event occurs. |
| onScrollEdge(event: (side: Edge) => void) | Invoked when scrolling reaches the edge. | | onScrollEdge(event: (side: Edge) => void) | Invoked when scrolling reaches the edge. |
| onScrollEnd(event: () => void) | Invoked when scrolling stops. | | onScrollEnd(event: () => void) | Invoked when scrolling stops. |
> **NOTE** > **NOTE**
> If the **onScrollBegin** event and **scrollBy** API are used to implement nested scrolling, you must set **edgeEffect** of the scrolling child node to **None**. For example, if a **\<List>** is nested in the **\<Scroll>** component, the **edgeEffect** attribute of the **\<List>** must be set to **EdgeEffect.None**. >
> If the **onScrollBegin** event and **scrollBy** API are used to implement nested scrolling, you must set **edgeEffect** of the scrolling child node to **None**. For example, if a **\<List>** is nested in the **\<Scroll>** component, the **edgeEffect** attribute of the **\<List>** must be set to **EdgeEffect.None**.
## Scroller ## Scroller
Implements a controller for a scrollable container component. You can bind this component to a container component and use it to control the scrolling of that component. Currently, this component can be bound to the **\<Scroll>** and **\<ScrollBar>** components. Implements a controller for a scrollable container component. You can bind this component to a container component and use it to control the scrolling of that component. Currently, this controller can be bound to the **\<List>**, **\<Scroll>** and **\<ScrollBar>** components. One controller can control only one container component.
### Objects to Import ### Objects to Import
...@@ -80,13 +70,13 @@ scrollTo(value: { xOffset: number | string, yOffset: number | string, animation? ...@@ -80,13 +70,13 @@ scrollTo(value: { xOffset: number | string, yOffset: number | string, animation?
Scrolls to the specified position. Scrolls to the specified position.
**Parameters**
- Parameters | Name | Type | Mandatory| Description |
| Name | Type | Mandatory | Default Value | Description | | --------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| --------- | ---------------------------------------- | ---- | ---- | ---------------------------------------- | | xOffset | Length | Yes | Horizontal scrolling offset. |
| xOffset | Length | Yes | - | Horizontal scrolling offset. | | yOffset | Length | Yes | Vertical scrolling offset. |
| yOffset | Length | Yes | - | Vertical scrolling offset. | | animation | {<br>duration: number,<br>curve: [Curve](ts-animatorproperty.md)<br>} | No | Animation configuration, which includes the following:<br>- **duration**: scrolling duration.<br>- **curve**: scrolling curve.|
| animation | {<br>duration:&nbsp;number,<br>curve:&nbsp;[Curve](ts-animatorproperty.md)&nbsp;\|<br>CubicBezier&nbsp;\|<br>SpringCurve<br>} | No | | Animation configuration, which includes the following:<br>- **duration**: scrolling duration.<br>- **curve**: scrolling curve.|
### scrollEdge ### scrollEdge
...@@ -96,40 +86,39 @@ scrollEdge(value: Edge): void ...@@ -96,40 +86,39 @@ scrollEdge(value: Edge): void
Scrolls to the edge of the container. Scrolls to the edge of the container.
**Parameters**
- Parameters | Name | Type| Mandatory | Description |
| Name | Type| Mandatory | Default Value | Description | | ----- | ---- | ---- | --------- |
| ----- | ---- | ---- | ---- | --------- | | value | [Edge](ts-appendix-enums.md#edge) | Yes | Edge position to scroll to.|
| value | [Edge](ts-appendix-enums.md#edge) | Yes | - | Edge position to scroll to.|
### scrollPage ### scrollPage
scrollPage(value: { next: boolean, direction?: Axis }): void scrollPage(value: { next: boolean, direction?: Axis }): void
Scrolls to the next or previous page. Scrolls to the next or previous page.
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| --------- | ------- | ---- | ---- | ------------------------------ | | Name | Type | Mandatory | Description |
| next | boolean | Yes | - | Whether to turn to the next page. The value **true** means to scroll to the next page, and **false** means to scroll to the previous page.| | --------- | ------- | ---- | ------------------------------ |
| direction | [Axis](ts-appendix-enums.md#axis) | No | - | Scrolling direction: horizontal or vertical. | | next | boolean | Yes | Whether to turn to the next page. The value **true** means to scroll to the next page, and **false** means to scroll to the previous page.|
| direction<sup>(deprecated) </sup> | [Axis](ts-appendix-enums.md#axis) | No | Scrolling direction: horizontal or vertical.<br> This API is deprecated since API version 9. |
### currentOffset ### currentOffset
currentOffset(): Object currentOffset()
Obtains the scrolling offset. Obtains the scrolling offset.
**Return value**
- Return value | Type | Description |
| Type | Description | | ---------------------------------------- | ---------------------------------------- |
| ---------------------------------------- | ---------------------------------------- | | {<br>xOffset: number,<br>yOffset: number<br>} | **xOffset**: horizontal scrolling offset.<br>**yOffset**: vertical scrolling offset.|
| {<br>xOffset:&nbsp;number,<br>yOffset:&nbsp;number<br>} | **xOffset**: horizontal scrolling offset.<br>**yOffset**: vertical scrolling offset.|
### scrollToIndex ### scrollToIndex
...@@ -141,16 +130,17 @@ Scrolls to the item with the specified index. ...@@ -141,16 +130,17 @@ Scrolls to the item with the specified index.
> **NOTE** > **NOTE**
> Only the **\<List>** component is supported. >
> Only the **\<List>** component is supported.
**Parameters**
- Parameters | Name| Type| Mandatory| Description |
| Name | Type | Mandatory | Default Value | Description | | ------ | -------- | ---- | ---------------------------------- |
| ----- | ------ | ---- | ---- | ----------------- | | value | number | Yes | Index of the item to be scrolled to in the list.|
| value | number | Yes | - | Index of the item to be scrolled to in the list.|
### scrollBy ### scrollBy<sup>9+</sup>
scrollBy(dx: Length, dy: Length): void scrollBy(dx: Length, dy: Length): void
...@@ -159,14 +149,15 @@ Scrolls by the specified amount. ...@@ -159,14 +149,15 @@ Scrolls by the specified amount.
> **NOTE** > **NOTE**
> Only the **\<Scroll>** component is supported. >
> Only the **\<Scroll>** component is supported.
**Parameters**
- Parameters | Name | Type | Mandatory | Description |
| Name | Type | Mandatory | Default Value | Description | | ----- | ------ | ---- | ----------------- |
| ----- | ------ | ---- | ---- | ----------------- | | dx | Length | Yes | Amount to scroll by in the horizontal direction. The percentage format is not supported.|
| dx | Length | Yes | - | Amount to scroll by in the horizontal direction.| | dy | Length | Yes | Amount to scroll by in the vertical direction. The percentage format is not supported.|
| dy | Length | Yes | - | Amount to scroll by in the vertical direction.|
## Example ## Example
...@@ -208,22 +199,27 @@ struct ScrollExample { ...@@ -208,22 +199,27 @@ struct ScrollExample {
.onScrollEnd(() => { .onScrollEnd(() => {
console.info('Scroll Stop') console.info('Scroll Stop')
}) })
Button('scroll 150')
.onClick(() => { // Click to scroll down to 150.0 vp.
this.scroller.scrollBy(0,150)
})
.margin({ top: 10, left: 20 })
Button('scroll 100') Button('scroll 100')
.onClick(() => { // Click to scroll down 100.0. .onClick(() => { // Click to scroll down by 100.0 vp.
this.scroller.scrollTo({ xOffset: 0, yOffset: this.scroller.currentOffset().yOffset + 100 }) this.scroller.scrollTo({ xOffset: 0, yOffset: this.scroller.currentOffset().yOffset + 100 })
}) })
.margin({ top: 10, left: 20 }) .margin({ top: 60, left: 20 })
Button('back top') Button('back top')
.onClick(() => { // Click to go back to the top. .onClick(() => { // Click to go back to the top.
this.scroller.scrollEdge(Edge.Top) this.scroller.scrollEdge(Edge.Top)
}) })
.margin({ top: 60, left: 20 }) .margin({ top: 110, left: 20 })
Button('next page') Button('next page')
.onClick(() => { // Click to scroll down to the bottom. .onClick(() => { // Click to go to the next page.
this.scroller.scrollPage({ next: true }) this.scroller.scrollPage({ next: true })
}) })
.margin({ top: 110, left: 20 }) .margin({ top: 170, left: 20 })
}.width('100%').height('100%').backgroundColor(0xDCDCDC) }.width('100%').height('100%').backgroundColor(0xDCDCDC)
} }
} }
......
# SideBarContainer # SideBarContainer
The **\<SideBarContainer>** component contains a sidebar and content area as its child components. The sidebar is the first child component and can be shown or hidden as needed. The content area is the second child component.
> **NOTE** > **NOTE**
> >
> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. > This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
The **\<SideBarContainer>** component contains a sidebar and content area as its child components. The sidebar is the first child component and can be shown or hidden as needed. The content area is the second child component.
## Required Permissions
None
## Child Components ## Child Components
Supported Supported
...@@ -22,46 +16,55 @@ Supported ...@@ -22,46 +16,55 @@ Supported
SideBarContainer( type?: SideBarContainerType ) SideBarContainer( type?: SideBarContainerType )
- Parameters **Parameters**
| Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- | | Name| Type| Mandatory| Description|
| type | SideBarContainerType | No| SideBarContainerType.Embed | Display type of the sidebar.| | -------- | -------- | -------- | -------- |
| type | SideBarContainerType | No| Display type of the sidebar.<br>Default value: **SideBarContainerType.Embed**|
## SideBarContainerType enums
- SideBarContainerType enums | Name| Description|
| Name| Description| | -------- | -------- |
| -------- | -------- | | Embed | The sidebar is embedded in the component and displayed side by side with the content area.|
| Embed | The sidebar is embedded in the component and displayed side by side with the content area.| | Overlay | The sidebar is displayed overlaid on the content area.|
| Overlay | The sidebar is displayed overlaid on the content area.|
## Attributes ## Attributes
| Name| Type| Default Value| Description| | Name| Type| Description|
| -------- | -------- | -------- |
| showSideBar | boolean | Whether to display the sidebar.<br>Default value: **true**|
| controlButton | ButtonStyle | Attributes of the sidebar control button.|
| showControlButton | boolean | Whether to display the sidebar control button.<br>Default value: **true**|
| sideBarWidth | number \| Length<sup>9+</sup> | Width of the sidebar.<br>Default value: **200**, in vp|
| minSideBarWidth | number \| Length<sup>9+</sup> | Minimum width of the sidebar.<br>Default value: **200**, in vp|
| maxSideBarWidth | number \| Length<sup>9+</sup> | Maximum width of the sidebar.<br>Default value: **280**, in vp|
| autoHide<sup>9+</sup> | boolean | Whether to automatically hide the sidebar when it is dragged to be smaller than the minimum width.<br>Default value: **true**|
| sideBarPosition<sup>9+</sup> | SideBarPosition | Position of the sidebar.<br>Default value: **SideBarPosition.Start**|
## ButtonStyle
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| showSideBar | boolean | true | Whether to display the sidebar.| | left | number | No| Spacing between the sidebar control button and the left of the container.<br>Default value: **16**, in vp|
| controlButton | ButtonStyle | - | Attributes of the sidebar control button.| | top | number | No| Spacing between the sidebar control button and the top of the container.<br>Default value: **48**, in vp|
| showControlButton | boolean | true | Whether to display the sidebar control button.| | width | number | No| Width of the sidebar control button.<br>Default value: **32**, in vp|
| sideBarWidth | number \| [Length<sup>9+</sup>](../../ui/ts-types.md#length-type)| 200 | Width of the sidebar.| | height | number | No| Height of the sidebar control button.<br>Default value: **32**, in vp|
| minSideBarWidth | number \| [Length<sup>9+</sup>](../../ui/ts-types.md#length-type)| 200 | Minimum width of the sidebar.| | icons | {<br>shown: string \| PixelMap \| [Resource](ts-types.md#resource) ,<br>hidden: string \| PixelMap \| [Resource](ts-types.md#resource) ,<br>switching?: string \| PixelMap \| [Resource](ts-types.md#resource) <br>} | No| Icons of the sidebar control button.<br> </p> - **shown**: icon of the control button when the sidebar is shown.<br>- **hidden**: icon of the control button when the sidebar is hidden.<br>- **switching**: icon of the control button when the sidebar is switching between the shown and hidden states.|
| maxSideBarWidth | number \| [Length<sup>9+</sup>](../../ui/ts-types.md#length-type)| 280 | Maximum width of the sidebar.|
| autoHide<sup>9+</sup> | boolean | true | Whether to automatically hide the sidebar when it is dragged to be smaller than the minimum width.| ## SideBarPosition<sup>9+</sup>
| sideBarPosition<sup>9+</sup> | SideBarPosition | SideBarPosition.Start | Position of the sidebar.|
| Name| Description|
- ButtonStyle | -------- | -------- |
| Name| Type| Mandatory| Default Value| Description| | Start | The sidebar is on the left side of the container.|
| -------- | -------- | -------- | -------- | -------- | | End | The sidebar is on the right side of the container.|
| left | number | No| 16 | Spacing between the sidebar control button and the left of the container.|
| top | number | No| 48 | Spacing between the sidebar control button and the top of the container.|
| width | number | No| 32 | Width of the sidebar control button.|
| height | number | No| 32 | Height of the sidebar control button.|
| icons | {<br>shown:&nbsp;string \| PixelMap \| [Resource](../../ui/ts-types.md) ,<br>hidden:&nbsp;string \| PixelMap \| [Resource](../../ui/ts-types.md) ,<br>switching?:&nbsp;string \| PixelMap \| [Resource](../../ui/ts-types.md) <br>} | No| - | Icons of the sidebar control button.<br> </p> - **shown**: icon of the control button when the sidebar is shown.<br>- **hidden**: icon of the control button when the sidebar is hidden.<br>- **switching**: icon of the control button when the sidebar is switching between the shown and hidden states.|
- SideBarPosition<sup>9+</sup>
| Name| Description|
| -------- | -------- |
| Start | The sidebar is on the left side of the container.|
| End | The sidebar is on the right side of the container.|
## SideBarPosition<sup>9+</sup>
| Name| Description|
| -------- | -------- |
| Start | The sidebar is on the left side of the container.|
| End | The sidebar is on the right side of the container.|
## Events ## Events
...@@ -77,8 +80,8 @@ SideBarContainer( type?: SideBarContainerType ) ...@@ -77,8 +80,8 @@ SideBarContainer( type?: SideBarContainerType )
@Entry @Entry
@Component @Component
struct SideBarContainerExample { struct SideBarContainerExample {
normalIcon : Resource = $r("app.media.user") normalIcon : Resource = $r("app.media.icon")
selectedIcon: Resource = $r("app.media.userFull") selectedIcon: Resource = $r("app.media.icon")
@State arr: number[] = [1, 2, 3] @State arr: number[] = [1, 2, 3]
@State current: number = 1 @State current: number = 1
...@@ -101,18 +104,17 @@ struct SideBarContainerExample { ...@@ -101,18 +104,17 @@ struct SideBarContainerExample {
}.width('100%') }.width('100%')
.justifyContent(FlexAlign.SpaceEvenly) .justifyContent(FlexAlign.SpaceEvenly)
.backgroundColor('#19000000') .backgroundColor('#19000000')
RowSplit() {
Column(){
Text('Split page one').fontSize(30) Column() {
}.justifyContent(FlexAlign.Center) Text('SideBarContainer content text1').fontSize(25)
Column(){ Text('SideBarContainer content text2').fontSize(25)
Text('Split page two').fontSize(30) }
}.justifyContent(FlexAlign.Center) .margin({ top: 50, left: 20, right: 30 })
}.width('100%')
} }
.sideBarWidth(240) .sideBarWidth(150)
.minSideBarWidth(210) .minSideBarWidth(50)
.maxSideBarWidth(260) .maxSideBarWidth(300)
.onChange((value: boolean) => { .onChange((value: boolean) => {
console.info('status:' + value) console.info('status:' + value)
}) })
......
# Stack # Stack
The **\<Stack>** component provides a stack container where child components are successively stacked and the latter one overwrites the previous one.
> **NOTE**<br> > **NOTE**
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. >
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
The **<Stack\>** component provides a stack container where child components are successively stacked and the latter one overwrites the previous one.
## Required Permissions
None
## Child Components ## Child Components
Supported Supported
## APIs ## APIs
Stack(value:{alignContent?: Alignment}) Stack(value?: { alignContent?: Alignment })
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| alignContent | [Alignment](ts-appendix-enums.md#alignment-enums) | No | Center | Alignment of child components in the container. |
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| alignContent | [Alignment](ts-appendix-enums.md#alignment) | No| Alignment of child components in the container.<br>Default value: **Alignment.Center**|
## Example
## Example
``` ```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct StackExample { struct StackExample {
......
# Swiper # Swiper
The **\<Swiper>** component is able to display child components in looping mode.
The **\<Swiper>** component provides a container that allows users to switch among child components using swipe gestures.
> **NOTE** > **NOTE**
> >
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
None
## Child Components ## Child Components
This component can contain child components. This component can contain child components.
...@@ -20,18 +14,18 @@ This component can contain child components. ...@@ -20,18 +14,18 @@ This component can contain child components.
## APIs ## APIs
Swiper(value:{controller?: SwiperController}) Swiper(controller?: SwiperController)
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ---------- | ------------------------------------- | ---- | -------------------- | | ---------- | ------------------------------------- | ---- | -------------------- |
| controller | [SwiperController](#swipercontroller) | No | Controller bound to the component to control the page switching.<br>Default value: **null** | | controller | [SwiperController](#swipercontroller) | No | Controller bound to the component to control the page switching.|
## Attributes ## Attributes
[Menu control](ts-universal-attributes-menu.md) is not supported. In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. [Menu control](ts-universal-attributes-menu.md) is not supported.
| Name | Type | Description | | Name | Type | Description |
| --------------------------- | ---------------------------------------- | ---------------------------------------- | | --------------------------- | ---------------------------------------- | ---------------------------------------- |
...@@ -42,29 +36,29 @@ Swiper(value:{controller?: SwiperController}) ...@@ -42,29 +36,29 @@ Swiper(value:{controller?: SwiperController})
| loop | boolean | Whether to enable loop playback.<br>The value **true** means to enable loop playback. When LazyForEach is used, it is recommended that the number of the components to load exceed 5.<br>Default value: **true**| | loop | boolean | Whether to enable loop playback.<br>The value **true** means to enable loop playback. When LazyForEach is used, it is recommended that the number of the components to load exceed 5.<br>Default value: **true**|
| duration | number | Duration of the animation for switching child components, in ms.<br>Default value: **400** | | duration | number | Duration of the animation for switching child components, in ms.<br>Default value: **400** |
| vertical | boolean | Whether vertical swiping is used.<br>Default value: **false** | | vertical | boolean | Whether vertical swiping is used.<br>Default value: **false** |
| itemSpace | Length | Space between child components.<br>Default value: **0** | | itemSpace | number \| string | Space between child components.<br>Default value: **0** |
| displayMode | SwiperDisplayMode | Mode in which elements are displayed along the main axis. This attribute takes effect only when **displayCount** is not set.<br>Default value: **SwiperDisplayMode.Stretch**| | displayMode | SwiperDisplayMode | Mode in which elements are displayed along the main axis. This attribute takes effect only when **displayCount** is not set.<br>Default value: **SwiperDisplayMode.Stretch**|
| cachedCount<sup>8+</sup> | number | Number of child components to be cached.<br>Default value: **1** | | cachedCount<sup>8+</sup> | number | Number of child components to be cached.<br>Default value: **1** |
| disableSwipe<sup>8+</sup> | boolean | Whether to disable the swipe feature.<br>Default value: **false** | | disableSwipe<sup>8+</sup> | boolean | Whether to disable the swipe feature.<br>Default value: **false** |
| curve<sup>8+</sup> | [Curve](ts-appendix-enums.md#curve) \| string | Animation curve. The ease-in/ease-out curve is used by default. For details about common curves, see [Curve](ts-appendix-enums.md#curve). You can also create custom curves ([interpolation curve objects](ts-interpolation-calculation.md)) by using the API provided by the interpolation calculation module.<br>Default value: **Curve.Ease** | | curve<sup>8+</sup> | [Curve](ts-appendix-enums.md#curve) \| string | Animation curve. The ease-in/ease-out curve is used by default. For details about common curves, see [Curve](ts-appendix-enums.md#curve). You can also create custom curves ([interpolation curve objects](ts-interpolation-calculation.md)) by using the API provided by the interpolation calculation module.<br>Default value: **Curve.Ease**|
| indicatorStyle<sup>8+</sup> | {<br/>left?:&nbsp;Length,<br/>top?:&nbsp;Length,<br/>right?:&nbsp;Length,<br/>bottom?:&nbsp;Length,<br/>size?:&nbsp;Length,<br/>mask?:&nbsp;boolean,<br/>color?:&nbsp;[ResourceColor](../../ui/ts-types.md),<br/>selectedColor?:&nbsp;[ResourceColor](../../ui/ts-types.md)<br/>} | Style of the navigation dots indicator.<br>- **left**: distance between the navigation dots indicator and the left edge of the **\<Swiper>** component.<br>- **top**: distance between the navigation dots indicator and the top edge of the **\<Swiper>** component.<br>- **right**: distance between the navigation dots indicator and the right edge of the **\<Swiper>** component.<br>- **bottom**: distance between the navigation dots indicator and the bottom edge of the **\<Swiper>** component.<br>- **size**: diameter of the navigation dots indicator.<br>- **color**: color of the navigation dots indicator.<br>- **selectedColor**: color of the selected navigation dot.| | indicatorStyle<sup>8+</sup> | {<br>left?: [Length](ts-types.md#length),<br>top?: [Length](ts-types.md#length),<br>right?: [Length](ts-types.md#length),<br>bottom?: [Length](ts-types.md#length),<br>size?: [Length](ts-types.md#length),<br>mask?: boolean,<br>color?: [ResourceColor](ts-types.md#resourcecolor),<br>selectedColor?: [ResourceColor](ts-types.md#resourcecolor)<br>} | Style of the navigation dots indicator.<br>\- **left**: distance between the navigation dots indicator and the left edge of the **\<Swiper>** component.<br>\- **top**: distance between the navigation dots indicator and the top edge of the **\<Swiper>** component.<br>\- **right**: distance between the navigation dots indicator and the right edge of the **\<Swiper>** component.<br>\- **bottom**: distance between the navigation dots indicator and the bottom edge of the **\<Swiper>** component.<br>\- **size**: diameter of the navigation dots indicator.<br>\- **mask**: whether to enable the mask for the navigation dots indicator.<br>\- **color**: color of the navigation dots indicator.<br>\- **selectedColor**: color of the selected navigation dot.|
| displayCount<sup>8+</sup> | number\|string | Number of elements to display.<br>Default value: **1** | | displayCount<sup>8+</sup> | number\|string | Number of elements to display.<br>Default value: **1** |
| effectMode<sup>8+</sup> | [EdgeEffect](ts-appendix-enums.md#edgeeffect) | Swipe effect. For details, see **EdgeEffect**.<br>Default value: **EdgeEffect.Spring**| | effectMode<sup>8+</sup> | [EdgeEffect](ts-appendix-enums.md#edgeeffect) | Swipe effect. For details, see **EdgeEffect**.<br>Default value: **EdgeEffect.Spring**|
## SwiperDisplayMode ## SwiperDisplayMode
| Name| Description| | Name| Description|
| ----------- | ------------------------------------------ | | ----------- | ------------------------------------------ |
| Stretch | The slide width of the **\<Swiper>** component is equal to the width of the component.| | Stretch | The slide width of the **\<Swiper>** component is equal to the width of the component.|
| AutoLinear | The slide width of the **\<Swiper>** component is equal to the maximum width of the child components.| | AutoLinear | The slide width of the **\<Swiper>** component is equal to that of the child component with the maximum width.|
## EdgeEffect ## EdgeEffect
| Name | Description | | Name | Description |
| ------ | ------------------------------------------------------------------------- | | ------ | ------------------------------------------------------------------------- |
| Spring | Spring effect. When at one of the edges, the component can move beyond the bounds through touches, and produce a bounce effect when the user releases their finger. | | Spring | Spring effect. When sliding to one edge, the component can move beyond the bounds through touches, and produce a bounce effect when the user releases their finger. |
| Fade | Fade effect. When at one of the edges, the component can move beyond the bounds through touches, and produce a fade effect along the way; when the user releases their finger, the fade changes. | | Fade | Fade effect. When sliding to one edge, the component can move beyond the bounds through touches, and produce a fade effect along the way; when the user releases their finger, the fade changes. |
| None | No effect. When at one of the edges, the component cannot move beyond the bounds. | | None | No effect. When sliding to one edge, the component cannot move beyond the bounds. |
## SwiperController ## SwiperController
...@@ -86,7 +80,7 @@ Turns to the previous page. ...@@ -86,7 +80,7 @@ Turns to the previous page.
finishAnimation(callback?: () => void): void finishAnimation(callback?: () => void): void
Stops this animation. Stops an animation.
**Parameters** **Parameters**
...@@ -100,7 +94,7 @@ Stops this animation. ...@@ -100,7 +94,7 @@ Stops this animation.
onChange(event: (index: number) => void) onChange(event: (index: number) => void)
Triggered when the index of the currently displayed component changes. Triggered when the index of the currently displayed child component changes.
**Parameters** **Parameters**
......
...@@ -23,7 +23,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the ...@@ -23,7 +23,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| Name| Type| Description| | Name| Type| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| tabBar | string \| Resource \| {<br>icon?: string \| Resource,<br>text?: string \| Resource<br>}<br>\| [CustomBuilder](../../ui/ts-types.md)<sup>8+</sup> | Content displayed on the tab bar.<br>**CustomBuilder**: builder, to which components can be passed (applicable to API version 8 and later versions).<br>> **NOTE**<br>If an icon uses an SVG image, the width and height attributes of the SVG image must be deleted. Otherwise, the icon size will be determined by the width and height attributes of the SVG image.| | tabBar | string \| Resource \| {<br>icon?: string \| Resource,<br>text?: string \| Resource<br>}<br>\| [CustomBuilder](ts-types.md)<sup>8+</sup> | Content displayed on the tab bar.<br>**CustomBuilder**: builder, to which components can be passed (applicable to API version 8 and later versions).<br>> **NOTE**<br>If an icon uses an SVG image, the width and height attributes of the SVG image must be deleted. Otherwise, the icon size will be determined by the width and height attributes of the SVG image.|
> **NOTE** > **NOTE**
> - The **\<TabContent>** component does not support setting of the common width attribute. By default, its width is the same as that of the parent **\<Tabs>** component. > - The **\<TabContent>** component does not support setting of the common width attribute. By default, its width is the same as that of the parent **\<Tabs>** component.
......
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
The **\<Tabs>** component is a container component that allows users to switch between content views through tabs. Each tab page corresponds to a content view. The **\<Tabs>** component is a container component that allows users to switch between content views through tabs. Each tab page corresponds to a content view.
> **NOTE** > **NOTE**<br>
> >
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
...@@ -14,7 +14,7 @@ This component can contain multiple [\<TabContent>](ts-container-tabcontent.md) ...@@ -14,7 +14,7 @@ This component can contain multiple [\<TabContent>](ts-container-tabcontent.md)
## APIs ## APIs
Tabs(value: {barPosition?: BarPosition, index?: number, controller?: [TabsController](#tabscontroller)}) Tabs(value?: {barPosition?: BarPosition, index?: number, controller?: [TabsController](#tabscontroller)})
**Parameters** **Parameters**
...@@ -41,8 +41,8 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the ...@@ -41,8 +41,8 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| vertical | boolean | Whether to use vertical tabs. The value **true** means to use vertical tabs, and **false** means to use horizontal tabs.<br>Default value: **false**| | vertical | boolean | Whether to use vertical tabs. The value **true** means to use vertical tabs, and **false** means to use horizontal tabs.<br>Default value: **false**|
| scrollable | boolean | Whether the tabs are scrollable. The value **true** means that the tabs are scrollable, and **false** means the opposite.<br>Default value: **true**| | scrollable | boolean | Whether the tabs are scrollable. The value **true** means that the tabs are scrollable, and **false** means the opposite.<br>Default value: **true**|
| barMode | BarMode | Tab bar layout mode. For details, see **BarMode**.<br>Default value: **BarMode.Fixed**| | barMode | BarMode | Tab bar layout mode. For details, see **BarMode**.<br>Default value: **BarMode.Fixed**|
| barWidth | number \| string<sup>8+</sup> | Width of the tab bar. | | barWidth | number \| Length<sup>8+</sup> | Width of the tab bar. |
| barHeight | number \| string<sup>8+</sup> | Height of the tab bar. | | barHeight | number \| Length<sup>8+</sup> | Height of the tab bar. |
| animationDuration | number | Animation duration of the tab content.<br>Default value: **200**| | animationDuration | number | Animation duration of the tab content.<br>Default value: **200**|
## BarMode ## BarMode
...@@ -58,7 +58,7 @@ In addition to the universal events (ts-universal-events-click.md), the followin ...@@ -58,7 +58,7 @@ In addition to the universal events (ts-universal-events-click.md), the followin
| Name| Description| | Name| Description|
| -------- | -------- | | -------- | -------- |
| onChange(callback: (index: number) =&gt; void) | Event triggered when a tab is switched.| | onChange(event: (index: number) =&gt; void) | Event triggered when a tab is switched.|
## TabsController ## TabsController
......
...@@ -28,15 +28,15 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the ...@@ -28,15 +28,15 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| Name| Type| Default Value| Mandatory| Description| | Name| Type| Default Value| Mandatory| Description|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| fill | [ResourceColor](../../ui/ts-types.md) | Color.Black | No| Color of the fill area.| | fill | [ResourceColor](ts-types.md#resourcecolor) | Color.Black | No| Color of the fill area.|
| fillOpacity | number \| string \| [Resource](../../ui/ts-types.md#resource-type)| 1 | No| Opacity of the fill area.| | fillOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | No| Opacity of the fill area.|
| stroke | [ResourceColor](../../ui/ts-types.md) | Color.Black | No| Stroke color.| | stroke | [ResourceColor](ts-types.md#resourcecolor) | Color.Black | No| Stroke color.|
| strokeDashArray | Array&lt;Length&gt; | [] | No| Stroke dashes.| | strokeDashArray | Array&lt;Length&gt; | [] | No| Stroke dashes.|
| strokeDashOffset | number \| string | 0 | No| Offset of the start point for drawing the stroke.| | strokeDashOffset | number \| string | 0 | No| Offset of the start point for drawing the stroke.|
| strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | No| Cap style of the stroke.| | strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | No| Cap style of the stroke.|
| strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | No| Join style of the stroke.| | strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | No| Join style of the stroke.|
| strokeMiterLimit | number \| string | 4 | No| Limit value when the sharp angle is drawn as a miter.| | strokeMiterLimit | number \| string | 4 | No| Limit value when the sharp angle is drawn as a miter.|
| strokeOpacity | number \| string \| [Resource](../../ui/ts-types.md#resource-type)| 1 | No| Stroke opacity.| | strokeOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | No| Stroke opacity.|
| strokeWidth | Length | 1 | No| Stroke width.| | strokeWidth | Length | 1 | No| Stroke width.|
| antiAlias | boolean | true | No| Whether anti-aliasing is enabled.| | antiAlias | boolean | true | No| Whether anti-aliasing is enabled.|
......
# Ellipse # Ellipse
The **\<Ellipse>** component is used to draw an ellipse. The **\<Ellipse>** component is used to draw an ellipse.
> **NOTE** > **NOTE**
...@@ -8,11 +7,6 @@ The **\<Ellipse>** component is used to draw an ellipse. ...@@ -8,11 +7,6 @@ The **\<Ellipse>** component is used to draw an ellipse.
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
None
## Child Components ## Child Components
Not supported Not supported
...@@ -22,12 +16,12 @@ Not supported ...@@ -22,12 +16,12 @@ Not supported
ellipse(options?: {width?: string | number, height?: string | number}) ellipse(options?: {width?: string | number, height?: string | number})
- Parameters **Parameters**
| Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- |
| width | string \| number | No| 0 | Width of the ellipse. |
| height | string \| number | No| 0 | Height of the ellipse. |
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| width | string \| number | No| Width.<br>Default value: **0**|
| height | string \| number | No| Height.<br>Default value: **0**|
## Attributes ## Attributes
...@@ -35,15 +29,15 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the ...@@ -35,15 +29,15 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| Name| Type| Default Value| Mandatory| Description| | Name| Type| Default Value| Mandatory| Description|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| fill | [ResourceColor](../../ui/ts-types.md) | Color.Black | No| Color of the fill area.| | fill | [ResourceColor](ts-types.md#resourcecolor) | Color.Black | No| Color of the fill area.|
| fillOpacity | number \| string \| [Resource](../../ui/ts-types.md#resource)| 1 | No| Opacity of the fill area.| | fillOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | No| Opacity of the fill area.|
| stroke | [ResourceColor](../../ui/ts-types.md) | Color.Black | No|Stroke color.| | stroke | [ResourceColor](ts-types.md#resourcecolor) | Color.Black | No|Stroke color.|
| strokeDashArray | Array&lt;Length&gt; | [] | No| Stroke dash.| | strokeDashArray | Array&lt;Length&gt; | [] | No| Stroke dash.|
| strokeDashOffset | number \| string | 0 | No| Offset of the start point for drawing the stroke.| | strokeDashOffset | number \| string | 0 | No| Offset of the start point for drawing the stroke.|
| strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | No| Cap style of the stroke.| | strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | No| Cap style of the stroke.|
| strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | No| Join style of the stroke.| | strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | No| Join style of the stroke.|
| strokeMiterLimit | number \| string | 4 | No| Limit value when the sharp angle is drawn as a miter.| | strokeMiterLimit | number \| string | 4 | No| Limit value when the sharp angle is drawn as a miter.|
| strokeOpacity | number \| string \| [Resource](../../ui/ts-types.md#resource)| 1 | No| Stroke opacity.| | strokeOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | No| Stroke opacity.|
| strokeWidth | Length | 1 | No| Stroke width.| | strokeWidth | Length | 1 | No| Stroke width.|
| antiAlias | boolean | true | No| Whether anti-aliasing is enabled.| | antiAlias | boolean | true | No| Whether anti-aliasing is enabled.|
...@@ -57,9 +51,9 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the ...@@ -57,9 +51,9 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
struct EllipseExample { struct EllipseExample {
build() { build() {
Flex({ justifyContent: FlexAlign.SpaceAround }) { Flex({ justifyContent: FlexAlign.SpaceAround }) {
// Draw an ellipse in a 150 x 70 rectangle. // Draw an ellipse in a 150 x 80 rectangle.
Ellipse({ width: 150, height: 80 }) Ellipse({ width: 150, height: 80 })
// Draw an ellipse in a 150 x 70 rectangle. // Draw an ellipse in a 150 x 80 rectangle.
Ellipse().width(150).height(80) Ellipse().width(150).height(80)
}.width('100%').margin({ top: 5 }) }.width('100%').margin({ top: 5 })
} }
......
...@@ -4,8 +4,7 @@ ...@@ -4,8 +4,7 @@
The **\<Line>** component is used to draw a straight line. The **\<Line>** component is used to draw a straight line.
> **NOTE** > **NOTE**
> > This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions ## Required Permissions
...@@ -20,13 +19,13 @@ Not supported ...@@ -20,13 +19,13 @@ Not supported
## APIs ## APIs
Line(options?: {width?: string | number, height?: string | number}) Line(value?: {width?: string | number, height?: string | number})
- Parameters - Parameters
| Name| Type| Mandatory| Default Value| Description| | Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| width | string \| number | No| 0 | Width of the line. | | width | string \| number | No| 0 | Width.|
| height | string \| number | No| 0 | Height of the line. | | height | string \| number | No| 0 | Height.|
## Attributes ## Attributes
...@@ -35,17 +34,17 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the ...@@ -35,17 +34,17 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| Name| Type| Default Value| Mandatory| Description| | Name| Type| Default Value| Mandatory| Description|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| startPoint | Array | [0, 0] | Yes | Coordinates (relative coordinates) of the start point of the line. | | startPoint | Array&lt;Length&gt; | [0, 0] | No | Coordinates (relative coordinates) of the start point of the line, in vp.|
| endPoint | Array | [0, 0] | Yes | Coordinates (relative coordinates) of the end point of the line. | | endPoint | Array&lt;Length&gt; | [0, 0] | No | Coordinates (relative coordinates) of the end point of the line, in vp.|
| fill | [ResourceColor](../../ui/ts-types.md) | Color.Black | No| Color of the fill area.| | fill | [ResourceColor](ts-types.md#resourcecolor) | Color.Black | No| Color of the fill area.|
| fillOpacity | number \| string \| [Resource](../../ui/ts-types.md#resource)| 1 | No| Opacity of the fill area.| | fillOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | No| Opacity of the fill area.|
| stroke | [ResourceColor](../../ui/ts-types.md) | Color.Black | No| Stroke color.| | stroke | [ResourceColor](ts-types.md#resourcecolor) | Color.Black | No| Stroke color.|
| strokeDashArray | Array&lt;Length&gt; | [] | No| Stroke dashes.| | strokeDashArray | Array&lt;Length&gt; | [] | No| Stroke dashes.|
| strokeDashOffset | number \| string | 0 | No| Offset of the start point for drawing the stroke.| | strokeDashOffset | number \| string | 0 | No| Offset of the start point for drawing the stroke.|
| strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | No| Cap style of the stroke.| | strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | No| Cap style of the stroke.|
| strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | No| Join style of the stroke.| | strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | No| Join style of the stroke.|
| strokeMiterLimit | number \| string | 4 | No| Limit value when the sharp angle is drawn as a miter.| | strokeMiterLimit | number \| string | 4 | No| Limit value when the sharp angle is drawn as a miter.|
| strokeOpacity | number \| string \| [Resource](../../ui/ts-types.md#resource)| 1 | No| Stroke opacity.| | strokeOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | No| Stroke opacity.|
| strokeWidth | Length | 1 | No| Stroke width.| | strokeWidth | Length | 1 | No| Stroke width.|
| antiAlias | boolean | true | No| Whether anti-aliasing is enabled.| | antiAlias | boolean | true | No| Whether anti-aliasing is enabled.|
...@@ -59,7 +58,8 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the ...@@ -59,7 +58,8 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
struct LineExample { struct LineExample {
build() { build() {
Column() { Column() {
Line({ width: 50, height: 100 }).startPoint([0, 0]).endPoint([50, 100]) Line().startPoint([0, 0]).endPoint([50, 100])
Line({ width: 50, height: 50 }).startPoint([0, 0]).endPoint([100, 100])
Line().width(200).height(200).startPoint([50, 50]).endPoint([150, 150]) Line().width(200).height(200).startPoint([50, 50]).endPoint([150, 150])
}.margin({ top: 5 }) }.margin({ top: 5 })
} }
......
# Path # Path
The **<Path\>** component is used to define a closed shape.
> **NOTE** > **NOTE**
> >
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
The **<Path\>** component is used to draw a path.
## Required Permissions
None
## Child Components ## Child Components
Not supported Not supported
## APIs
## Attributes Path(value?: { width?: number | string; height?: number | string; commands?: string })
| Name | Type | Default Value | Mandatory | Description |
| -------- | -------- | -------- | -------- | -------- |
| width | Length | 0 | No | Width of the rectangle where the path is located. |
| height | Length | 0 | No | Height of the rectangle where the path is located. |
| commands | string | '' | Yes | Commands for drawing the path. |
The supported commands are as follows:
- M = moveto **Parameters**
- L = lineto | Name | Type | Mandatory| Description |
| -------- | ---------------- | ---- | ----------------------------------- |
| width | number \| string | No | Width of the rectangle where the path is located.<br>Default value: **0** |
| height | number \| string | No | Height of the rectangle where the path is located.<br>Default value: **0** |
| commands | string | No | Command for drawing the path.<br>Default value: **''**|
- H = horizontal lineto ## Attributes
- V = vertical lineto
- C = curveto
- S = smooth curveto
- Q = quadratic Bezier curve
- T = smooth quadratic Bezier curveto
- A = elliptical Arc
- Z = closepath
In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported.
| Name | Type | Default Value | Mandatory | Description |
| -------- | ----------------------------------- | ---- | ---- | ---------------------------------------- |
| commands | string | '' | No | Command for drawing the path. The unit is px. For details about how to convert the pixel units, see [Pixel Unit Conversion](../../ui/ts-pixel-units.md).|
| fill | [ResourceColor](ts-types.md#resourcecolor) | Color.Black | No| Color of the fill area.|
| fillOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | No| Opacity of the fill area.|
| stroke | [ResourceColor](ts-types.md#resourcecolor) | Color.Black | No| Stroke color.|
| strokeDashArray | Array&lt;Length&gt; | [] | No| Stroke dashes.|
| strokeDashOffset | number \| string | 0 | No| Offset of the start point for drawing the stroke.|
| strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | No| Cap style of the stroke.|
| strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | No| Join style of the stroke.|
| strokeMiterLimit | number \| string | 4 | No| Limit value when the sharp angle is drawn as a miter.|
| strokeOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | No| Opacity of the stroke.|
| strokeWidth | Length | 1 | No| Width of the stroke.|
| antiAlias | boolean | true | No| Whether anti-aliasing is enabled.|
For example, the command **M0 20 L50 50 L50 100 Z** defines a path that starts from (0, 20), reaches (50, 50) and then (50, 100), and ends at (0, 20). The supported commands are as follows:
| Command | Attribute | Parameter | Description |
| ---- | -------------------------------- | ---------------------------------------- | ---------------------------------------- |
| M | moveto | (x y) | Starts a new subpath at the point specified by the given (x, y) coordinates. For example, `M 0 0` starts a new subpath at point (0, 0).|
| L | lineto | (x y) | Draws a line from the current point to the point specified by the given (x, y) coordinates. The specified point becomes the start point of the new subpath. For example, `L 50 50` draws a line from the current point to point (50, 50), which is the start point of the new subpath.|
| H | horizontal lineto | x | Draws a horizontal line from the current point. This command is equivalent to the **L** command where the y-coordinate is 0. For example, `H 50 ` draws a line from the current point to point (50, 0), which is the start point of the new subpath.|
| V | vertical lineto | y | Draws a vertical line from the current point. This command is equivalent to the **L** command where the x-coordinate is 0. For example, `V 50 ` draws a line from the current point to point (0, 50), which is the start point of the new subpath.|
| C | curveto | (x1 y1 x2 y2 x y) | Draws a cubic Bezier curve from the current point to the point specified by the given (x, y) coordinates, with (x1, y1) as the control point of the curve start point and (x2, y2) as the control point of the curve end point. For example, `C100 100 250 100 250 200 ` draws a cubic Bezier curve from the current point to point (250, 200), which is the start point of the new subpath.|
| S | smooth curveto | (x2 y2 x y) | Draws a cubic Bezier curve from the current point to the point specified by the given (x, y) coordinates, with (x2, y2) as the control point of the curve end point. If the previous command is **C** or **S**, the control point of the curve start point is the mapping of the control point of the curve end point in the previous command relative to the start point. For example, in `C100 100 250 100 250 200 S400 300 400 200`, the second segment of the cubic Bezier curve uses point (250, 300) as the control point of the curve start point. If there is no previous command or the previous command is not **C** or **S**, the control point of the curve start point coincides with the current point.|
| Q | quadratic Belzier curve | (x1 y1 x y) | Use (x1, y1) as the control point to draw a quadratic Bessel curve from the current point to (x, y). For example, Q400 50 600 300 indicates that a quadratic Bessel curve from the current point to the (600, 300) point is drawn, and the (600, 300) point is used as the starting point of the new subpath.|
| T | smooth quadratic Belzier curveto | (x y) | Draw a quadratic Bessel curve from the current point to (x, y). If the previous command is Q or T, the control point is the mapping of the end point control point of the previous command relative to the start point. For example, a control point of the second Bessel curve segment of the Q400 50 600 300 T1000 300 is (800, 350). If there is no previous command or the previous command is not Q or T, the first control point coincides with the current point.|
| A | elliptical Arc | (rx ry x-axis-rotation large-arc-flag sweep-flag x y) | Draws an elliptical arc from the current point to (x, y). The size and direction of an ellipse are defined by two radiuses (rx, ry) and x-axis-rotation, indicating how the entire ellipse rotates relative to the current coordinate system (in degrees). large-arc-flag and sweep-flag determine an arc drawing manner.|
| Z | closepath | none | Closes the current subpath by connecting the current path back to the initial point of the current subpath. |
For example, commands('M0 20 L50 50 L50 100 Z') defines a triangle that starts from position (0, 20), draws a straight line from point (0, 20) to point (50, 50), draws a straight line from point (50, 50) to point (50, 100), and draws a closed path from point (50, 100) to point (0, 20) to form a closed triangle.
## Example ## Example
```ts ```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct PathExample { struct PathExample {
build() { build() {
Column({ space: 5 }) { Column({ space: 5 }) {
Text('Straight line').fontSize(9).fontColor(0xCCCCCC).width('90%') Text('Straight line').fontSize(9).fontColor(0xCCCCCC).width('90%')
// Draw a straight line with a length of 900px and a width of 3vp.
Path().width(300).height(10).commands('M0 0 L900 0').stroke(Color.Black).strokeWidth(3) Path().width(300).height(10).commands('M0 0 L900 0').stroke(Color.Black).strokeWidth(3)
Text('Straight line graph').fontSize(9).fontColor(0xCCCCCC).width('90%') Text('Straight line graph').fontSize(9).fontColor(0xCCCCCC).width('90%')
Flex({ justifyContent: FlexAlign.SpaceAround }) { Flex({ justifyContent: FlexAlign.SpaceAround }) {
// Run MoveTo(150, 0), LineTo(300, 300), LineTo(0, 300), and ClosePath() in sequence.
Path().width(100).height(100).commands('M150 0 L300 300 L0 300 Z') Path().width(100).height(100).commands('M150 0 L300 300 L0 300 Z')
// Run MoveTo(0, 0), HorizontalLineto(300), VerticalLineto(300), HorizontalLineto(0), and ClosePath() in sequence.
Path().width(100).height(100).commands('M0 0 H300 V300 H0 Z') Path().width(100).height(100).commands('M0 0 H300 V300 H0 Z')
// Run MoveTo(150, 0), LineTo(0, 150), LineTo(60, 300), LineTo(240, 300), LineTo(300, 150), and ClosePath() in sequence.
Path().width(100).height(100).commands('M150 0 L0 150 L60 300 L240 300 L300 150 Z') Path().width(100).height(100).commands('M150 0 L0 150 L60 300 L240 300 L300 150 Z')
}.width('100%') }.width('100%')
Text('Curve graphics').fontSize(9).fontColor(0xCCCCCC).width('90%') Text('Curve graphics').fontSize(9).fontColor(0xCCCCCC).width('90%')
Flex({ justifyContent: FlexAlign.SpaceAround }) { Flex({ justifyContent: FlexAlign.SpaceAround }) {
/ / Run MoveTo(0, 300), draw a curve between (150, 0) and (300, 300), and then run ClosePath().
Path().width(100).height(100).commands("M0 300 S150 0 300 300 Z") Path().width(100).height(100).commands("M0 300 S150 0 300 300 Z")
/ / Run MoveTo(0, 150), draw a curve among (0, 150), (150, 0), and (300, 150), and then run ClosePath().
Path().width(100).height(100).commands('M0 150 C0 150 150 0 300 150 L150 300 Z') Path().width(100).height(100).commands('M0 150 C0 150 150 0 300 150 L150 300 Z')
} }
}.width('100%').margin({ top: 5 }) }.width('100%').margin({ top: 5 })
...@@ -89,4 +89,4 @@ struct PathExample { ...@@ -89,4 +89,4 @@ struct PathExample {
} }
``` ```
![en-us_image_0000001212058492](figures/en-us_image_0000001212058492.png) ![zh-cn_image_0000001219744193](figures/zh-cn_image_0000001219744193.png)
\ No newline at end of file
# Polygon # Polygon
The **\<Polygon>** component is used to draw a polygon. The **\<Polygon>** component is used to draw a polygon.
> **NOTE** > **NOTE**
...@@ -8,11 +7,6 @@ The **\<Polygon>** component is used to draw a polygon. ...@@ -8,11 +7,6 @@ The **\<Polygon>** component is used to draw a polygon.
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
None
## Child Components ## Child Components
Not supported Not supported
...@@ -20,31 +14,31 @@ Not supported ...@@ -20,31 +14,31 @@ Not supported
## APIs ## APIs
Polygon(options?: {width?: string | number, height?: string | number}) Polygon(value?: {width?: string | number, height?: string | number})
- Parameters - Parameters
| Name| Type| Mandatory| Default Value| Description| | Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| width | string \| number | No| 0 | Width of the polygon. | | width | string \| number | No| 0 | Width.|
| height | string \| number | No| 0 | Height of the polygon. | | height | string \| number | No| 0 | Height.|
## Attributes ## Attributes
In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported.
| Name| Type| Default Value| Mandatory| Description| | Name| Type| Default Value| Mandatory| Description|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| points | Array&lt;Point&gt; | [] | No| Vertex coordinates of the polygon.| | points | Array&lt;Point&gt; | [] | No| Vertex coordinates of the polygon.|
| fill | [ResourceColor](../../ui/ts-types.md) | Color.Black | No| Color of the fill area.| | fill | [ResourceColor](ts-types.md#resourcecolor) | Color.Black | No| Color of the fill area.|
| fillOpacity | number \| string \| [Resource](../../ui/ts-types.md#resource)| 1 | No| Opacity of the fill area.| | fillOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | No| Opacity of the fill area.|
| stroke | [ResourceColor](../../ui/ts-types.md) | Color.Black | No| Stroke color.| | stroke | [ResourceColor](ts-types.md#resourcecolor) | Color.Black | No| Stroke color.|
| strokeDashArray | Array&lt;Length&gt; | [] | No| Stroke dashes.| | strokeDashArray | Array&lt;Length&gt; | [] | No| Stroke dashes.|
| strokeDashOffset | number \| string | 0 | No| Offset of the start point for drawing the stroke.| | strokeDashOffset | number \| string | 0 | No| Offset of the start point for drawing the stroke.|
| strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | No| Cap style of the stroke.| | strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | No| Cap style of the stroke.|
| strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | No| Join style of the stroke.| | strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | No| Join style of the stroke.|
| strokeMiterLimit | number \| string | 4 | No| Limit value when the sharp angle is drawn as a miter.| | strokeMiterLimit | number \| string | 4 | No| Limit value when the sharp angle is drawn as a miter.|
| strokeOpacity | number \| string \| [Resource](../../ui/ts-types.md#resource)| 1 | No| Stroke opacity.| | strokeOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | No| Stroke opacity.|
| strokeWidth | Length | 1 | No| Stroke width.| | strokeWidth | Length | 1 | No| Stroke width.|
| antiAlias | boolean | true | No| Whether anti-aliasing is enabled.| | antiAlias | boolean | true | No| Whether anti-aliasing is enabled.|
...@@ -79,4 +73,4 @@ struct PolygonExample { ...@@ -79,4 +73,4 @@ struct PolygonExample {
} }
``` ```
![en-us_image_0000001212218458](figures/en-us_image_0000001212218458.gif) ![en-us_image_0000001174582856](figures/en-us_image_0000001174582856.gif)
\ No newline at end of file
# Polyline # Polyline
The **\<Polyline>** component is used to draw a polyline. The **\<Polyline>** component is used to draw a polyline.
> **NOTE** > **NOTE**
...@@ -8,11 +7,6 @@ The **\<Polyline>** component is used to draw a polyline. ...@@ -8,11 +7,6 @@ The **\<Polyline>** component is used to draw a polyline.
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
None
## Child Components ## Child Components
Not supported Not supported
...@@ -20,31 +14,31 @@ Not supported ...@@ -20,31 +14,31 @@ Not supported
## APIs ## APIs
Polyline(options?: {width?: string | number, height?: string | number}) Polyline(value?: {width?: string | number, height?: string | number})
- Parameters - Parameters
| Name| Type| Mandatory| Default Value| Description| | Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| width | string \| number | No| 0 | Width of the polyline. | | width | string \| number | No| 0 | Width.|
| height | string \| number | No| 0 | Height of the polyline. | | height | string \| number | No| 0 | Height.|
## Attributes ## Attributes
In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported.
| Name| Type| Default Value| Mandatory| Description| | Name| Type| Default Value| Mandatory| Description|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| points | Array&lt;Point&gt; | [] | No| List of coordinates that the polyline passes through.| | points | Array&lt;Point&gt; | [] | No| List of coordinates that the polyline passes through.|
| fill | [ResourceColor](../../ui/ts-types.md) | Color.Black | No| Color of the fill area.| | fill | [ResourceColor](ts-types.md#resourcecolor) | Color.Black | No| Color of the fill area.|
| fillOpacity | number \| string \| [Resource](../../ui/ts-types.md#resource-type)| 1 | No| Opacity of the fill area.| | fillOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | No| Opacity of the fill area.|
| stroke | [ResourceColor](../../ui/ts-types.md) | Color.Black | No| Stroke color.| | stroke | [ResourceColor](ts-types.md#resourcecolor) | Color.Black | No| Stroke color.|
| strokeDashArray | Array&lt;Length&gt; | [] | No| Stroke dashes.| | strokeDashArray | Array&lt;Length&gt; | [] | No| Stroke dashes.|
| strokeDashOffset | number \| string | 0 | No| Offset of the start point for drawing the stroke.| | strokeDashOffset | number \| string | 0 | No| Offset of the start point for drawing the stroke.|
| strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | No| Cap style of the stroke.| | strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | No| Cap style of the stroke.|
| strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | No| Join style of the stroke.| | strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | No| Join style of the stroke.|
| strokeMiterLimit | number \| string | 4 | No| Limit value when the sharp angle is drawn as a miter.| | strokeMiterLimit | number \| string | 4 | No| Limit value when the sharp angle is drawn as a miter.|
| strokeOpacity | number \| string \| [Resource](../../ui/ts-types.md#resource-type)| 1 | No| Stroke opacity.| | strokeOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | No| Stroke opacity.|
| strokeWidth | Length | 1 | No| Stroke width.| | strokeWidth | Length | 1 | No| Stroke width.|
| antiAlias | boolean | true | No| Whether anti-aliasing is enabled.| | antiAlias | boolean | true | No| Whether anti-aliasing is enabled.|
......
# Rect # Rect
The **\<Rect>** component is used to draw a rectangle. The **\<Rect>** component is used to draw a rectangle.
> **NOTE** > **NOTE**
> >
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
None
## Child Components ## Child Components
...@@ -19,37 +14,37 @@ Not supported ...@@ -19,37 +14,37 @@ Not supported
## APIs ## APIs
Rect(options?: {width?: string | number,height?: string | number,radius?: string | number | Array&lt;string | number&gt;} | Rect(value?: {width?: string | number,height?: string | number,radius?: string | number | Array&lt;string | number&gt;} |
{width?: string | number,height?: string | number,radiusWidth?: string | number,radiusHeight?: string | number}) {width?: string | number,height?: string | number,radiusWidth?: string | number,radiusHeight?: string | number})
- Parameters - Parameters
| Name| Type| Mandatory| Default Value| Description| | Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| width | string \| number | No| 0 | Width of the rectangle. | | width | string \| number | No| 0 | Width.|
| height | string \| number | No| 0 | Height of the rectangle. | | height | string \| number | No| 0 | Height.|
| radius | string \| number \| Array&lt;string \| number&gt; | No| 0 | Radius of the rounded corner. You can set separate radiuses for four rounded corners.| | radius | string \| number \| Array&lt;string \| number&gt; | No| 0 | Radius of the rounded corner. You can set separate radiuses for four rounded corners.|
| radiusWidth | string \| number | No| 0 | Width of the rounded corner.| | radiusWidth | string \| number | No| 0 | Width of the rounded corner.|
| radiusHeight | string \| number | No| 0 | Height of the rounded corner.| | radiusHeight | string \| number | No| 0 | Height of the rounded corner.|
## Attributes ## Attributes
In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported.
| Name| Type| Default Value| Mandatory| Description| | Name| Type| Default Value| Mandatory| Description|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| radiusWidth | string \| number | 0 | No| Width of the rounded corner. The width and height are the same when only the width is set.| | radiusWidth | string \| number | 0 | No| Width of the rounded corner. The width and height are the same when only the width is set.|
| radiusHeight | string \| number | 0 | No| Height of the rounded corner. The width and height are the same only when the height is set.| | radiusHeight | string \| number | 0 | No| Height of the rounded corner. The width and height are the same only when the height is set.|
| radius | string \| number \| Array&lt;string \| number&gt; | 0 | No| Radius of the rounded corner. You can set separate radiuses for four rounded corners.| | radius | string \| number \| Array&lt;string \| number&gt; | 0 | No| Radius of the rounded corner. You can set separate radiuses for four rounded corners.|
| fill | [ResourceColor](../../ui/ts-types.md) | Color.Black | No| Color of the fill area.| | fill | [ResourceColor](ts-types.md#resourcecolor) | Color.Black | No| Color of the fill area.|
| fillOpacity | number \| string \| [Resource](../../ui/ts-types.md#resource-type)| 1 | No| Opacity of the fill area.| | fillOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | No| Opacity of the fill area.|
| stroke | [ResourceColor](../../ui/ts-types.md) | Color.Black | No| Stroke color.| | stroke | [ResourceColor](ts-types.md#resourcecolor) | Color.Black | No| Stroke color.|
| strokeDashArray | Array&lt;Length&gt; | [] | No| Stroke dash.| | strokeDashArray | Array&lt;Length&gt; | [] | No| Stroke dash.|
| strokeDashOffset | number \| string | 0 | No| Offset of the start point for drawing the stroke.| | strokeDashOffset | number \| string | 0 | No| Offset of the start point for drawing the stroke.|
| strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | No| Cap style of the stroke.| | strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | No| Cap style of the stroke.|
| strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | No| Join style of the stroke.| | strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | No| Join style of the stroke.|
| strokeMiterLimit | number \| string | 4 | No| Limit value when the sharp angle is drawn as a miter.| | strokeMiterLimit | number \| string | 4 | No| Limit value when the sharp angle is drawn as a miter.|
| strokeOpacity | number \| string \| [Resource](../../ui/ts-types.md#resource-type)| 1 | No| Stroke opacity.| | strokeOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | No| Stroke opacity.|
| strokeWidth | Length | 1 | No| Stroke width.| | strokeWidth | Length | 1 | No| Stroke width.|
| antiAlias | boolean | true | No| Whether anti-aliasing is enabled.| | antiAlias | boolean | true | No| Whether anti-aliasing is enabled.|
......
# Shape # Shape
> **NOTE**
>
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
The **\<Shape>** component is the parent component of the drawing components. The attributes described in this topic are universal attributes supported by all the drawing components. The **\<Shape>** component is the parent component of the drawing components. The attributes described in this topic are universal attributes supported by all the drawing components.
1. Drawing components use **\<Shape>** as their parent to implement the effect similar to SVG. 1. Drawing components use **\<Shape>** as their parent to implement the effect similar to SVG.
2. The **\<Shape>** component is used independently to draw a specific shape. 2. The **\<Shape>** component is used independently to draw a specific shape.
> **NOTE**
## Required Permissions >
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
None
## Child Components ## Child Components
...@@ -41,15 +34,15 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the ...@@ -41,15 +34,15 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| Name| Type| Default Value| Mandatory| Description| | Name| Type| Default Value| Mandatory| Description|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| viewPort | {<br>x?: number \| string,<br>y?: number \| string,<br>width?: number \| string,<br>height?: number \| string<br>} | { x:0, y:0, width:0, height:0 } | No| View port of the shape.| | viewPort | {<br>x?: number \| string,<br>y?: number \| string,<br>width?: number \| string,<br>height?: number \| string<br>} | { x:0, y:0, width:0, height:0 } | No| View port of the shape.|
| fill | [ResourceColor](../../ui/ts-types.md) | Color.Black | No| Color of the fill area.| | fill | [ResourceColor](ts-types.md#resourcecolor) | Color.Black | No| Color of the fill area.|
| fillOpacity | number \| string \| [Resource](../../ui/ts-types.md#resource-type)| 1 | No| Opacity of the fill area.| | fillOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | No| Opacity of the fill area.|
| stroke | [ResourceColor](../../ui/ts-types.md) | Color.Black | No| Stroke color.| | stroke | [ResourceColor](ts-types.md#resourcecolor) | Color.Black | No| Stroke color.|
| strokeDashArray | Array&lt;Length&gt; | [] | No| Stroke dash.| | strokeDashArray | Array&lt;Length&gt; | [] | No| Stroke dash.|
| strokeDashOffset | number \| string | 0 | No| Offset of the start point for drawing the stroke.| | strokeDashOffset | number \| string | 0 | No| Offset of the start point for drawing the stroke.|
| strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | No| Cap style of the stroke.| | strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | No| Cap style of the stroke.|
| strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | No| Join style of the stroke.| | strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | No| Join style of the stroke.|
| strokeMiterLimit | number \| string | 4 | No| Limit value when the sharp angle is drawn as a miter.| | strokeMiterLimit | number \| string | 4 | No| Limit value when the sharp angle is drawn as a miter.|
| strokeOpacity | number \| string \| [Resource](../../ui/ts-types.md#resource-type)| 1 | No| Stroke opacity.| | strokeOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | No| Stroke opacity.|
| strokeWidth | number \| string | 1 | No| Stroke width.| | strokeWidth | number \| string | 1 | No| Stroke width.|
| antiAlias | boolean | true | No| Whether anti-aliasing is enabled.| | antiAlias | boolean | true | No| Whether anti-aliasing is enabled.|
| mesh<sup>8+</sup> | Array&lt;number&gt;,number,number | [],0,0 | No| Mesh effect. The first parameter is an array of lengths (column + 1) * (row + 1) * 2, which records the position of each vertex of the distorted bitmap. The second parameter is the number of columns in the mesh matrix. The third parameter is the number of rows in the mesh matrix.| | mesh<sup>8+</sup> | Array&lt;number&gt;,number,number | [],0,0 | No| Mesh effect. The first parameter is an array of lengths (column + 1) * (row + 1) * 2, which records the position of each vertex of the distorted bitmap. The second parameter is the number of columns in the mesh matrix. The third parameter is the number of rows in the mesh matrix.|
......
...@@ -9,10 +9,10 @@ You can create explicit animation with your custom settings. ...@@ -9,10 +9,10 @@ You can create explicit animation with your custom settings.
| API | Description | | API | Description |
| ------------------------------------------------------------ | ------------------------------------------------------------ | | ------------------------------------------------------------ | ------------------------------------------------------------ |
| animateTo(value: [AnimationOptions](#animationoptions), event: ()=&gt; void) : void | Provides a transition animation when the status changes due to the closure code.<br>**event** specifies the closure function that displays the dynamic effect. The system automatically inserts the transition animation if the status changes in the closure function.| | animateTo(value: [AnimateParam](#animateparam), event: ()=&gt; void) : void | Provides a transition animation when the status changes due to the closure code.<br>**event** specifies the closure function that displays the dynamic effect. The system automatically inserts the transition animation if the status changes in the closure function.|
## AnimationOptions ## AnimateParam
| Name| Type| Description| | Name| Type| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
......
# Gesture Binding Methods # Gesture Binding
Bind different types of gesture events to components and set response methods for them.
> **NOTE**<br> > **NOTE**
> This method is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. >
> The APIs of this module are supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions ## Required Permissions
...@@ -16,50 +18,76 @@ None ...@@ -16,50 +18,76 @@ None
Use the following attributes to bind gesture recognition to a component. When a gesture is recognized, the event callback is invoked to notify the component. Use the following attributes to bind gesture recognition to a component. When a gesture is recognized, the event callback is invoked to notify the component.
| Name | Type | Default Value | Description | | Parameter| Type| Default Value| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| gesture | gesture: GestureType,<br/>mask?: GestureMask | gesture: -,<br/>mask: GestureMask.Normal | Gesture to recognize.<br/>**gesture** specifies the type of the gesture to bind, and **mask** specifies the event response setting. | | gesture | gesture: GestureType,<br>mask?: GestureMask | gesture: -,<br>mask: GestureMask.Normal | Gesture to recognize.<br>- **gesture**: type of the gesture to bind.<br>- **mask**: event response setting.|
| priorityGesture | gesture: GestureType,<br/>mask?: GestureMask | gesture: -,<br/>mask: GestureMask.Normal | Gesture to preferentially recognize.<br/>**gesture** specifies the type of the gesture to bind, and **mask** specifies the event response setting.<br/>**NOTE**<br/>By default, the child component takes precedence over the parent component in gesture recognition. When **priorityGesture** is configured for the parent component, the parent component takes precedence over the child component in gesture recognition. | | priorityGesture | gesture: GestureType,<br>mask?: GestureMask | gesture: -,<br>mask: GestureMask.Normal | Gesture to preferentially recognize.<br>- **gesture**: type of the gesture to bind.<br>- **mask**: event response setting.<br>By default, the child component takes precedence over the parent component in gesture recognition. When **priorityGesture** is configured for the parent component, the parent component takes precedence over the child component in gesture recognition.|
| parallelGesture | gesture: GestureType,<br/>mask?: GestureMask | gesture: -,<br/>mask: GestureMask.Normal | Gesture that can be triggered together with the child component gesture.<br/>**gesture** specifies the type of the gesture to bind, and **mask** specifies the event response setting.<br/>**NOTE**<br/>The gesture event is not a bubbling event. When **parallelGesture** is set for the parent component, gesture events that are the same for the parent component and child components can be triggered, thereby implementing a bubbling effect. | | parallelGesture | gesture: GestureType,<br>mask?: GestureMask | gesture: -,<br>mask: GestureMask.Normal | Gesture that can be triggered together with the child component gesture.<br>- **gesture**: type of the gesture to bind. <br>- **mask**: event response setting.<br>The gesture event is not a bubbling event. When **parallelGesture** is set for the parent component, gesture events that are the same for the parent component and child components can be triggered, thereby implementing a bubbling effect.|
- GestureMask enums - GestureMask
| Name | Description | | Name| Description|
| -------- | -------- | | -------- | -------- |
| Normal | The gestures of child components are not masked and are recognized based on the default gesture recognition sequence. | | Normal | The gestures of child components are not masked and are recognized based on the default gesture recognition sequence.|
| IgnoreInternal | The gestures of child components are masked. Only the gestures of the current component are recognized.<br/>**NOTE**<br/>The built-in gestures of the child components are not masked. For example, when the child component is a **&lt;List&gt;** component, the built-in sliding gestures can still be triggered. | | IgnoreInternal | The gestures of child components are masked. Only the gestures of the current component are recognized.<br>However, the built-in gestures of the child components are not masked. For example, when the child component is a **<List>** component, the built-in sliding gestures can still be triggered.|
- GestureType enums - GestureType
| Name | Description | | Name| Description|
| -------- | -------- | | -------- | -------- |
| TapGesture | Tap gesture, which can be a single-tap or multi-tap gesture. | | TapGesture | Tap gesture, which can be a single-tap or multi-tap gesture.|
| LongPressGesture | Long press gesture. | | LongPressGesture | Long press gesture.|
| PanGesture | Pan gesture. | | PanGesture | Pan gesture, which requires a minimum 5 vp movement distance of a finger on the screen.|
| PinchGesture | Pinch gesture. | | PinchGesture | Pinch gesture.|
| RotationGesture | Rotation gesture. | | RotationGesture | Rotation gesture.|
| GestureGroup | A group of gestures. Continuous recognition, parallel recognition, and exclusive recognition are supported. | | SwipeGesture | Swipe gesture, which can be recognized when the swipe speed is 100 vp/s or higher.|
| GestureGroup | A group of gestures. Continuous recognition, parallel recognition, and exclusive recognition are supported.|
## Gesture Response Event ## Gesture Response Event
The component uses the **gesture** method to bind the gesture object and uses the events provided in this object to respond to the gesture operation. For example, the **onAction** event of the **TapGesture** object can be used to respond to a click event. For details about the events, see the section of each gesture object. The component uses the **gesture** method to bind the gesture object and uses the events provided in this object to respond to the gesture operation. For example, the **onAction** event of the **TapGesture** object can be used to respond to a click event. For details about the event definitions of other gestures, see the corresponding gesture sections.
- TapGesture events - TapGesture
| Name | Description | | Name| Description|
| -------- | -------- | | -------- | -------- |
| onAction((event?: GestureEvent) =&gt; void) | Callback invoked when a tap gesture is recognized. | | onAction((event?:GestureEvent) =&gt; void) | Callback invoked when a tap gesture is recognized.|
- GestureEvent attributes - GestureEvent attributes
| Name | Type | Description | | Name| Type| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| timestamp | number | Timestamp of the event. | | timestamp<sup>8+</sup> | number | Timestamp of the event. It is interval between the time when the event is triggered and the time when the system starts, in nanoseconds.|
| target<sup>8+</sup> | EventTarget | Object that triggers the gesture event. | | target<sup>8+</sup> | [EventTarget](ts-universal-events-click.md) | Display area of the element that triggers the gesture event.|
| source<sup>8+</sup> | SourceType | Event input device.|
| repeat | boolean | Whether the event is triggered repeatedly. This parameter is used for the **LongPressGesture** event.|
| fingerList<sup>8+</sup> | FingerInfo[] | Information about all fingers that trigger the event, which is used for the **LongPressGesture** and **TapGesture** events.|
| offsetX | number | Offset of the gesture event on the x-axis, in vp. This parameter is used for the **PanGesture** event.|
| offsetY | number | Offset of the gesture event on the y-axis, in vp. This parameter is used for the **PanGesture** event.|
| angle | number | Rotation angle for the **RotationGesture** event; angle of the swipe gesture for the **SwipeGesture** event, that is, the change in the included angle between the line segment created by the two fingers and the horizontal direction.<br>**NOTE**<br>Angle calculation method: After a swipe gesture is recognized, a line connecting the two fingers is identified as the initial line. As the fingers swipe, the line between the fingers rotates. Based on the coordinates of the initial line's and current line's end points, an arc tangent function is used to calculate the respective included angle of the points relative to the horizontal direction by using the following formula: Rotation angle = arctan2(cy2-cy1,cx2-cx1) - arctan2(y2-y1,x2-x1) The initial line is used as the coordinate system. The clockwise rotation is 0 to 180 degrees, and the counter-clockwise rotation is –180 to 0 degrees. |
| speed<sup>8+</sup> | number | Swipe gesture speed, that is, the average swipe speed of all fingers. The unit is vp/s. This attribute is used for the **SwipeGesture** event.|
| scale | number | Scale ratio. This attribute is used for the **PinchGesture** event.|
| pinchCenterX | number | X-coordinate of the center of the pinch gesture, in px. This attribute is used for the **PinchGesture** event.|
| pinchCenterY | number | Y-coordinate of the center of the pinch gesture, in px. This attribute is used for the **PinchGesture** event.|
- SourceType
| Name| Description|
| -------- | -------- |
| Unknown | Unknown device type.|
| Mouse | Mouse.|
| TouchScreen | Touchscreen.|
- FingerInfo
| Name| Type| Description|
| -------- | -------- | -------- |
| id | number | Index of a finger.|
| globalX | number | X-coordinate relative to the upper left corner of the application window.|
| globalY | number | Y-coordinate relative to the upper left corner of the application window.|
| localX | number | X-coordinate relative to the upper left corner of the current component.|
| localY | number | Y-coordinate relative to the upper left corner of the current component.|
## Example ## Example
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
...@@ -77,7 +105,7 @@ struct GestureSettingsExample { ...@@ -77,7 +105,7 @@ struct GestureSettingsExample {
this.value = 'gesture onAction' this.value = 'gesture onAction'
})) }))
}.height(200).width(300).padding(60).border({ width: 1 }) }.height(200).width(300).padding(60).border({ width: 1 })
// When priorityGesture is specified, the bound gesture is preferentially recognized and the child component gesture is ignored. // When priorityGesture is specified, the bound gesture is preferentially recognized and the child component gesture is ignored.
.priorityGesture( .priorityGesture(
TapGesture() TapGesture()
.onAction((event: GestureEvent) => { .onAction((event: GestureEvent) => {
...@@ -91,4 +119,4 @@ struct GestureSettingsExample { ...@@ -91,4 +119,4 @@ struct GestureSettingsExample {
} }
``` ```
![en-us_image_0000001256858411](figures/en-us_image_0000001256858411.gif) ![en-us_image_0000001257058419](figures/en-us_image_0000001257058419.gif)
\ No newline at end of file
# Interpolation Calculation # Interpolation Calculation
Interpolation calculation can be implemented to set the animation interpolation curve, which is used to construct the step curve, cubic Bezier curve, and spring curve objects.
> **NOTE**
>
> This event is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
> **NOTE**<br>
> This animation is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Modules to Import ## Modules to Import
```ts ```js
import curves from '@ohos.curves' import Curves from '@ohos.curves'
``` ```
## Required Permissions
None ## Curves.initCurve<sup>9+</sup>
## curves.init initCurve(curve?: Curve): ICurve
init(curve?: Curve): Object
Implements initialization for the interpolation curve, which is used to create an interpolation curve object based on the input parameter. Implements initialization for the interpolation curve, which is used to create an interpolation curve object based on the input parameter.
- Parameters **Parameters**
| Name| Type | Mandatory| Default Value | Description |
| ------ | ------------------------------------------------------------ | ---- | ------------ | ---------- |
| curve | [Curve](#curve-enums)| No | Curve.Linear | Curve type.|
**Return value**
| Type | Description |
| ---------------------------------- | ---------------- |
| [ICurve](#icurve) | Interpolation object of the curve.|
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| curve | Curve | No | Linear | Curve object. |
- Return value<br> **Example**
Curve object.
```ts
import Curves from '@ohos.curves'
Curves.initCurve(Curve.EaseIn) // Create an ease-in curve.
```
## curves.steps ## Curves.stepsCurve<sup>9+</sup>
stepsCurve(count: number, end: boolean): ICurve
steps(count: number, end: boolean): Object
Constructs a step curve object. Constructs a step curve object.
- Parameters **Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------- | ----| ------------------------------------------------------------ |
| count | number | Yes | Number of steps. Must be a positive integer. |
| end | boolean | Yes | Whether the step change occurs at the start or end point of each interval.<br>- **true**: The step change occurs at the end point.<br>- **false**: The step change occurs at the start point.|
**Return value**
| Type | Description |
| ---------------------------------- | ---------------- |
| [ICurve](#icurve) | Curve object.|
**Example**
```ts
import Curves from '@ohos.curves'
Curves.stepsCurve(9, true) // Create a step curve.
```
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| count | number | Yes | - | Number of steps. The value must be a positive integer. |
| end | boolean | No | true | Step change at the start or end point of each interval. Defaults to **true**, indicating that the step change occurs at the end point. |
- Return value ## Curves.cubicBezierCurve<sup>9+</sup>
Curve object.
## curves.cubicBezier cubicBezierCurve(x1: number, y1: number, x2: number, y2: number): ICurve
cubicBezier(x1: number, y1: number, x2: number, y2: number): Object
Constructs a third-order Bezier curve object. The curve value must be between 0 and 1. Constructs a third-order Bezier curve object. The curve value must be between 0 and 1.
1. Parameters
| Name | Type | Mandatory | Description | **Parameters**
| ---- | ------ | --------- | -------------------------------------------------------------- | | Name | Type | Mandatory | Description |
| x1 | number | Yes | Horizontal coordinate of the first point on the Bezier curve. | | ---- | ------ | ---- | -------------- |
| y1 | number | Yes | Vertical coordinate of the first point on the Bezier curve. | | x1 | number | Yes | Horizontal coordinate of the first point on the Bezier curve.|
| x2 | number | Yes | Horizontal coordinate of the second point on the Bezier curve. | | y1 | number | Yes | Vertical coordinate of the first point on the Bezier curve.|
| y2 | number | Yes | Vertical coordinate of the second point on the Bezier curve. | | x2 | number | Yes | Horizontal coordinate of the second point on the Bezier curve.|
| y2 | number | Yes | Vertical coordinate of the second point on the Bezier curve.|
2. Return value **Return value**
Curve object.
## curves.spring | Type | Description |
| ---------------------------------- | ---------------- |
| [ICurve](#icurve) | Curve object.|
**Example**
```ts
import Curves from '@ohos.curves'
Curves.cubicBezierCurve(0.1, 0.0, 0.1, 1.0) // Create a cubic Bezier curve.
```
## Curves.springCurve<sup>9+</sup>
springCurve(velocity: number, mass: number, stiffness: number, damping: number): ICurve
spring(velocity: number, mass: number, stiffness: number, damping: number): Object
Constructs a spring curve object. Constructs a spring curve object.
1. Parameters
| Name | Type | Mandatory | Description | **Parameters**
| --------- | ------ | --------- | ----------------- | | Name | Type | Mandatory | Description |
| velocity | number | Yes | Initial velocity. | | --------- | ------ | ---- | ----- |
| mass | number | Yes | Mass. | | velocity | number | Yes | Initial velocity. It is a parameter that affects the elastic dynamic effect by external factors. It aims to ensure the smooth transition from the previous motion state to the elastic dynamic effect.|
| stiffness | number | Yes | Stiffness. | | mass | number | Yes | Quality. The force object of the elastic system will have inertia effects on the elastic system. The greater the mass, the greater the amplitude of the oscillation, and the slower the speed of restoring to the equilibrium position.|
| damping | number | Yes | Damping. | | stiffness | number | Yes | Stiffness. It is the degree to which an object deforms by resisting the force applied. In an elastic system, the greater the stiffness, the stronger the ability to resist deformation, and the faster the speed of restoring to the equilibrium position.|
| damping | number | Yes | Damping. It is a pure number and has no real physical meaning. It is used to describe the oscillation and attenuation of the system after being disturbed. The larger the damping, the smaller the number of oscillations of elastic motion and the smaller the oscillation amplitude.|
2. Return value
Curve object.
## Example **Return value**
| Type | Description |
| ---------------------------------- | ---------------- |
| [ICurve](#icurve)| Curve object.|
**Example**
```ts ```ts
import Curves from '@ohos.curves' import Curves from '@ohos.curves'
let curve1 = Curves.init() // Create a default linear interpolation curve. Curves.springCurve(100, 1, 228, 30) // Create a spring curve.
let curve2 = Curves.init(Curve.EaseIn) // Create an interpolation curve which is slow and then fast by default.
let curve3 = Curves.spring(100, 1, 228, 30) // Create a spring interpolation curve.
let curve3 = Curves.cubicBezier(0.1, 0.0, 0.1, 1.0) // Create a third-order Bezier curve.
``` ```
Curve objects can be created only by the preceding APIs.
| API | Description |
| -------- | -------- |
| interpolate(time: number): number | Calculation function of the interpolation curve. Passing a normalized time parameter to this function returns the current interpolation.<br/>**time**: indicates the current normalized time. The value ranges from 0 to 1.<br/>The curve interpolation corresponding to the normalized time point is returned. |
- Example ## ICurve
```ts
import Curves from '@ohos.curves' ### interpolate
let curve = Curves.init(Curve.EaseIn) // Create an interpolation curve which is slow and then fast by default.
let value: number = curve.interpolate(0.5) // Calculate the interpolation for half of the time. interpolate(fraction: number): number
```
Calculation function of the interpolation curve. Passing a normalized time parameter to this function returns the current interpolation.
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------ | ---- | -------------------------------------------- |
| fraction | number | Yes | Current normalized time. The value ranges from 0 to 1.|
**Return value**
| Type | Description |
| ------ | ------------------------------------ |
| number | The curve interpolation corresponding to the normalized time point is returned.|
**Example**
```ts
import Curves from '@ohos.curves'
let curve = Curves.initCurve(Curve.EaseIn) // Create an ease-in curve.
let value: number = curve.interpolate(0.5) // Calculate the interpolation for half of the time.
```
## Curves.init<sup>(deprecated)</sup>
init(curve?: Curve): string
Implements initialization to create a curve object based on the input parameter. This API is deprecated since API version 9. Use [Curves.initCurve](#curvesinitcurve9) instead.
**Parameters**
| Name| Type | Mandatory| Default Value | Description |
| ------ | ------------------------------------------------------------ | ---- | ------------ | ---------- |
| curve |[Curve](#curve-enums)| No | Curve.Linear | Curve type.|
## Curves.steps<sup>(deprecated)</sup>
steps(count: number, end: boolean): string
Constructs a step curve object. This API is deprecated since API version 9. Use [Curves.stepsCurve](# curvesstepscurve9) instead.
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------- | ----| ------------------------------------------------------------ |
| count | number | Yes | Number of steps. Must be a positive integer. |
| end | boolean | Yes | Whether the step change occurs at the start or end of each interval.<br>- **true**: The step change occurs at the end point.<br>- **false**: The step change occurs at the start point.|
## Curves.cubicBezier<sup>(deprecated)</sup>
cubicBezier(x1: number, y1: number, x2: number, y2: number): string
Constructs a cubic Bezier curve object. The curve value must range from 0 to 1. This API is deprecated since API version 9. Use [Curves.cubicBezierCurve](#curvescubicbeziercurve9) instead.
**Parameters**
| Name | Type | Mandatory | Description |
| ---- | ------ | ---- | -------------- |
| x1 | number | Yes | Horizontal coordinate of the first point on the Bezier curve.|
| y1 | number | Yes | Vertical coordinate of the first point on the Bezier curve.|
| x2 | number | Yes | Horizontal coordinate of the second point on the Bezier curve.|
| y2 | number | Yes | Vertical coordinate of the second point on the Bezier curve.|
## Curves.spring<sup>(deprecated)</sup>
spring(velocity: number, mass: number, stiffness: number, damping: number): string
Constructs a spring curve object. This API is deprecated since API version 9. Use [Curves.cubicBezierCurve](#curvescubicbeziercurve9) instead.
**Parameters**
| Name | Type | Mandatory | Description |
| --------- | ------ | ---- | ----- |
| velocity | number | Yes | Initial velocity. It is a parameter that affects the elastic dynamic effect by external factors. It aims to ensure the smooth transition from the previous motion state to the elastic dynamic effect.|
| mass | number | Yes | Quality. The force object of the elastic system will have inertia effects on the elastic system. The greater the mass, the greater the amplitude of the oscillation, and the slower the speed of restoring to the equilibrium position.|
| stiffness | number | Yes | Stiffness. It is the degree to which an object deforms by resisting the force applied. In an elastic system, the greater the stiffness, the stronger the ability to resist deformation, and the faster the speed of restoring to the equilibrium position.|
| damping | number | Yes | Damping. It is a pure number and has no real physical meaning. It is used to describe the oscillation and attenuation of the system after being disturbed. The larger the damping, the smaller the number of oscillations of elastic motion and the smaller the oscillation amplitude.|
## Curve
| Name | Description |
| ------------------- | ---------------------------------------- |
| Linear | The animation speed keeps unchanged. |
| Ease | The animation starts slowly, accelerates, and then slows down towards the end. The cubic-bezier curve (0.25, 0.1, 0.25, 1.0) is used.|
| EaseIn | The animation starts at a low speed and then picks up speed until the end. The cubic-bezier curve (0.42, 0.0, 1.0, 1.0) is used.|
| EaseOut | The animation ends at a low speed. The cubic-bezier curve (0.0, 0.0, 0.58, 1.0) is used.|
| EaseInOut | The animation starts and ends at a low speed. The cubic-bezier curve (0.42, 0.0, 0.58, 1.0) is used.|
| FastOutSlowIn | The animation uses the standard cubic-bezier curve (0.4, 0.0, 0.2, 1.0).|
| LinearOutSlowIn | The animation uses the deceleration cubic-bezier curve (0.0, 0.0, 0.2, 1.0).|
| FastOutLinearIn | The animation uses the acceleration cubic-bezier curve (0.4, 0.0, 1.0, 1.0).|
| ExtremeDeceleration | The animation uses the extreme deceleration cubic-bezier curve (0.0, 0.0, 0.0, 1.0).|
| Sharp | The animation uses the sharp cubic-bezier curve (0.33, 0.0, 0.67, 1.0).|
| Rhythm | The animation uses the rhythm cubic-bezier curve (0.7, 0.0, 0.2, 1.0).|
| Smooth | The animation uses the smooth cubic-bezier curve (0.4, 0.0, 0.4, 1.0).|
| Friction | The animation uses the friction cubic-bezier curve (0.2, 0.0, 0.2, 1.0).|
## Example ## Example
```ts ```ts
// xxx.ets
import Curves from '@ohos.curves' import Curves from '@ohos.curves'
@Entry @Entry
@Component @Component
...@@ -124,14 +265,13 @@ struct ImageComponent { ...@@ -124,14 +265,13 @@ struct ImageComponent {
.height(this.heightSize) .height(this.heightSize)
.backgroundColor(Color.Red) .backgroundColor(Color.Red)
.onClick(()=> { .onClick(()=> {
let curve = Curves.cubicBezier(0.25, 0.1, 0.25, 1.0); let curve = Curves.cubicBezierCurve(0.25, 0.1, 0.25, 1.0);
this.widthSize = curve.interpolate(0.5) * this.widthSize; this.widthSize = curve.interpolate(0.5) * this.widthSize;
this.heightSize = curve.interpolate(0.5) * this.heightSize; this.heightSize = curve.interpolate(0.5) * this.heightSize;
}) })
.animation({duration: 2000 , curve: Curves.spring(0.25, 0.1, 0.25, 1.0)}) .animation({duration: 2000 , curve: Curves.stepsCurve(9, true)})
}.width("100%").height("100%") }.width("100%").height("100%")
} }
} }
``` ```
![en-us_image_0000001212058456](figures/en-us_image_0000001212058456.gif)
![en-us_image_0000001212058456](figures/en-us_image_0000001212058456.gif)
\ No newline at end of file
# Matrix Transformation # Matrix Transformation
> **NOTE**<br> Matrix transformation enables you to rotate, scale, skew, or translate an image.
> This animation is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
> **NOTE**
>
> The APIs of this module are supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Modules to Import ## Modules to Import
...@@ -9,335 +13,429 @@ ...@@ -9,335 +13,429 @@
import matrix4 from '@ohos.matrix4' import matrix4 from '@ohos.matrix4'
``` ```
## Required Permissions
None
## matrix4.init ## matrix4.init
init(array: Array&lt;number&gt;): Object init(array: Array&lt;number&gt;): Matrix4Transit
Matrix constructor, which is used to create a 4x4 matrix by using the input parameter. Column-major order is used. Matrix constructor, which is used to create a 4x4 matrix by using the input parameter. Column-major order is used.
1. Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- | | Name| Type | Mandatory| Description |
| array | Array&lt;number&gt; | Yes | [1, 0, 0, 0,<br/>0, 1, 0, 0,<br/>0, 0, 1, 0,<br/>0, 0, 0, 1] | A number array whose length is 16 (4 x 4). For details, see the parameter description. | | ------ | ------------------- | ---- | ------------------------------------------------------------ |
| array | Array&lt;number&gt; | Yes | A number array whose length is 16 (4 x 4). For details, see **array**.<br>Default value:<br>[1, 0, 0, 0,<br>0, 1, 0, 0,<br>0, 0, 1, 0,<br>0, 0, 0, 1] |
2. Return value
| Type | Description | **Return value**
| ------ | ------------------------------------------------------- |
| Object | 4x4 matrix object created based on the input parameter. | | Type | Description |
| -------------- | ---------------------------- |
3. Parameter description | Matrix4Transit | 4x4 matrix object created based on the input parameter.|
| Name | Type | Mandatory | Description |
| ---- | ------ | --------- | ------------------------------------------------------------------------------- | **array**
| m00 | number | Yes | Scaling value of the x-axis. Defaults to **1** for the unit matrix. |
| m01 | number | Yes | The second value, which is affected by the rotation of the x, y, and z axes. | | Name | Type | Mandatory | Description |
| m02 | number | Yes | The third value, which is affected by the rotation of the x, y, and z axes. | | ---- | ------ | ---- | -------------------- |
| m03 | number | Yes | Meaningless. | | m00 | number | Yes | Scaling value of the x-axis. Defaults to **1** for the identity matrix. |
| m10 | number | Yes | The fifth value, which is affected by the rotation of the x, y, and z axes. | | m01 | number | Yes | The second value, which is affected by the rotation of the x, y, and z axes. |
| m11 | number | Yes | Scaling value of the y-axis. Defaults to **1** for the unit matrix. | | m02 | number | Yes | The third value, which is affected by the rotation of the x, y, and z axes. |
| m12 | number | Yes | The seventh value, which is affected by the rotation of the x, y, and z axes. | | m03 | number | Yes | Meaningless. |
| m13 | number | Yes | Meaningless. | | m10 | number | Yes | The fifth value, which is affected by the rotation of the x, y, and z axes. |
| m20 | number | Yes | The ninth value, which is affected by the rotation of the x, y, and z axes. | | m11 | number | Yes | Scaling value of the y-axis. Defaults to **1** for the identity matrix. |
| m21 | number | Yes | The tenth value, which is affected by the rotation of the x, y, and z axes. | | m12 | number | Yes | The seventh value, which is affected by the rotation of the x, y, and z axes. |
| m22 | number | Yes | Scaling value of the z-axis. Defaults to **1** for the unit matrix. | | m13 | number | Yes | Meaningless. |
| m23 | number | Yes | Meaningless. | | m20 | number | Yes | The ninth value, which is affected by the rotation of the x, y, and z axes. |
| m30 | number | Yes | Translation value of the x-axis, in px. Defaults to **0** for the unit matrix. | | m21 | number | Yes | The tenth value, which is affected by the rotation of the x, y, and z axes. |
| m31 | number | Yes | Translation value of the y-axis, in px. Defaults to **0** for the unit matrix. | | m22 | number | Yes | Scaling value of the z-axis. Defaults to **1** for the identity matrix. |
| m32 | number | Yes | Translation value of the z-axis, in px. Defaults to **0** for the unit matrix. | | m23 | number | Yes | Meaningless. |
| m33 | number | Yes | Valid in homogeneous coordinates, presenting the perspective projection effect. | | m30 | number | Yes | Translation value of the x-axis, in px. Defaults to **0** for the identity matrix.|
| m31 | number | Yes | Translation value of the y-axis, in px. Defaults to **0** for the identity matrix.|
4. Example | m32 | number | Yes | Translation value of the z-axis, in px. Defaults to **0** for the identity matrix.|
| m33 | number | Yes | Valid in homogeneous coordinates, presenting the perspective projection effect. |
```ts
import Matrix4 from '@ohos.matrix4' **Example**
// Create a 4x4 matrix.
let matrix = Matrix4.init([1.0, 0.0, 0.0, 0.0, ```ts
0.0, 1.0, 0.0, 0.0, import matrix4 from '@ohos.matrix4'
0.0, 0.0, 1.0, 0.0, // Create a 4x4 matrix.
0.0, 0.0, 0.0, 1.0]) let matrix = matrix4.init([1.0, 0.0, 0.0, 0.0,
``` 0.0, 1.0, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0])
@Entry
@Component
struct Tests {
build() {
Column() {
Image($r("app.media.zh"))
.width("40%")
.height(100)
.transform(matrix)
}
}
}
```
## matrix4.identity ## matrix4.identity
identity(): Object identity(): Matrix4Transit
Matrix initialization function. Can return a unit matrix object.
1. Return value Matrix initialization function. Can return an identity matrix object.
| Type | Description |
| ------ | ------------------- | **Return value**
| Object | Unit matrix object. |
| Type | Description |
| -------------- | -------------- |
| Matrix4Transit | Identity matrix object.|
**Example**
```ts
// The effect of matrix 1 is the same as that of matrix 2.
import matrix4 from '@ohos.matrix4'
let matrix1 = matrix4.init([1.0, 0.0, 0.0, 0.0,
0.0, 1.0, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0])
let matrix2 = matrix4.identity()
@Entry
@Component
struct Tests {
build() {
Column() {
Image($r("app.media.zh"))
.width("40%")
.height(100)
.transform(matrix1)
Image($r("app.media.zh"))
.width("40%")
.height(100)
.margin({ top: 150 })
.transform(matrix2)
}
}
}
```
2. Example
```ts
// The effect of matrix 1 is the same as that of matrix 2.
import Matrix4 from '@ohos.matrix4'
let matrix = Matrix4.init([1.0, 0.0, 0.0, 0.0,
0.0, 1.0, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0])
let matrix2 = Matrix4.identity()
```
## matrix4.copy ## matrix4.copy
copy(): Object copy(): Matrix4Transit
Matrix copy function, which is used to copy the current matrix object. Matrix copy function, which is used to copy the current matrix object.
1. Return value **Return value**
| Type | Description |
| ------ | ---------------------------------- |
| Object | Copy object of the current matrix. |
2. Example | Type | Description |
| -------------- | -------------------- |
```ts | Matrix4Transit | Copy object of the current matrix.|
import Matrix4 from '@ohos.matrix4'
@Entry **Example**
@Component
struct Test { ```ts
private matrix1 = Matrix4.identity().translate({x:100}) // xxx.ets
private matrix2 = this.matrix1.copy().scale({x:2}) import matrix4 from '@ohos.matrix4'
build() { @Entry
Column() { @Component
Image($r("app.media.bg1")) struct Test {
.width("40%") private matrix1 = Matrix4.identity().translate({x:100})
.height(100) private matrix2 = this.matrix1.copy().scale({x:2})
.transform(this.matrix1)
Image($r("app.media.bg2")) build() {
.width("40%") Column() {
.height(100) Image($r("app.media.bg1"))
.margin({top:50}) .width("40%")
.transform(this.matrix2) .height(100)
} .transform(this.matrix1)
Image($r("app.media.bg2"))
.width("40%")
.height(100)
.margin({top:50})
.transform(this.matrix2)
} }
} }
``` }
```
![en-us_image_0000001256858419](figures/en-us_image_0000001256858419.png)
![en-us_image_0000001256858419](figures/en-us_image_0000001256858419.png)
## Matrix4 ## Matrix4
### combine ### combine
combine(matrix: Matrix4): Object combine(matrix: Matrix4): Matrix4Transit
Matrix overlay function, which is used to overlay the effects of two matrices to generate a new matrix object. Matrix overlay function, which is used to overlay the effects of two matrices to generate a new matrix object.
1. Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ------ | ------- | --------- | ------------- | ----------------------------- |
| matrix | Matrix4 | Yes | - | Matrix object to be overlaid. |
2. Return value | Name| Type | Mandatory| Description |
| Type | Description | | ------ | ------- | ---- | ------------------ |
| ------ | ---------------------------- | | matrix | Matrix4 | Yes | Matrix object to be overlaid.|
| Object | Object after matrix overlay. |
- Example **Return value**
```ts | Type | Description |
import Matrix4 from '@ohos.matrix4' | -------------- | ------------------ |
@Entry | Matrix4Transit | Object after matrix overlay.|
@Component
struct Test { **Example**
private matrix1 = Matrix4.identity().translate({x:200}).copy()
private matrix2 = Matrix4.identity().scale({x:2}).copy() ```ts
build() { // xxx.ets
Column() { import matrix4 from '@ohos.matrix4'
// Translate the x-axis by 100 pixels and then scale it up or down by 2x. @Entry
Image($r("app.media.bg1")).transform(this.matrix1.combine(this.matrix2)) @Component
.width("40%") struct Test {
.height(100) private matrix1 = matrix4.identity().translate({x:200}).copy()
.margin({top:50}) private matrix2 = matrix4.identity().scale({x:2}).copy()
}
build() {
Column() {
// Before matrix transformation
Image($r("app.media.icon"))
.width("40%")
.height(100)
.margin({top:50})
// Translate the x-axis by 200px, and then scale down the x-axis twice.
Image($r("app.media.icon"))
.transform(this.matrix1.combine(this.matrix2))
.width("40%")
.height(100)
.margin({top:50})
} }
} }
``` }
```
![en-us_image_0000001212378428](figures/en-us_image_0000001212378428.png)
![en-us_image_0000001212378428](figures/en-us_image_0000001212378428.png)
### invert ### invert
invert(): Object invert(): Matrix4Transit
Matrix inverse function. Can return an inverse matrix of the current matrix object, that is, get an opposite effect. Matrix inverse function. Can return an inverse matrix of the current matrix object, that is, get an opposite effect.
1. Return value **Return value**
| Type | Description |
| ------ | -------- | | Type | Description |
| Object | Inverse matrix object of the current matrix. | | -------------- | ---------------------- |
| Matrix4Transit | Inverse matrix object of the current matrix.|
**Example**
```ts
import matrix4 from '@ohos.matrix4'
// The effect of matrix 1 (width scaled up by 2x) is opposite to that of matrix 2 (width scaled down by 2x).
let matrix1 = matrix4.identity().scale({x:2})
let matrix2 = matrix1.invert()
@Entry
@Component
struct Tests {
build() {
Column() {
Image($r("app.media.zh"))
.width(200)
.height(100)
.transform(matrix1)
.margin({ top: 100 })
Image($r("app.media.zh"))
.width(200)
.height(100)
.margin({ top: 150 })
.transform(matrix2)
}
}
}
```
2. Example
```ts
import Matrix4 from '@ohos.matrix4'
// The effect of matrix 1 (width scaled up by 2x) is opposite to that of matrix 2 (width scaled down by 2x).
let matrix1 = Matrix4.identity().scale({x:2})
let matrix2 = matrix1.invert()
```
### translate ### translate
translate({x?: number, y?: number, z?: number}): Object translate({x?: number, y?: number, z?: number}): Matrix4Transit
Matrix translation function, which is used to add the translation effect to the x, y, and z axes of the current matrix. Matrix translation function, which is used to add the translation effect to the x, y, and z axes of the current matrix.
1. Parameters **Parameter**
| Name | Type | Mandatory | Default Value | Description |
|----- | ------ | -------- | -------------- | ------------------------------------------ |
| x | number | No | 0 | Translation distance of the x-axis, in px. |
| y | number | No | 0 | Translation distance of the y-axis, in px. |
| z | number | No | 0 | Translation distance of the z-axis, in px. |
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------------------------------------- |
| x | number | No | Translation distance of the x-axis, in px.<br>Default value: **0**|
| y | number | No | Translation distance of the y-axis, in px.<br>Default value: **0**|
| z | number | No | Translation distance of the z-axis, in px.<br>Default value: **0**|
2. Return value **Return value**
| Type | Description |
| ------ | ---------------------------------------------------- |
| Object | Matrix object after the translation effect is added. |
3. Example | Type | Description |
| -------------- | ---------------------------- |
```ts | Matrix4Transit | Matrix object after the translation effect is added.|
import Matrix4 from '@ohos.matrix4'
@Entry **Example**
@Component
struct Test { ```ts
private matrix1 = Matrix4.identity().translate({x:100, y:200, z:30}) // xxx.ets
build() { import matrix4 from '@ohos.matrix4'
Column() { @Entry
Image($r("app.media.bg1")).transform(this.matrix1) @Component
.width("40%") struct Test {
.height(100) private matrix1 = matrix4.identity().translate({x:100, y:200, z:30})
}
build() {
Column() {
Image($r("app.media.bg1")).transform(this.matrix1)
.width("40%")
.height(100)
} }
} }
``` }
```
![en-us_image_0000001212058494](figures/en-us_image_0000001212058494.png)
![en-us_image_0000001212058494](figures/en-us_image_0000001212058494.png)
### scale ### scale
scale({x?: number, y?: number, z?: number, centerX?: number, centerY?: number}): Object scale({x?: number, y?: number, z?: number, centerX?: number, centerY?: number}): Matrix4Transit
Matrix scaling function, which is used to add the scaling effect to the x, y, and z axes of the current matrix. Matrix scaling function, which is used to add the scaling effect to the x, y, and z axes of the current matrix.
1. Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ------- | ------ | --------- | ------------- | --------------------------------- |
| x | number | No | 1 | Scaling multiple of the x-axis. |
| y | number | No | 1 | Scaling multiple of the y-axis. |
| z | number | No | 1 | Scaling multiple of the z-axis. |
| centerX | number | No | 0 | X coordinate of the center point. |
| centerY | number | No | 0 | Y coordinate of the center point. |
| Name | Type | Mandatory| Description |
| ------- | ------ | ---- | --------------------------------- |
| x | number | No | Scaling multiple of the x-axis.<br>Default value: **1** |
| y | number | No | Scaling multiple of the y-axis.<br>Default value: **1** |
| z | number | No | Scaling multiple of the z-axis.<br>Default value: **1** |
| centerX | number | No | X coordinate of the center point.<br>Default value: **0**|
| centerY | number | No | Y coordinate of the center point.<br>Default value: **0**|
2. Return value **Return value**
| Type | Description |
| ------ | ------------------------------------------------ |
| Object | Matrix object after the scaling effect is added. |
3. Example | Type | Description |
| -------------- | ---------------------------- |
```ts | Matrix4Transit | Matrix object after the scaling effect is added.|
import Matrix4 from '@ohos.matrix4'
@Entry **Example**
@Component
struct Test { ```ts
private matrix1 = Matrix4.identity().scale({x:2, y:3, z:4, centerX:50, centerY:50}) // xxx.ets
build() { import matrix4 from '@ohos.matrix4'
Column() { @Entry
Image($r("app.media.bg1")).transform(this.matrix1) @Component
.width("40%") struct Test {
.height(100) private matrix1 = matrix4.identity().scale({x:2, y:3, z:4, centerX:50, centerY:50})
}
build() {
Column() {
Image($r("app.media.bg1")).transform(this.matrix1)
.width("40%")
.height(100)
} }
} }
``` }
```
![zh-cn_image_0000001219864131](figures/zh-cn_image_0000001219864131.png)
![en-us_image_0000001256978367](figures/en-us_image_0000001256978367.png)
### rotate ### rotate
rotate({x?: number, y?: number, z?: number, angle?: number, centerX?: Length, centerY?: Length}): Object rotate({x?: number, y?: number, z?: number, angle?: number, centerX?: Length, centerY?: Length}): Matrix4Transit
Matrix rotation function, which is used to add the rotation effect to the x, y, and z axes of the current matrix. Matrix rotation function, which is used to add the rotation effect to the x, y, and z axes of the current matrix.
1. Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ------- | ------ | --------- | ------------- | ----------------------------------------- | | Name | Type | Mandatory| Description |
| x | number | No | 1 | X coordinate of the rotation axis vector. | | ------- | ------ | ---- | --------------------------------- |
| y | number | No | 1 | Y coordinate of the rotation axis vector. | | x | number | No | X coordinate of the rotation axis vector.<br>Default value: **1** |
| z | number | No | 1 | Z coordinate of the rotation axis vector. | | y | number | No | Y coordinate of the rotation axis vector.<br>Default value: **1** |
| angle | number | No | 0 | Rotation angle. | | z | number | No | Z coordinate of the rotation axis vector.<br>Default value: **1** |
| centerX | number | No | 0 | X coordinate of the center point. | | angle | number | No | Rotation angle.<br>Default value: **0** |
| centerY | number | No | 0 | Y coordinate of the center point. | | centerX | number | No | X coordinate of the center point.<br>Default value: **0**|
| centerY | number | No | Y coordinate of the center point.<br>Default value: **0**|
2. Return value
| Type | Description | **Return value**
| ------ | ------------------------------------------------- |
| Object | Matrix object after the rotation effect is added. | | Type | Description |
| -------------- | ---------------------------- |
3. Example | Matrix4Transit | Matrix object after the rotation effect is added.|
```ts **Example**
import Matrix4 from '@ohos.matrix4'
@Entry ```ts
@Component // xxx.ets
struct Test { import matrix4 from '@ohos.matrix4'
private matrix1 = Matrix4.identity().rotate({x:1, y:1, z:2, angle:30}) @Entry
build() { @Component
Column() { struct Test {
Image($r("app.media.bg1")).transform(this.matrix1) private matrix1 = matrix4.identity().rotate({x:1, y:1, z:2, angle:30})
.width("40%")
.height(100) build() {
}.width("100%").margin({top:50}) Column() {
} Image($r("app.media.bg1")).transform(this.matrix1)
.width("40%")
.height(100)
}.width("100%").margin({top:50})
} }
``` }
```
![en-us_image_0000001211898504](figures/en-us_image_0000001211898504.png)
![en-us_image_0000001211898504](figures/en-us_image_0000001211898504.png)
### transformPoint ### transformPoint
transformPoint(point: Point): Point transformPoint(point: Point): Point
Matrix point transformation function, which is used to apply the current transformation effect to a coordinate point. Matrix point transformation function, which is used to apply the current transformation effect to a coordinate point.
1. Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ----- | ----- | --------- | ------------- | ------------------------ |
| point | Point | Yes | - | Point to be transformed. |
2. Return value | Name| Type | Mandatory| Description |
| Type | Description | | ------ | ----- | ---- | ------------------ |
| ----- | ----------------------------------------- | | point | Point | Yes | Point to be transformed.|
| Point | Point object after matrix transformation. |
3. Example **Return value**
```ts | Type | Description |
import Matrix4 from '@ohos.matrix4' | ----- | ---------------- |
import prompt from '@system.prompt' | Point | Point object after matrix transformation|
**Example**
```ts
// xxx.ets
import matrix4 from '@ohos.matrix4'
import prompt from '@system.prompt'
@Entry
@Component
struct Test {
private matrix1 = matrix4.identity().transformPoint([100, 10])
@Entry build() {
@Component Column() {
struct Test { Button("get Point")
private matrix1 = Matrix4.identity().transformPoint([100, 10]) .onClick(() => {
build() { prompt.showToast({message:JSON.stringify(this.matrix1),duration:2000})
Column() { }).backgroundColor(0x2788D9)
Button("get Point") }.width("100%").padding(50)
.onClick(() => {
prompt.showToast({message:JSON.stringify(this.matrix1),duration:2000})
}).backgroundColor(0x2788D9)
}.width("100%").padding(50)
}
} }
``` }
```
![en-us_image_0000001212218464](figures/en-us_image_0000001212218464.gif) ![en-us_image_0000001212218464](figures/en-us_image_0000001212218464.gif)
\ No newline at end of file
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
The **\<Video>** component is used to play a video and control its playback. The **\<Video>** component is used to play a video and control its playback.
> **NOTE**<br> > **NOTE**
> >
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
...@@ -24,9 +24,9 @@ Video(value: {src?: string | Resource, currentProgressRate?: number | string | P ...@@ -24,9 +24,9 @@ Video(value: {src?: string | Resource, currentProgressRate?: number | string | P
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ------------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | ------------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| src | string \| [Resource](../../ui/ts-types.md) | No | Path of the video source, which can be a local path or a URL.<br>The video resources can be stored in the **video** or **rawfile** folder under **resources**.<br>The path can include a **dataability://** prefix, which is used to access the video path provided by a Data ability. For details about the path, see [Data Ability Development](../../ability/fa-dataability.md).<br>**NOTE**<br>The supported video formats are MP4, MKV, WebM, and TS. | | src | string \| [Resource](ts-types.md#resource) | No | Path of the video source, which can be a local path or a URL.<br>The video resources can be stored in the **video** or **rawfile** folder under **resources**.<br>The path can include a **dataability://** prefix, which is used to access the video path provided by a Data ability. For details about the path, see [Data Ability Development](../../ability/fa-dataability.md).<br>**NOTE**<br>The supported video formats are MP4, MKV, WebM, and TS. |
| currentProgressRate | number \| string \| PlaybackSpeed<sup>8+</sup> | No | Video playback speed.<br>**NOTE**<br>The value of the number type can only be **0.75**, **1.0**, **1.25**, **1.75**, or **2.0**.<br>Default value: **1.0** \| **PlaybackSpeed.Speed_Forward_1_00_X** | | currentProgressRate | number \| string \| PlaybackSpeed<sup>8+</sup> | No | Video playback speed.<br>**NOTE**<br>The value of the number type can only be **0.75**, **1.0**, **1.25**, **1.75**, or **2.0**.<br>Default value: **1.0** \| PlaybackSpeed.Speed_Forward_1_00_X |
| previewUri | string \| PixelMap<sup>8+</sup> \| [Resource](../../ui/ts-types.md) | No | Path of the preview image. | | previewUri | string \| PixelMap<sup>8+</sup> \| [Resource](ts-types.md#resource) | No | Path of the preview image. |
| controller | [VideoController](#videocontroller) | No | Controller. | | controller | [VideoController](#videocontroller) | No | Controller. |
## PlaybackSpeed<sup>8+</sup> ## PlaybackSpeed<sup>8+</sup>
...@@ -62,9 +62,10 @@ In addition to the universal events (ts-universal-events-click.md), the followin ...@@ -62,9 +62,10 @@ In addition to the universal events (ts-universal-events-click.md), the followin
| onFinish(event:() =&gt; void) | Triggered when the video playback is finished. | | onFinish(event:() =&gt; void) | Triggered when the video playback is finished. |
| onError(event:() =&gt; void) | Triggered when the video playback fails. | | onError(event:() =&gt; void) | Triggered when the video playback fails. |
| onPrepared(callback:(event?: { duration: number }) =&gt; void) | Triggered when video preparation is complete. The video duration (in seconds) is obtained from **duration**.| | onPrepared(callback:(event?: { duration: number }) =&gt; void) | Triggered when video preparation is complete. The video duration (in seconds) is obtained from **duration**.|
| onSeeking(callback:(event?: { duration: number }) =&gt; void) | Triggered to report the time (in seconds) when the progress bar is being dragged. | | onSeeking(callback:(event?: { time: number }) =&gt; void) | Triggered to report the time (in seconds) when the progress bar is being dragged. |
| onSeeked(callback:(event?: { duration: number }) =&gt; void) | Triggered to report the playback time (in seconds) when the user finishes dragging the progress bar. | | onSeeked(callback:(event?: { time: number }) =&gt; void) | Triggered to report the playback time (in seconds) when the user finishes dragging the progress bar. |
| onUpdate(callback:(event?: { duration: number }) =&gt; void) | Triggered once per 250 ms when the playback progress changes. The unit of the current playback time is second. | | onUpdate(callback:(event?: { time: number }) =&gt; void) | Triggered once per 250 ms when the playback progress changes. The unit of the current playback time is second. |
| onFullscreenChange(callback:(event?: { fullscreen: boolean }) =&gt; void) | Triggered when the playback mode is switched between full-screen mode and non-full-screen mode. The value **true** means that the playback is in full-screen mode, and **false** means that the playback is non-full-screen mode. |
## VideoController ## VideoController
...@@ -158,7 +159,7 @@ Sets the video playback position with the specified seek mode. ...@@ -158,7 +159,7 @@ Sets the video playback position with the specified seek mode.
@Entry @Entry
@Component @Component
struct VideoCreateComponent { struct VideoCreateComponent {
@State srcs: Resource = $rawfile('video1'); @State srcs: Resource = $rawfile('video1.mp4');
@State previewUris: Resource = $r('app.media.img'); @State previewUris: Resource = $r('app.media.img');
@State currentProgressRates: number = 1; @State currentProgressRates: number = 1;
@State autoPlays: boolean = false; @State autoPlays: boolean = false;
...@@ -201,7 +202,7 @@ struct VideoCreateComponent { ...@@ -201,7 +202,7 @@ struct VideoCreateComponent {
}) })
Row() { Row() {
Button("src").onClick(() => { Button("src").onClick(() => {
this.srcs = $rawfile('video2'); this.srcs = $rawfile('video2.mp4');
}); });
Button("previewUri").onClick(() => { Button("previewUri").onClick(() => {
this.previewUris = $r('app.media.img1'); this.previewUris = $r('app.media.img1');
......
# Action Sheet # Action Sheet
An action sheet is a dialog box that displays actions a user can take.
> **NOTE** > **NOTE**
> >
> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. > The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
An action sheet is a dialog box that displays actions a user can take.
## Required Permissions ## Required Permissions
...@@ -16,39 +14,41 @@ None ...@@ -16,39 +14,41 @@ None
## ActionSheet.show ## ActionSheet.show
show(options: { paramObject1}) show(value: { title: string | Resource, message: string | Resource, confirm?: {value: string | Resource, action:() => void}, cancel?:()=>void, sheets: Array&lt;SheetInfo&gt;, autoCancel?:boolean, alignment?: DialogAlignment, offset?: { dx: number | string | Resource; dy: number | string | Resource } })
Defines and shows an action sheet. Defines and shows the action sheet.
- paramObject1 parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| title | string \|[Resource](../../ui/ts-types.md) | No | None | Title of the dialog box. |
| message | string \|[Resource](../../ui/ts-types.md) | | | Content of the dialog box. |
| autoCancel | boolean | No | true | Whether to close the dialog box when the overlay is clicked. |
| confirm | {<br/>value: string \| [Resource](../../ui/ts-types.md),<br/>action: () =&gt; void<br/>} | No | - | Text content of the confirm button and callback upon button clicking.<br/>**value**: button text.<br/>**action**: callback upon button clicking. |
| cancel | () =&gt; void | No | - | Callback invoked when the dialog box is closed after the overlay is clicked. |
| alignment | [DialogAlignment](ts-methods-custom-dialog-box.md) | No | DialogAlignment.Default | Alignment mode of the dialog box in the vertical direction. |
| offset | {<br/>dx: Length,<br/>dy: Length<br/>} | No | {<br/>dx: 0,<br/>dy: 0<br/>} | Offset of the dialog box relative to the alignment position. |
| sheets | Array<SheetInfo&gt; | Yes | - | Options in the dialog box. Each option supports the image, text, and callback. |
- SheetInfo parameters | Name | Type | Mandatory | Description |
| Name | Type | Mandatory | Default Value | Description | | ---------- | -------------------------- | ------- | ----------------------------- |
| -------- | -------- | -------- | -------- | -------- | | title | string \| [Resource](ts-types.md#resource) | Yes | Title of the dialog box.|
| title | string \| [Resource](../../ui/ts-types.md) | Yes | - | Sheet text. | | message | string \| [Resource](ts-types.md#resource) | Yes | Content of the dialog box. |
| icon | string \| [Resource](../../ui/ts-types.md) | No | None | Sheet icon. | | autoCancel | boolean | No | Whether to close the dialog box when the overlay is clicked.<br>Default value: **true**|
| action | ()=&gt;void | Yes | - | Callback when the sheet is selected. | | confirm | {<br>value: string \| [Resource](ts-types.md#resource),<br>action: () =&gt; void<br>} | No | Text content of the confirm button and callback upon button clicking.<br>Default value:<br>**value**: button text.<br>**action**: callback upon button clicking.|
| cancel | () =&gt; void | No | Callback invoked when the dialog box is closed after the overlay is clicked. |
| alignment | [DialogAlignment](ts-methods-custom-dialog-box.md#dialogalignment) | No | Alignment mode of the dialog box in the vertical direction.<br>Default value: **DialogAlignment.Default**|
| offset | {<br>dx: Length,<br>dy: Length<br>} | No | Offset of the dialog box relative to the alignment position.{<br>dx: 0,<br>dy: 0<br>} |
| sheets | Array&lt;SheetInfo&gt; | Yes | Options in the dialog box. Each option supports the image, text, and callback.|
## SheetInfo parameters
## Example | Name| Type | Mandatory| Description |
| ------ | ------------------------------------------------------------ | ---- | ----------------- |
| title | string \| [Resource](ts-types.md#resource) | Yes | Sheet text. |
| icon | string \| [Resource](ts-types.md#resource) | No | Sheet icon. By default, no icon is displayed. |
| action | ()=&gt;void | Yes | Callback when the sheet is selected.|
## Example
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
@Component @Component
struct ActionSheetExample { struct ActionSheetExample {
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Button('Click to Show ActionSheet') Button('Click to Show ActionSheet')
...@@ -90,6 +90,4 @@ struct ActionSheetExample { ...@@ -90,6 +90,4 @@ struct ActionSheetExample {
} }
``` ```
![en-us_image_0000001212058508](figures/en-us_image_0000001212058508.gif) ![en-us_image_0000001212058508](figures/en-us_image_0000001212058508.gif)
# Alert Dialog Box # Alert Dialog Box
You can set the text content and response callback for an alert dialog box.
> **NOTE** > **NOTE**
> >
> This method is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > The APIs of this module are supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
The **<AlertDialog\>** component is used to display an alert dialog box. You can set the text content and response callback for an alert dialog box as needed.
## Attributes ## Attributes
| Name | Type | Default Value | Description | | Name | Type | Description|
| -------- | -------- | -------- | -------- | | ---- | --------------- | -------- |
| show | options: { paramObject1 \| paramObject2} | - | Defines and displays the **<AlertDialog\>** component. | | show | AlertDialogParamWithConfirm \| AlertDialogParamWithButtons | Shows the **\<AlertDialog>** component. |
- paramObject1 parameters ## AlertDialogParamWithConfirm
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- | -------- | | ---------- | ---------------- | ---------- | ------------------------------- |
| title | string \| [Resource](../../ui/ts-types.md) | No | - | Title of a dialog box. | | title | [ResourceStr](ts-types.md#resourcestr) | No | Title of the dialog box.|
| message | string \| [Resource](../../ui/ts-types.md) | Yes | - | Content of the dialog box. | | message | [ResourceStr](ts-types.md#resourcestr) | Yes | Content of the dialog box.|
| autoCancel | boolean | No | true | Whether to close the dialog box when the overlay is clicked. | | autoCancel | boolean | No | Whether to close the dialog box when the overlay is clicked.<br>Default value: **true**|
| confirm | {<br/>value: string \| [Resource](../../ui/ts-types.md),<br>fontColor?: Color\| number \| string \| [Resource](../../ui/ts-types.md),<br/>backgroundColor?:Color \| number \| string \| [Resource](../../ui/ts-types.md),<br>action: () =&gt; void<br/>} <br/> | No | - | Text content, text color, background color, and click callback of the confirm button. | | confirm | {<br>value: string \| [Resource](ts-types.md#resource),<br>fontColor?: Color \| number \| string \| [Resource](ts-types.md#resource),<br>backgroundColor?: Color \| number \| string \| [Resource](ts-types.md#resource),<br>action: () =&gt; void<br>} | No | Text content, text color, background color, and click callback of the confirm button.|
| cancel | () =&gt; void | No | - | Callback invoked when the dialog box is closed after the overlay is clicked. | | cancel | () =&gt; void | No | Callback invoked when the dialog box is closed after the overlay is clicked.|
| alignment | [DialogAlignment](ts-methods-custom-dialog-box.md) | No | DialogAlignment.Default | Alignment mode of the dialog box in the vertical direction. | | alignment | [DialogAlignment](ts-methods-custom-dialog-box.md#dialogalignment) | No | Alignment mode of the dialog box in the vertical direction.<br>Default value: **DialogAlignment.Default**|
| offset | {<br/>dx: Length \| [Resource](../../ui/ts-types.md),<br/>dy: Length \| [Resource](../../ui/ts-types.md)<br/>} | No | - | Offset of the dialog box relative to the alignment position. | | offset | [Offset](ts-types.md#offset) | No | Offset of the dialog box relative to the alignment position.|
| gridCount | number | No | - | Number of grid columns occupied by the width of the dialog box. | | gridCount | number | No | Number of grid columns occupied by the width of the dialog box. |
- paramObject2 parameters
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| title | string \| [Resource](../../ui/ts-types.md) | No | - | Title of a dialog box. |
| message | string \| [Resource](../../ui/ts-types.md) | Yes | - | Content of the dialog box. |
| autoCancel | boolean | No | true | Whether to close the dialog box when the overlay is clicked. |
| primaryButton | {<br/>value: string \| [Resource](../../ui/ts-types.md),<br>fontColor?: Color \| number \| string \| [Resource](../../ui/ts-types.md),<br/>backgroundColor?:Color \| number\| string\| [Resource](../../ui/ts-types.md),<br>action: () =&gt; void<br/>} <br/> | No | - | Text content, text color, background color, and click callback of the primary button. |
| secondaryButton | {<br/>value: string \|[Resource](../../ui/ts-types.md),<br>fontColor?: Color \| number \| string \| [Resource](../../ui/ts-types.md),<br/>backgroundColor?:Color \| number\| string\| [Resource](../../ui/ts-types.md),<br>action: () =&gt; void<br/>} <br/> | No | - | Text content, text color, background color, and click callback of the secondary button. |
| cancel | () =&gt; void | No | - | Callback invoked when the dialog box is closed after the overlay is clicked. |
| alignment | [DialogAlignment](ts-methods-custom-dialog-box.md) | No | DialogAlignment.Default | Alignment mode of the dialog box in the vertical direction. |
| offset | {<br/>dx: Length \| [Resource](../../ui/ts-types.md),<br/>dy: Length \| [Resource](../../ui/ts-types.md)<br/>} | No | - | Offset of the dialog box relative to the alignment position. |
| gridCount | number | No | - | Number of grid columns occupied by the width of the dialog box. |
## AlertDialogParamWithButtons
| Name | Type | Mandatory | Description |
| --------------- | ---------------------- | ------------ | --------------------- |
| title | [ResourceStr](ts-types.md#resourcestr) | No | Title of the dialog box. |
| message | [ResourceStr](ts-types.md#resourcestr) | Yes | Content of the dialog box. |
| autoCancel | boolean | No | Whether to close the dialog box when the overlay is clicked.<br>Default value: **true** |
| primaryButton | {<br>value: string \| [Resource](ts-types.md#resource),<br>fontColor?: Color \| number \| string \| [Resource](ts-types.md#resource),<br>backgroundColor?: Color \| number \| string \| [Resource](ts-types.md#resource),<br>action: () =&gt; void;<br>} | No| Text content, text color, background color, and click callback of the primary button.|
| secondaryButton | {<br>value: string \| [Resource](ts-types.md#resource),<br>fontColor?: Color \| number \| string \| [Resource](ts-types.md#resource),<br>backgroundColor?: Color \| number \| string \| [Resource](ts-types.md#resource),<br>action: () =&gt; void;<br>} | No | Text content, text color, background color, and click callback of the primary button.|
| cancel | () =&gt; void | No | Callback invoked when the dialog box is closed after the overlay is clicked. |
| alignment | [DialogAlignment](ts-methods-custom-dialog-box.md#dialogalignment) | No | Alignment mode of the dialog box in the vertical direction.<br>Default value: **DialogAlignment.Default**|
| offset | [Offset](ts-types.md#offset) | No | Offset of the dialog box relative to the alignment position.|
| gridCount | number | No | Number of grid columns occupied by the width of the dialog box. |
## Example ## Example
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
@Component @Component
struct AlertDialogExample { struct AlertDialogExample {
build() { build() {
Column({ space: 5 }) { Column({ space: 5 }) {
Button('one button dialog') Button('one button dialog')
......
...@@ -7,35 +7,39 @@ A custom dialog box is a dialog box you customize by using APIs of the **CustomD ...@@ -7,35 +7,39 @@ A custom dialog box is a dialog box you customize by using APIs of the **CustomD
> The APIs of this module are supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > The APIs of this module are supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## APIs ## APIs
CustomDialogController(value:{builder: CustomDialog, cancel?: () =&gt; void, autoCancel?: boolean, alignment?: DialogAlignment, offset?: Offset, customStyle?: boolean}) CustomDialogController(value:{builder: CustomDialog, cancel?: () =&gt; void, autoCancel?: boolean, alignment?: DialogAlignment, offset?: Offset, customStyle?: boolean, gridCount?: number})
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ---------------------- | ---------------------------------------- | ---- | ----------------------- | ---------------------- | | Name | Type | Mandatory | Description |
| builder | [CustomDialog](../../ui/ts-component-based-customdialog.md) | Yes | - | Constructor of the custom dialog box content. | | ---------------------- | ---------------------------------------- | ------------------------- | ---------------------- |
| cancel | () =&gt; void | No | - | Callback invoked when the dialog box is closed after the overlay exits. | | builder | [CustomDialog](../../ui/ts-component-based-customdialog.md) | Yes | Constructor of the custom dialog box content. |
| autoCancel | boolean | No | true | Whether to allow users to click the overlay to exit. | | cancel | () =&gt; void | No | Callback invoked when the dialog box is closed after the overlay exits. |
| alignment | DialogAlignment | No | DialogAlignment.Default | Alignment mode of the dialog box in the vertical direction. | | autoCancel | boolean | No | Whether to allow users to click the overlay to exit.<br>Default value: **true** |
| offset | {<br>dx: Length \| [Resource](../../ui/ts-types.md#resource)<br>dy: Length \| [Resource](../../ui/ts-types.md#resource)<br>} | No | - | Offset of the dialog box relative to the alignment position.| | alignment | [DialogAlignment](#dialogalignment) | No | Alignment mode of the dialog box in the vertical direction.<br>Default value: **DialogAlignment.Default** |
| customStyle | boolean | No | false | Whether to use a custom style for the dialog box. | | offset | {<br>dx: Length \| [Resource](ts-types.md#resource),<br>dy: Length \| [Resource](ts-types.md#resource)<br>} | No | Offset of the dialog box relative to the alignment position.|
| gridCount<sup>8+</sup> | number | No | - | Number of grid columns occupied by the dialog box. | | customStyle | boolean | No | Whether to use a custom style for the dialog box.<br>Default value: **false** |
| gridCount<sup>8+</sup> | number | No | Number of grid columns occupied by the dialog box. |
- DialogAlignment
| Name | Description | ## DialogAlignment
| ------------------------ | ------- |
| Top | Vertical top alignment.| | Name | Description |
| Center | Vertical center alignment.| | ------------------------ | ------- |
| Bottom | Vertical bottom alignment.| | Top | Vertical top alignment.|
| Default | Default alignment. | | Center | Vertical center alignment.|
| TopStart<sup>8+</sup> | Top left alignment. | | Bottom | Vertical bottom alignment.|
| TopEnd<sup>8+</sup> | Top right alignment. | | Default | Default alignment. |
| CenterStart<sup>8+</sup> | Center left alignment. | | TopStart<sup>8+</sup> | Top left alignment. |
| CenterEnd<sup>8+</sup> | Center right alignment. | | TopEnd<sup>8+</sup> | Top right alignment. |
| BottomStart<sup>8+</sup> | Bottom left alignment. | | CenterStart<sup>8+</sup> | Center left alignment. |
| BottomEnd<sup>8+</sup> | Bottom right alignment. | | CenterEnd<sup>8+</sup> | Center right alignment. |
| BottomStart<sup>8+</sup> | Bottom left alignment. |
| BottomEnd<sup>8+</sup> | Bottom right alignment. |
## CustomDialogController ## CustomDialogController
......
...@@ -4,7 +4,7 @@ A date picker dialog box is a dialog box that allows users to select a date from ...@@ -4,7 +4,7 @@ A date picker dialog box is a dialog box that allows users to select a date from
> **NOTE** > **NOTE**
> >
> The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. > The APIs of this module are supported since API version 9. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions ## Required Permissions
...@@ -24,9 +24,9 @@ Shows a date picker dialog box. ...@@ -24,9 +24,9 @@ Shows a date picker dialog box.
| end | Date | No| Date('2100-12-31') | End date of the picker.| | end | Date | No| Date('2100-12-31') | End date of the picker.|
| selected | Date | No| Current system date| Date of the selected item.| | selected | Date | No| Current system date| Date of the selected item.|
| lunar | boolean | No| false | Whether to display the lunar calendar.| | lunar | boolean | No| false | Whether to display the lunar calendar.|
| onAccept | (value: [DatePickerResult](ts-basic-components-datepicker.md#DatePickerResult)) => void | No| - | Callback invoked when the OK button in the dialog box is clicked. | | onAccept | (value: [DatePickerResult](ts-basic-components-datepicker.md#DatePickerResult)) => void | No| - | Callback invoked when the OK button in the dialog box is clicked.|
| onCancel | () => void | No| - | Callback invoked when the Cancel button in the dialog box is clicked. | | onCancel | () => void | No| - | Callback invoked when the Cancel button in the dialog box is clicked.|
| onChange | (value: [DatePickerResult](ts-basic-components-datepicker.md#DatePickerResult)) => void | No| - | Callback invoked when the selected item in the picker changes. | | onChange | (value: [DatePickerResult](ts-basic-components-datepicker.md#DatePickerResult)) => void | No| - | Callback invoked when the selected item in the picker changes.|
## Example ## Example
......
# Menu # Menu
The menu bound to a component through [bindContextMenu](../ts-universal-attributes-menu.md#atrributes) on a page can be closed as needed. The menu bound to a component through [bindContextMenu](./ts-universal-attributes-menu.md#atrributes) on a page can be closed as needed.
> **NOTE** > **NOTE**
> >
...@@ -15,7 +15,7 @@ None ...@@ -15,7 +15,7 @@ None
## ContextMenu.close ## ContextMenu.close
|Name|Description| |Name|Description|
|----|---| |----|---|
| close(): void | Closes the menu bound to this component through [bindContextMenu](../ts-universal-attributes-menu.md#atrributes) on a page. | | close(): void | Closes the menu bound to this component through [bindContextMenu](./ts-universal-attributes-menu.md#atrributes) on a page.|
## Example ## Example
......
...@@ -13,20 +13,20 @@ None ...@@ -13,20 +13,20 @@ None
## TextPickerDialog.show ## TextPickerDialog.show
show(options: TextPickerDialogOptions) show(options?: TextPickerDialogOptions)
Shows a text picker in the given settings. Shows a text picker in the given settings.
- TextPickerDialogOptions - TextPickerDialogOptions
| Name| Type| Mandatory| Default Value| Description| | Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| range | string[] | Yes| - | Data selection range of the picker.| | range | string[] \| [Resource](../../ui/ts-types.md#resource)| Yes| - | Data selection range of the picker.|
| selected | number | No| 0 | Index of the selected item in the range.| | selected | number | No| 0 | Index of the selected item in the range.|
| value | string | No | - | Value of the selected item. This parameter does not take effect when the **selected** parameter is set. If the value is not within the range, the first item in the range is used instead.| | value | string | No | - | Value of the selected item. This parameter does not take effect when the **selected** parameter is set. If the value is not within the range, the first item in the range is used instead.|
| defaultPickerItemHeight | number \| string | No| - | Default height of an item in the picker.| | defaultPickerItemHeight | number \| string | No| - | Default height of an item in the picker.|
| onAccept | (value: TextPickerResult) => void | No| - | Callback invoked when the OK button in the dialog box is clicked. | | onAccept | (value: TextPickerResult) => void | No| - | Callback invoked when the OK button in the dialog box is clicked.|
| onCancel | () => void | No| - | Callback invoked when the Cancel button in the dialog box is clicked. | | onCancel | () => void | No| - | Callback invoked when the Cancel button in the dialog box is clicked.|
| onChange | (value: TextPickerResult) => void | No| - | Callback invoked when the selected item in the picker changes. | | onChange | (value: TextPickerResult) => void | No| - | Callback invoked when the selected item in the picker changes.|
- TextPickerResult - TextPickerResult
| Name| Type| Description| | Name| Type| Description|
......
...@@ -4,7 +4,7 @@ A time picker dialog box is a dialog box that allows users to select a time from ...@@ -4,7 +4,7 @@ A time picker dialog box is a dialog box that allows users to select a time from
> **NOTE** > **NOTE**
> >
> The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. > The APIs of this module are supported since API version 9. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions ## Required Permissions
...@@ -22,9 +22,9 @@ Shows a time picker dialog box. ...@@ -22,9 +22,9 @@ Shows a time picker dialog box.
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| selected | Date | No| Current system time| Time of the selected item.| | selected | Date | No| Current system time| Time of the selected item.|
| useMilitaryTime | boolean | No| false | Whether to display time in 24-hour format.| | useMilitaryTime | boolean | No| false | Whether to display time in 24-hour format.|
| onAccept | (value: [TimePickerResult](ts-basic-components-timepicker.md#TimePickerResult)) => void | No| - | Callback invoked when the OK button in the dialog box is clicked. | | onAccept | (value: [TimePickerResult](ts-basic-components-timepicker.md#TimePickerResult)) => void | No| - | Callback invoked when the OK button in the dialog box is clicked.|
| onCancel | () => void | No| - | Callback invoked when the Cancel button in the dialog box is clicked. | | onCancel | () => void | No| - | Callback invoked when the Cancel button in the dialog box is clicked.|
| onChange | (value: [TimePickerResult](ts-basic-components-timepicker.md#TimePickerResult)) => void | No| - | Callback invoked when the selected item in the picker changes. | | onChange | (value: [TimePickerResult](ts-basic-components-timepicker.md#TimePickerResult)) => void | No| - | Callback invoked when the selected item in the picker changes.|
## Example ## Example
......
...@@ -9,7 +9,7 @@ The motion path animation is used to animate a component along a custom path. ...@@ -9,7 +9,7 @@ The motion path animation is used to animate a component along a custom path.
## Attributes ## Attributes
| Parameter| Type| Default Value| Description| | Name| Type| Default Value| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| motionPath | {<br>path: string,<br>from?: number,<br>to?: number,<br>rotatable?: boolean<br>}<br>**NOTE**<br>In a path, **start** and **end** can be used to replace the start point and end point. Example:<br>'Mstart.x start.y L50 50 Lend.x end.y Z'| {<br>"",<br>0.0,<br>1.0,<br>false<br>} | Motion path of the component. The input parameters are described as follows:<br>- **path**: motion path of the translation animation. The value is an SVG path string.<br>- **from**: start point of the motion path. The default value is **0.0**.<br>- **to**: end point of the motion path. The default value is **1.0**.<br>- **rotatable**: whether to rotate along the path.| | motionPath | {<br>path: string,<br>from?: number,<br>to?: number,<br>rotatable?: boolean<br>}<br>**NOTE**<br>In a path, **start** and **end** can be used to replace the start point and end point. Example:<br>'Mstart.x start.y L50 50 Lend.x end.y Z'| {<br>"",<br>0.0,<br>1.0,<br>false<br>} | Motion path of the component. The input parameters are described as follows:<br>- **path**: motion path of the translation animation. The value is an SVG path string.<br>- **from**: start point of the motion path. The default value is **0.0**.<br>- **to**: end point of the motion path. The default value is **1.0**.<br>- **rotatable**: whether to rotate along the path.|
...@@ -26,6 +26,7 @@ struct MotionPathExample { ...@@ -26,6 +26,7 @@ struct MotionPathExample {
build() { build() {
Column() { Column() {
Button('click me') Button('click me')
// Execute the animation: Move from the start point to (300,200), then to (300,500), and finally to the end point.
.motionPath({ path: 'Mstart.x start.y L300 200 L300 500 Lend.x end.y', from: 0.0, to: 1.0, rotatable: true }) .motionPath({ path: 'Mstart.x start.y L300 200 L300 500 Lend.x end.y', from: 0.0, to: 1.0, rotatable: true })
.onClick((event: ClickEvent) => { .onClick((event: ClickEvent) => {
animateTo({ duration: 4000, curve: Curve.Linear }, () => { animateTo({ duration: 4000, curve: Curve.Linear }, () => {
......
# OffscreenCanvasRenderingContext2D # OffscreenCanvasRenderingContext2D
Use **OffscreenCanvasRenderingContext2D** to draw rectangles, images, and text offscreen onto a canvas. Drawing offscreen onto a canvas is a process where content to draw onto the canvas is first drawn in the buffer, and then converted into a picture, and finally the picture is drawn on the canvas. This process increases the drawing efficiency.
> **NOTE**<br>The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
Use **OffscreenCanvasRenderingContext2D** to draw rectangles, images, and text offscreen onto a canvas. Drawing offscreen onto a canvas is a process where content to draw onto the canvas is first drawn in the buffer, and then converted into a picture, and finally the picture is drawn on the canvas. This process increases the drawing efficiency. > **NOTE**
>
> The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
## APIs ## APIs
OffscreenCanvasRenderingContext2D(width: number, height: number, setting: RenderingContextSettings) OffscreenCanvasRenderingContext2D(width: number, height: number, setting: RenderingContextSettings)
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ------- | ---------------------------------------- | --------- | ------------- | ------------------------------- | | Name | Type | Mandatory | Default Value | Description |
| width | number | Yes | - | Width of the offscreen canvas. | | ------- | ---------------------------------------- | ---- | ---- | ------------------------------ |
| height | number | Yes | - | Height of the offscreen canvas. | | width | number | Yes | - | Width of the offscreen canvas. |
| setting | [RenderingContextSettings](ts-canvasrenderingcontext2d.md#renderingcontextsettings) | Yes | - | See RenderingContextSettings. | | height | number | Yes | - | Height of the offscreen canvas. |
| setting | [RenderingContextSettings](ts-canvasrenderingcontext2d.md#renderingcontextsettings) | Yes | - | See RenderingContextSettings.|
## Attributes ## Attributes
| Name | Type | Default Value | Description | | Name | Type | Description |
| ---------------------------------------- | ---------------------------------------- | ------------------------------- | ---------------------------------------- | | ----------------------------------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| [fillStyle](#fillstyle) | &lt;color&gt; \| [CanvasGradient](ts-components-canvas-canvasgradient.md) \| [CanvasPattern](#canvaspattern) | - | Style used to fill an area.<br/>- When the type is **&lt;color&gt;**, this attribute indicates the fill color.<br/>- When the type is **CanvasGradient**, this attribute indicates a gradient object, which is created using the [createLinearGradient](#createlineargradient) method.<br/>- When the type is **CanvasPattern**, this attribute indicates a pattern, which is created using the [createPattern](#createpattern) method. | | [fillStyle](#fillstyle) | string \| [CanvasGradient](ts-components-canvas-canvasgradient.md) \| [CanvasPattern](#canvaspattern) | Style to fill an area.<br>- When the type is **\<color>**, this parameter indicates the color of the filling area.<br>- When the type is **CanvasGradient**, this attribute indicates a gradient object, which is created using the **[createLinearGradient](#createlineargradient)** API.<br>- When the type is **CanvasPattern**, this attribute indicates a pattern, which is created using the **[createPattern](#createpattern)** API. |
| [lineWidth](#linewidth) | number | - | Line width. | | [lineWidth](#linewidth) | number | Line width. |
| [strokeStyle](#strokestyle) | &lt;color&gt; \| [CanvasGradient](ts-components-canvas-canvasgradient.md) \| [CanvasPattern](#canvaspattern) | - | Stroke style.<br/>- When the type is **&lt;color&gt;**, this attribute indicates the stroke color.<br/>- When the type is **CanvasGradient**, this attribute indicates a gradient object, which is created using the [createLinearGradient](#createlineargradient) method.<br/>- When the type is **CanvasPattern**, this attribute indicates a pattern, which is created using the [createPattern](#createpattern) method. | | [strokeStyle](#strokestyle) | string \| [CanvasGradient](ts-components-canvas-canvasgradient.md) \| [CanvasPattern](#canvaspattern) | Stroke style.<br>- When the type is **\<color>**, this parameter indicates the stroke color.<br>- When the type is **CanvasGradient**, this attribute indicates a gradient object, which is created using the **[createLinearGradient](#createlineargradient)** API.<br>- When the type is **CanvasPattern**, this attribute indicates a pattern, which is created using the **[createPattern](#createpattern)** API. |
| [lineCap](#linecap) | string | 'butt' | Style of the line endpoints. The options are as follows:<br/>- **'butt'**: The endpoints of the line are squared off.<br/>- **'round'**: The endpoints of the line are rounded.<br/>- **'square'**: The endpoints of the line are squared off by adding a box with an equal width and half the height of the line's thickness. | | [lineCap](#linecap) | CanvasLineCap | Style of the line endpoints. The options are as follows:<br>- **butt**: The endpoints of the line are squared off.<br>- **round**: The endpoints of the line are rounded.<br>- **square**: The endpoints of the line are squared off, and each endpoint has added a rectangle whose length is the same as the line thickness and whose width is half of the line thickness.<br>- Default value: **'butt'** |
| [lineJoin](#linejoin) | string | 'miter' | Style of the shape used to join line segments. The options are as follows:<br/>- **'round'**: The shape used to join line segments is a rounded corner with the radius equal to the line width.<br/>- **'bevel'**: The shape used to join line segments is a beveled corner. The rectangular corner of each line is independent.<br/>- **'miter'**: The shape used to join line segments is a mitered corner. The corner is formed by extending the outside edges of the lines until they meet. You can adjust the effect of this attribute using **miterLimit**. | | [lineJoin](#linejoin) | CanvasLineJoin | Style of the shape used to join line segments. The options are as follows:<br>- **round**: The intersection is a sector, whose radius at the rounded corner is equal to the line width.<br>- **bevel**: The intersection is a triangle. The rectangular corner of each line is independent.<br>- **miter**: The intersection has a miter corner by extending the outside edges of the lines until they meet. You can view the effect of this attribute in **miterLimit**.<br>- Default value: **'miter'** |
| [miterLimit](#miterlimit) | number | 10 | Maximum miter length. The miter length is the distance between the inner corner and the outer corner where two lines meet. | | [miterLimit](#miterlimit) | number | Maximum miter length. The miter length is the distance between the inner corner and the outer corner where two lines meet.<br>- Default value: **10** |
| [font](#font) | string | 'normal normal 14px sans-serif' | Font style.<br/>Syntax: ctx.font='font-size font-family'<br/>- (Optional) **font-size**: font size and row height. The unit can only be px.<br/>- (Optional) **font-family**: font family.<br/>Syntax: ctx.font='font-style font-weight font-size font-family'<br/>- (Optional) **font-style**: specifies the font style. Available values are **'normal'** and **'italic'**.<br/>- (Optional) **font-weight**: font weight. Available values are as follows: **'normal'**, **'bold'**, **'bolder'**, **'lighter'**, **100**, **200**, **300**, **400**, **500**, **600**, **700**, **800**, **900**<br/>- (Optional) **font-size**: font size and row height. The unit can only be px.<br/>- (Optional) **font-family**: font family. Available values are **'sans-serif'**, **'serif'**, and **'monospace'**. | | [font](#font) | string | Font style.<br>Syntax: ctx.font='font-size font-family'<br>- (Optional) **font-size**: font size and row height. The unit can only be pixels.<br>(Optional) **font-family**: font family.<br>Syntax: ctx.font='font-style font-weight font-size font-family'<br>- (Optional) **font-style**: font style. Available values are **normal** and **italic**.<br>- (Optional) **font-weight**: font weight. Available values are as follows: **normal**, **bold**, **bolder**, **lighter**, **100**, **200**, **300**, **400**, **500**, **600**, **700**, **800**, **900**.<br>- (Optional) **font-size**: font size and row height. The unit can only be pixels.<br>- (Optional) **font-family**: font family. Available values are **sans-serif**, **serif**, and **monospace**.<br>Default value: **'normal normal 14px sans-serif'** |
| [textAlign](#textalign) | string | 'left' | Text alignment mode. Available values are as follows:<br/>- **'left'**: The text is left-aligned.<br/>- **'right'**: The text is right-aligned.<br/>- **'center'**: The text is center-aligned.<br/>- **'start'**: The text is aligned with the start bound.<br/>- **'end'**: The text is aligned with the end bound.<br/>> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br/>> In the **ltr** layout mode, the value **start** equals **left**. In the **rtl** layout mode, the value **start** equals **right**. | | [textAlign](#textalign) | CanvasTextAlign | Text alignment mode. Available values are as follows:<br>- **left**: The text is left-aligned.<br>- **right**: The text is right-aligned.<br>- **center**: The text is center-aligned.<br>- **start**: The text is aligned with the start bound.<br>- **end**: The text is aligned with the end bound.<br>**NOTE**<br>In the **ltr** layout mode, the value **'start'** equals **'left'**. In the **rtl** layout mode, the value **'start'** equals **'right'**.<br>- Default value: **'left'** |
| [textBaseline](#textbaseline) | string | 'alphabetic' | Horizontal alignment mode of text. Available values are as follows:<br/>- **'alphabetic'**: The text baseline is the normal alphabetic baseline.<br/>- **'top'**: The text baseline is on the top of the text bounding box.<br/>- **'hanging'**: The text baseline is a hanging baseline over the text.<br/>- **'middle'**: The text baseline is in the middle of the text bounding box.<br/>- **'ideographic'**: The text baseline is the ideographic baseline. If a character exceeds the alphabetic baseline, the ideographic baseline is located at the bottom of the excess character.<br/>- **'bottom'**: The text baseline is at the bottom of the text bounding box. Its difference from the ideographic baseline is that the ideographic baseline does not consider letters in the next line. | | [textBaseline](#textbaseline) | CanvasTextBaseline | Horizontal alignment mode of text. Available values are as follows:<br>- **alphabetic**: The text baseline is the normal alphabetic baseline.<br>- **top**: The text baseline is on the top of the text bounding box.<br>- **hanging**: The text baseline is a hanging baseline over the text.<br>- **middle**: The text baseline is in the middle of the text bounding box.<br>**'ideographic'**: The text baseline is the ideographic baseline. If a character exceeds the alphabetic baseline, the ideographic baseline is located at the bottom of the excess character.<br>- **bottom**: The text baseline is at the bottom of the text bounding box. Its difference from the ideographic baseline is that the ideographic baseline does not consider letters in the next line.<br>- Default value: **'alphabetic'** |
| [globalAlpha](#globalalpha) | number | - | Opacity. **0.0**: completely transparent; **1.0**: completely opaque. | | [globalAlpha](#globalalpha) | number | Opacity.<br>**0.0**: completely transparent.<br>**1.0**: completely opaque. |
| [lineDashOffset](#linedashoffset) | number | 0.0 | Offset of the dashed line. The precision is float. | | [lineDashOffset](#linedashoffset) | number | Offset of the dashed line. The precision is float.<br>- Default value: **0.0** |
| [globalCompositeOperation](#globalcompositeoperation) | string | 'source-over' | Composition operation type. Available values are as follows: **'source-over'**, **'source-atop'**, **'source-in'**, **'source-out'**, **'destination-over'**, **'destination-atop'**, **'destination-in'**, **'destination-out'**, **'lighter'**, **'copy'**, and **'xor'**. | | [globalCompositeOperation](#globalcompositeoperation) | string | Composition operation type. Available values are as follows: **'source-over'**, **'source-atop'**, **'source-in'**, **'source-out'**, **'destination-over'**, **'destination-atop'**, **'destination-in'**, **'destination-out'**, **'lighter'**, **'copy'**, and **'xor'**.<br>- Default value: **'source-over'** |
| [shadowBlur](#shadowblur) | number | 0.0 | Blur level during shadow drawing. A larger value indicates a more blurred effect. The precision is float. | | [shadowBlur](#shadowblur) | number | Blur level during shadow drawing. A larger value indicates a more blurred effect. The precision is float.<br>- Default value: **0.0** |
| [shadowColor](#shadowcolor) | &lt;color&gt; | - | Shadow color. | | [shadowColor](#shadowcolor) | string | Shadow color. |
| [shadowOffsetX](#shadowoffsetx) | number | - | X-axis shadow offset relative to the original object. | | [shadowOffsetX](#shadowoffsetx) | number | X-axis shadow offset relative to the original object. |
| [shadowOffsetY](#shadowoffsety) | number | - | Y-axis shadow offset relative to the original object. | | [shadowOffsetY](#shadowoffsety) | number | Y-axis shadow offset relative to the original object. |
| [imageSmoothingEnabled](#imagesmoothingenabled) | boolean | true | Whether to adjust the image smoothness during image drawing. The value **true** means to enable this feature, and **false** means the opposite. | | [imageSmoothingEnabled](#imagesmoothingenabled) | boolean | Whether to adjust the image smoothness during image drawing. The value **true** means to enable this feature, and **false** means the opposite.<br>- Default value: **true** |
| imageSmoothingQuality | string | 'low' | Image smoothness. The value can be **'low'**, **'medium'**, or **'high'**. | | imageSmoothingQuality | string | Image smoothness. The value can be **'low'**, **'medium'**, or **'high'**.<br>- Default value: **'low'** |
> **NOTE** > **NOTE**
> The value of the **&lt;color&gt;** type can be in 'rgb(255, 255, 255)', 'rgba(255, 255, 255, 1.0)', or '\#FFFFFF' format. >
> For **fillStyle**, **shadowColor**, and **strokeStyle**, the value format of the string type is 'rgb(255, 255, 255)', 'rgba(255, 255, 255, 1.0)', '\#FFFFFF'.
### fillStyle ### fillStyle
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
...@@ -82,7 +84,6 @@ struct FillStyleExample { ...@@ -82,7 +84,6 @@ struct FillStyleExample {
### lineWidth ### lineWidth
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
...@@ -116,7 +117,6 @@ struct LineWidthExample { ...@@ -116,7 +117,6 @@ struct LineWidthExample {
### strokeStyle ### strokeStyle
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
...@@ -146,13 +146,11 @@ struct StrokeStyleExample { ...@@ -146,13 +146,11 @@ struct StrokeStyleExample {
} }
``` ```
![en-us_image_0000001257058429](figures/en-us_image_0000001257058429.png) ![en-us_image_0000001257058429](figures/en-us_image_0000001257058429.png)
### lineCap ### lineCap
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
...@@ -190,7 +188,6 @@ struct LineCapExample { ...@@ -190,7 +188,6 @@ struct LineCapExample {
### lineJoin ### lineJoin
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
...@@ -229,7 +226,6 @@ struct LineJoinExample { ...@@ -229,7 +226,6 @@ struct LineJoinExample {
### miterLimit ### miterLimit
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
...@@ -268,7 +264,6 @@ struct MiterLimit { ...@@ -268,7 +264,6 @@ struct MiterLimit {
### font ### font
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
...@@ -302,7 +297,6 @@ struct Fonts { ...@@ -302,7 +297,6 @@ struct Fonts {
### textAlign ### textAlign
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
...@@ -351,7 +345,6 @@ struct CanvasExample { ...@@ -351,7 +345,6 @@ struct CanvasExample {
### textBaseline ### textBaseline
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
...@@ -400,7 +393,6 @@ struct TextBaseline { ...@@ -400,7 +393,6 @@ struct TextBaseline {
### globalAlpha ### globalAlpha
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
...@@ -437,7 +429,6 @@ struct GlobalAlpha { ...@@ -437,7 +429,6 @@ struct GlobalAlpha {
### lineDashOffset ### lineDashOffset
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
...@@ -456,6 +447,7 @@ struct LineDashOffset { ...@@ -456,6 +447,7 @@ struct LineDashOffset {
.onReady(() =>{ .onReady(() =>{
this.offContext.arc(100, 75, 50, 0, 6.28) this.offContext.arc(100, 75, 50, 0, 6.28)
this.offContext.setLineDash([10,20]) this.offContext.setLineDash([10,20])
this.offContext.lineDashOffset = 10.0;
this.offContext.stroke(); this.offContext.stroke();
var image = this.offContext.transferToImageBitmap() var image = this.offContext.transferToImageBitmap()
this.context.transferFromImageBitmap(image) this.context.transferFromImageBitmap(image)
...@@ -465,27 +457,26 @@ struct LineDashOffset { ...@@ -465,27 +457,26 @@ struct LineDashOffset {
.height('100%') .height('100%')
} }
} }
```
```
![en-us_image_0000001212058506](figures/en-us_image_0000001212058506.png) ![en-us_image_0000001212058506](figures/en-us_image_0000001212058506.png)
### globalCompositeOperation ### globalCompositeOperation
| Name | Description | | Name | Description |
| ---------------- | ---------------------------------------- | | ---------------- | ------------------------ |
| source-over | Displays the new drawing above the existing drawing. This attribute is used by default. | | source-over | Displays the new drawing above the existing drawing. This attribute is used by default. |
| source-atop | Displays the new drawing on the top of the existing drawing. | | source-atop | Displays the new drawing on the top of the existing drawing. |
| source-in | Displays the new drawing inside the existing drawing. | | source-in | Displays the new drawing inside the existing drawing. |
| source-out | Displays the part of the new drawing that is outside of the existing drawing. | | source-out | Displays part of the new drawing that is outside of the existing drawing. |
| destination-over | Displays the existing drawing above the new drawing. | | destination-over | Displays the existing drawing above the new drawing. |
| destination-atop | Displays the existing drawing on the top of the new drawing. | | destination-atop | Displays the existing drawing on the top of the new drawing. |
| destination-in | Displays the existing drawing inside the new drawing. | | destination-in | Displays the existing drawing inside the new drawing. |
| destination-out | Displays the part of the existing drawing that is outside of the new drawing. | | destination-out | Displays the existing drawing outside the new drawing. |
| lighter | Displays both the new drawing and the existing drawing. | | lighter | Displays both the new and existing drawing. |
| copy | Displays the new drawing and neglects the existing drawing. | | copy | Displays the new drawing and neglects the existing drawing. |
| xor | Combines the new drawing and existing drawing using the XOR operation. | | xor | Combines the new drawing and existing drawing using the XOR operation.|
```ts ```ts
// xxx.ets // xxx.ets
...@@ -528,7 +519,6 @@ struct GlobalCompositeOperation { ...@@ -528,7 +519,6 @@ struct GlobalCompositeOperation {
### shadowBlur ### shadowBlur
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
...@@ -564,7 +554,6 @@ struct ShadowBlur { ...@@ -564,7 +554,6 @@ struct ShadowBlur {
### shadowColor ### shadowColor
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
...@@ -601,7 +590,6 @@ struct ShadowColor { ...@@ -601,7 +590,6 @@ struct ShadowColor {
### shadowOffsetX ### shadowOffsetX
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
...@@ -638,7 +626,6 @@ struct ShadowOffsetX { ...@@ -638,7 +626,6 @@ struct ShadowOffsetX {
### shadowOffsetY ### shadowOffsetY
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
...@@ -675,7 +662,6 @@ struct ShadowOffsetY { ...@@ -675,7 +662,6 @@ struct ShadowOffsetY {
### imageSmoothingEnabled ### imageSmoothingEnabled
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
...@@ -717,15 +703,16 @@ fillRect(x: number, y: number, w: number, h: number): void ...@@ -717,15 +703,16 @@ fillRect(x: number, y: number, w: number, h: number): void
Fills a rectangle on the canvas. Fills a rectangle on the canvas.
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ------ | ------ | --------- | ------------- | ---------------------------------------- |
| x | number | Yes | 0 | X-coordinate of the upper left corner of the rectangle. |
| y | number | Yes | 0 | Y-coordinate of the upper left corner of the rectangle. |
| width | number | Yes | 0 | Width of the rectangle. |
| height | number | Yes | 0 | Height of the rectangle. |
- Example | Name | Type | Mandatory | Default Value | Description |
| ------ | ------ | ---- | ---- | ------------- |
| x | number | Yes | 0 | X-coordinate of the upper left corner of the rectangle.|
| y | number | Yes | 0 | Y-coordinate of the upper left corner of the rectangle.|
| width | number | Yes | 0 | Width of the rectangle. |
| height | number | Yes | 0 | Height of the rectangle. |
**Example**
```ts ```ts
// xxx.ets // xxx.ets
...@@ -763,15 +750,16 @@ strokeRect(x: number, y: number, w: number, h: number): void ...@@ -763,15 +750,16 @@ strokeRect(x: number, y: number, w: number, h: number): void
Draws an outlined rectangle on the canvas. Draws an outlined rectangle on the canvas.
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ------ | ------ | --------- | ------------- | ---------------------------------------- | | Name | Type | Mandatory | Default Value | Description |
| x | number | Yes | 0 | X-coordinate of the upper left corner of the rectangle. | | ------ | ------ | ---- | ---- | ------------ |
| y | number | Yes | 0 | Y-coordinate of the upper left corner of the rectangle. | | x | number | Yes | 0 | X-coordinate of the upper left corner of the rectangle.|
| width | number | Yes | 0 | Width of the rectangle. | | y | number | Yes | 0 | Y-coordinate of the upper left corner of the rectangle.|
| height | number | Yes | 0 | Height of the rectangle. | | width | number | Yes | 0 | Width of the rectangle. |
| height | number | Yes | 0 | Height of the rectangle. |
- Example **Example**
```ts ```ts
// xxx.ets // xxx.ets
...@@ -808,15 +796,16 @@ clearRect(x: number, y: number, w: number, h: number): void ...@@ -808,15 +796,16 @@ clearRect(x: number, y: number, w: number, h: number): void
Clears the content in a rectangle on the canvas. Clears the content in a rectangle on the canvas.
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ------ | ------ | --------- | ------------- | ---------------------------------------- | | Name | Type | Mandatory | Default Value | Description |
| x | number | Yes | 0 | X-coordinate of the upper left corner of the rectangle. | | ------ | ------ | ---- | ---- | ------------- |
| y | number | Yes | 0 | Y-coordinate of the upper left corner of the rectangle. | | x | number | Yes | 0 | X-coordinate of the upper left corner of the rectangle.|
| width | number | Yes | 0 | Width of the rectangle. | | y | number | Yes | 0 | Y-coordinate of the upper left corner of the rectangle.|
| height | number | Yes | 0 | Height of the rectangle. | | width | number | Yes | 0 | Width of the rectangle. |
| height | number | Yes | 0 | Height of the rectangle. |
- Example **Example**
```ts ```ts
// xxx.ets // xxx.ets
...@@ -851,18 +840,20 @@ Clears the content in a rectangle on the canvas. ...@@ -851,18 +840,20 @@ Clears the content in a rectangle on the canvas.
### fillText ### fillText
fillText(text: string, x: number, y: number): void fillText(text: string, x: number, y: number, maxWidth?: number): void
Draws filled text on the canvas. Draws filled text on the canvas.
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ---- | ------ | --------- | ------------- | ---------------------------------------- |
| text | string | Yes | "" | Text to draw. |
| x | number | Yes | 0 | X-coordinate of the lower left corner of the text. |
| y | number | Yes | 0 | Y-coordinate of the lower left corner of the text. |
- Example | Name | Type | Mandatory | Default Value | Description |
| ---- | ------ | ---- | ---- | --------------- |
| text | string | Yes | "" | Text to draw. |
| x | number | Yes | 0 | X-coordinate of the lower left corner of the text.|
| y | number | Yes | 0 | Y-coordinate of the lower left corner of the text.|
| maxWidth | number | No | - | Maximum width allowed for the text.|
**Example**
```ts ```ts
// xxx.ets // xxx.ets
...@@ -900,14 +891,16 @@ strokeText(text: string, x: number, y: number): void ...@@ -900,14 +891,16 @@ strokeText(text: string, x: number, y: number): void
Draws a text stroke on the canvas. Draws a text stroke on the canvas.
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ---- | ------ | --------- | ------------- | ---------------------------------------- | | Name | Type | Mandatory | Default Value | Description |
| text | string | Yes | "" | Text to draw. | | ---- | ------ | ---- | ---- | --------------- |
| x | number | Yes | 0 | X-coordinate of the lower left corner of the text. | | text | string | Yes | "" | Text to draw. |
| y | number | Yes | 0 | Y-coordinate of the lower left corner of the text. | | x | number | Yes | 0 | X-coordinate of the lower left corner of the text.|
| y | number | Yes | 0 | Y-coordinate of the lower left corner of the text.|
| maxWidth | number | No | - | Maximum width of the text to be drawn.|
- Example **Example**
```ts ```ts
// xxx.ets // xxx.ets
...@@ -945,22 +938,37 @@ measureText(text: string): TextMetrics ...@@ -945,22 +938,37 @@ measureText(text: string): TextMetrics
Returns a **TextMetrics** object used to obtain the width of specified text. Returns a **TextMetrics** object used to obtain the width of specified text.
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ---- | ------ | --------- | ------------- | -------------------- | | Name | Type | Mandatory | Default Value | Description |
| text | string | Yes | "" | Text to be measured. | | ---- | ------ | ---- | ---- | ---------- |
| text | string | Yes | "" | Text to be measured.|
**Return value**
- Return value | Type | Description |
| Type | Description | | ----------- | ------- |
| ----------- | ----------------------- | | TextMetrics | **TextMetrics** object.|
| TextMetrics | **TextMetrics** object. |
- **TextMetrics** attributes **TextMetrics**
| Name | Type | Description |
| ----- | ------ | ------------------ |
| width | number | Width of the text. |
- Example | Name | Type | Description |
| ----- | ------ | ------- |
| width | number | Width of the text.|
| height | number | Height of the text.|
| actualBoundingBoxAscent | number | Distance from the horizontal line specified by the **CanvasRenderingContext2D.textBaseline** attribute to the top of the bounding rectangle used to render the text. The current value is **0**.|
| actualBoundingBoxDescent | number | Distance from the horizontal line specified by the **CanvasRenderingContext2D.textBaseline** attribute to the bottom of the bounding rectangle used to render the text. The current value is **0**.|
| actualBoundingBoxLeft | number | Distance parallel to the baseline from the alignment point determined by the **CanvasRenderingContext2D.textAlign** attribute to the left side of the bounding rectangle of the text. The current value is **0**.|
| actualBoundingBoxRight | number | Distance parallel to the baseline from the alignment point determined by the **CanvasRenderingContext2D.textAlign** attribute to the right side of the bounding rectangle of the text. The current value is **0**.|
| alphabeticBaseline | number | Distance from the horizontal line specified by the **CanvasRenderingContext2D.textBaseline** attribute to the alphabetic baseline of the line box. The current value is **0**.|
| emHeightAscent | number | Distance from the horizontal line specified by the **CanvasRenderingContext2D.textBaseline** attribute to the top of the em square in the line box. The current value is **0**.|
| emHeightDescent | number | Distance from the horizontal line specified by the **CanvasRenderingContext2D.textBaseline** attribute to the bottom of the em square in the line box. The current value is **0**.|
| fontBoundingBoxAscent | number | Distance from the horizontal line specified by the **CanvasRenderingContext2D.textBaseline** attribute to the top of the highest bounding rectangle of all the fonts used to render the text. The current value is **0**.|
| fontBoundingBoxDescent | number | Distance from the horizontal line specified by the **CanvasRenderingContext2D.textBaseline** attribute to the bottom of the bounding rectangle of all the fonts used to render the text. The current value is **0**.|
| hangingBaseline | number | Distance from the horizontal line specified by the **CanvasRenderingContext2D.textBaseline** attribute to the hanging baseline of the line box. The current value is **0**.|
| ideographicBaseline | number | Distance from the horizontal line indicated by the **CanvasRenderingContext2D.textBaseline** attribute to the ideographic baseline of the line box. The current value is **0**.|
**Example**
```ts ```ts
// xxx.ets // xxx.ets
...@@ -999,12 +1007,13 @@ stroke(path?: Path2D): void ...@@ -999,12 +1007,13 @@ stroke(path?: Path2D): void
Strokes a path. Strokes a path.
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ---- | ---------------------------------------- | --------- | ------------- | -------------------------- | | Name | Type | Mandatory | Default Value | Description |
| path | [Path2D](ts-components-canvas-path2d.md) | No | null | A **Path2D** path to draw. | | ---- | ---------------------------------------- | ---- | ---- | ------------ |
| path | [Path2D](ts-components-canvas-path2d.md) | No | null | A **Path2D** path to draw.|
- Example **Example**
```ts ```ts
// xxx.ets // xxx.ets
...@@ -1044,7 +1053,7 @@ beginPath(): void ...@@ -1044,7 +1053,7 @@ beginPath(): void
Creates a drawing path. Creates a drawing path.
- Example **Example**
```ts ```ts
// xxx.ets // xxx.ets
...@@ -1086,13 +1095,14 @@ moveTo(x: number, y: number): void ...@@ -1086,13 +1095,14 @@ moveTo(x: number, y: number): void
Moves a drawing path to a target position on the canvas. Moves a drawing path to a target position on the canvas.
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ---- | ------ | --------- | ------------- | ------------------------------------ |
| x | number | Yes | 0 | X-coordinate of the target position. |
| y | number | Yes | 0 | Y-coordinate of the target position. |
- Example | Name | Type | Mandatory | Default Value | Description |
| ---- | ------ | ---- | ---- | --------- |
| x | number | Yes | 0 | X-coordinate of the target position.|
| y | number | Yes | 0 | Y-coordinate of the target position.|
**Example**
```ts ```ts
// xxx.ets // xxx.ets
...@@ -1132,13 +1142,14 @@ lineTo(x: number, y: number): void ...@@ -1132,13 +1142,14 @@ lineTo(x: number, y: number): void
Connects the current point to a target position using a straight line. Connects the current point to a target position using a straight line.
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ---- | ------ | --------- | ------------- | ------------------------------------ | | Name | Type | Mandatory | Default Value | Description |
| x | number | Yes | 0 | X-coordinate of the target position. | | ---- | ------ | ---- | ---- | --------- |
| y | number | Yes | 0 | Y-coordinate of the target position. | | x | number | Yes | 0 | X-coordinate of the target position.|
| y | number | Yes | 0 | Y-coordinate of the target position.|
- Example **Example**
```ts ```ts
// xxx.ets // xxx.ets
...@@ -1178,7 +1189,7 @@ closePath(): void ...@@ -1178,7 +1189,7 @@ closePath(): void
Draws a closed path. Draws a closed path.
- Example **Example**
```ts ```ts
// xxx.ets // xxx.ets
...@@ -1216,17 +1227,24 @@ Draws a closed path. ...@@ -1216,17 +1227,24 @@ Draws a closed path.
### createPattern ### createPattern
createPattern(image: ImageBitmap, repetition: string): CanvasPattern createPattern(image: ImageBitmap, repetition: string | null): CanvasPattern | null
Creates a pattern for image filling based on a specified source image and repetition mode. Creates a pattern for image filling based on a specified source image and repetition mode.
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ---------- | ---------------------------------------- | --------- | ------------- | ---------------------------------------- |
| image | [ImageBitmap](ts-components-canvas-imagebitmap.md) | Yes | null | Source image. For details, see ImageBitmap. |
| repetition | string | Yes | "" | Repetition mode. The value can be **'repeat'**, **'repeat-x'**, **'repeat-y'**, or **'no-repeat'**. |
- Example | Name | Type | Mandatory | Default Value | Description |
| ---------- | ---------------------------------------- | ---- | ---- | ---------------------------------------- |
| image | [ImageBitmap](ts-components-canvas-imagebitmap.md) | Yes | null | Source image. For details, see **ImageBitmap**. |
| repetition | string | Yes | "" | Repetition mode. The value can be **"repeat"**, **"repeat-x"**, **"repeat-y"**, or **"no-repeat"**.|
**Return value**
| Type | Description |
| ---------- | ---------------------------------------- |
| [CanvasPattern](#canvaspattern) | Created pattern for image filling based on a specified source image and repetition mode.|
**Example**
```ts ```ts
// xxx.ets // xxx.ets
...@@ -1266,17 +1284,18 @@ bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number, ...@@ -1266,17 +1284,18 @@ bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number,
Draws a cubic bezier curve on the canvas. Draws a cubic bezier curve on the canvas.
- Name **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ---- | ------ | --------- | ------------- | ---------------------------------------- | | Name | Type | Mandatory | Default Value | Description |
| cp1x | number | Yes | 0 | X-coordinate of the first parameter of the bezier curve. | | ---- | ------ | ---- | ---- | -------------- |
| cp1y | number | Yes | 0 | Y-coordinate of the first parameter of the bezier curve. | | cp1x | number | Yes | 0 | X-coordinate of the first parameter of the bezier curve.|
| cp2x | number | Yes | 0 | X-coordinate of the second parameter of the bezier curve. | | cp1y | number | Yes | 0 | Y-coordinate of the first parameter of the bezier curve.|
| cp2y | number | Yes | 0 | Y-coordinate of the second parameter of the bezier curve. | | cp2x | number | Yes | 0 | X-coordinate of the second parameter of the bezier curve.|
| x | number | Yes | 0 | X-coordinate of the end point on the bezier curve. | | cp2y | number | Yes | 0 | Y-coordinate of the second parameter of the bezier curve.|
| y | number | Yes | 0 | Y-coordinate of the end point on the bezier curve. | | x | number | Yes | 0 | X-coordinate of the end point on the bezier curve. |
| y | number | Yes | 0 | Y-coordinate of the end point on the bezier curve. |
- Example **Example**
```ts ```ts
// xxx.ets // xxx.ets
...@@ -1316,15 +1335,16 @@ quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void ...@@ -1316,15 +1335,16 @@ quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void
Draws a quadratic curve on the canvas. Draws a quadratic curve on the canvas.
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ---- | ------ | --------- | ------------- | ---------------------------------------- |
| cpx | number | Yes | 0 | X-coordinate of the bezier curve parameter. |
| cpy | number | Yes | 0 | Y-coordinate of the bezier curve parameter. |
| x | number | Yes | 0 | X-coordinate of the end point on the bezier curve. |
| y | number | Yes | 0 | Y-coordinate of the end point on the bezier curve. |
- Example | Name | Type | Mandatory | Default Value | Description |
| ---- | ------ | ---- | ---- | ----------- |
| cpx | number | Yes | 0 | X-coordinate of the bezier curve parameter.|
| cpy | number | Yes | 0 | Y-coordinate of the bezier curve parameter.|
| x | number | Yes | 0 | X-coordinate of the end point on the bezier curve.|
| y | number | Yes | 0 | Y-coordinate of the end point on the bezier curve.|
**Example**
```ts ```ts
// xxx.ets // xxx.ets
...@@ -1360,21 +1380,22 @@ Draws a quadratic curve on the canvas. ...@@ -1360,21 +1380,22 @@ Draws a quadratic curve on the canvas.
### arc ### arc
arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, anticlockwise?: boolean): void arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, counterclockwise?: boolean): void
Draws an arc on the canvas. Draws an arc on the canvas.
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ------------- | ------- | --------- | ------------- | ---------------------------------------- | | Name | Type | Mandatory | Default Value | Description |
| x | number | Yes | 0 | X-coordinate of the center point of the arc. | | ------------- | ------- | ---- | ----- | ---------- |
| y | number | Yes | 0 | Y-coordinate of the center point of the arc. | | x | number | Yes | 0 | X-coordinate of the center point of the arc.|
| radius | number | Yes | 0 | Radius of the arc. | | y | number | Yes | 0 | Y-coordinate of the center point of the arc.|
| startAngle | number | Yes | 0 | Start radian of the arc. | | radius | number | Yes | 0 | Radius of the arc. |
| endAngle | number | Yes | 0 | End radian of the arc. | | startAngle | number | Yes | 0 | Start radian of the arc. |
| anticlockwise | boolean | No | false | Whether to draw the arc counterclockwise. | | endAngle | number | Yes | 0 | End radian of the arc. |
| counterclockwise | boolean | No | false | Whether to draw the arc counterclockwise.|
- Example **Example**
```ts ```ts
// xxx.ets // xxx.ets
...@@ -1413,16 +1434,17 @@ arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void ...@@ -1413,16 +1434,17 @@ arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void
Draws an arc based on the radius and points on the arc. Draws an arc based on the radius and points on the arc.
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ------ | ------ | --------- | ------------- | ---------------------------------------- | | Name | Type | Mandatory | Default Value | Description |
| x1 | number | Yes | 0 | X-coordinate of the first point on the arc. | | ------ | ------ | ---- | ---- | --------------- |
| y1 | number | Yes | 0 | Y-coordinate of the first point on the arc. | | x1 | number | Yes | 0 | X-coordinate of the first point on the arc.|
| x2 | number | Yes | 0 | X-coordinate of the second point on the arc. | | y1 | number | Yes | 0 | Y-coordinate of the first point on the arc.|
| y2 | number | Yes | 0 | Y-coordinate of the second point on the arc. | | x2 | number | Yes | 0 | X-coordinate of the second point on the arc.|
| radius | number | Yes | 0 | Radius of the arc. | | y2 | number | Yes | 0 | Y-coordinate of the second point on the arc.|
| radius | number | Yes | 0 | Radius of the arc. |
- Example **Example**
```ts ```ts
// xxx.ets // xxx.ets
...@@ -1457,24 +1479,24 @@ Draws an arc based on the radius and points on the arc. ...@@ -1457,24 +1479,24 @@ Draws an arc based on the radius and points on the arc.
### ellipse ### ellipse
ellipse(x: number, y: number, radiusX: number, radiusY: number, rotation: number, startAngle: number, endAngle: number, anticlockwise?: boolean): void ellipse(x: number, y: number, radiusX: number, radiusY: number, rotation: number, startAngle: number, endAngle: number, counterclockwise?: boolean): void
Draws an ellipse in the specified rectangular region. Draws an ellipse in the specified rectangular region on the canvas.
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ------------- | ------- | --------- | ------------- | ---------------------------------------- |
| x | number | Yes | 0 | X-coordinate of the ellipse center. |
| y | number | Yes | 0 | Y-coordinate of the ellipse center. |
| radiusX | number | Yes | 0 | Ellipse radius on the x-axis. |
| radiusY | number | Yes | 0 | Ellipse radius on the y-axis. |
| rotation | number | Yes | 0 | Rotation angle of the ellipse, in radians. |
| startAngle | number | Yes | 0 | Angle of the start point for drawing the ellipse, in radians. |
| endAngle | number | Yes | 0 | Angle of the end point for drawing the ellipse, in radians. |
| anticlockwise | boolean | No | false | Whether to draw the ellipse in the counterclockwise direction. |
- Example | Name | Type | Mandatory | Default Value | Description |
| ------------- | ------- | ---- | ----- | ----------------- |
| x | number | Yes | 0 | X-coordinate of the ellipse center. |
| y | number | Yes | 0 | Y-coordinate of the ellipse center. |
| radiusX | number | Yes | 0 | Ellipse radius on the x-axis. |
| radiusY | number | Yes | 0 | Ellipse radius on the y-axis. |
| rotation | number | Yes | 0 | Rotation angle of the ellipse. The unit is radian. |
| startAngle | number | Yes | 0 | Angle of the start point for drawing the ellipse. The unit is radian.|
| endAngle | number | Yes | 0 | Angle of the end point for drawing the ellipse. The unit is radian.|
| counterclockwise | boolean | No | false | Whether to draw the ellipse in the counterclockwise direction. |
**Example**
```ts ```ts
// xxx.ets // xxx.ets
...@@ -1509,19 +1531,20 @@ Draws an ellipse in the specified rectangular region. ...@@ -1509,19 +1531,20 @@ Draws an ellipse in the specified rectangular region.
### rect ### rect
rect(x: number, y: number, width: number, height: number): void rect(x: number, y: number, w: number, h: number): void
Creates a rectangle. Creates a rectangle on the canvas.
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ------ | ------ | --------- | ------------- | ---------------------------------------- |
| x | number | Yes | 0 | X-coordinate of the upper left corner of the rectangle. |
| y | number | Yes | 0 | Y-coordinate of the upper left corner of the rectangle. |
| width | number | Yes | 0 | Width of the rectangle. |
| height | number | Yes | 0 | Height of the rectangle. |
- Example | Name | Type | Mandatory | Default Value | Description |
| ------ | ------ | ---- | ---- | ------------- |
| x | number | Yes | 0 | X-coordinate of the upper left corner of the rectangle.|
| y | number | Yes | 0 | Y-coordinate of the upper left corner of the rectangle.|
| w | number | Yes | 0 | Width of the rectangle. |
| h | number | Yes | 0 | Height of the rectangle. |
**Example**
```ts ```ts
// xxx.ets // xxx.ets
...@@ -1557,9 +1580,9 @@ Creates a rectangle. ...@@ -1557,9 +1580,9 @@ Creates a rectangle.
fill(): void fill(): void
Fills the area inside a closed path. Fills the area inside a closed path on the canvas.
- Example **Example**
```ts ```ts
// xxx.ets // xxx.ets
...@@ -1597,7 +1620,7 @@ clip(): void ...@@ -1597,7 +1620,7 @@ clip(): void
Sets the current path to a clipping path. Sets the current path to a clipping path.
- Example **Example**
```ts ```ts
// xxx.ets // xxx.ets
...@@ -1634,16 +1657,17 @@ Sets the current path to a clipping path. ...@@ -1634,16 +1657,17 @@ Sets the current path to a clipping path.
### rotate ### rotate
rotate(rotate: number): void rotate(angle: number): void
Rotates a canvas clockwise around its coordinate axes. Rotates a canvas clockwise around its coordinate axes.
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ------ | ------ | --------- | ------------- | ---------------------------------------- | | Name | Type | Mandatory | Default Value | Description |
| rotate | number | Yes | 0 | Clockwise rotation angle. You can use **Math.PI / 180** to convert the angle to a radian. | | ------ | ------ | ---- | ---- | ---------------------------------------- |
| angle | number | Yes | 0 | Clockwise rotation angle. You can use **Math.PI / 180** to convert the angle to a radian.|
- Example **Example**
```ts ```ts
// xxx.ets // xxx.ets
...@@ -1679,15 +1703,16 @@ Rotates a canvas clockwise around its coordinate axes. ...@@ -1679,15 +1703,16 @@ Rotates a canvas clockwise around its coordinate axes.
scale(x: number, y: number): void scale(x: number, y: number): void
Scales a canvas based on scale factors. Scales the canvas based on scale factors.
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ---- | ------ | --------- | ------------- | ------------------------ |
| x | number | Yes | 0 | Horizontal scale factor. |
| y | number | Yes | 0 | Vertical scale factor. |
- Example | Name | Type | Mandatory | Default Value | Description |
| ---- | ------ | ---- | ---- | ----------- |
| x | number | Yes | 0 | Horizontal scale factor.|
| y | number | Yes | 0 | Vertical scale factor.|
**Example**
```ts ```ts
// xxx.ets // xxx.ets
...@@ -1722,28 +1747,30 @@ Scales a canvas based on scale factors. ...@@ -1722,28 +1747,30 @@ Scales a canvas based on scale factors.
### transform ### transform
transform(scaleX: number, skewX: number, skewY: number, scaleY: number, translateX: number, translateY: number): void transform(a: number, b: number, c: number, d: number, e: number, f: number): void
Defines a transformation matrix. To transform a graph, you only need to set parameters of the matrix. The coordinates of the graph are multiplied by the matrix values to obtain new coordinates of the transformed graph. You can use the matrix to implement multiple transform effects. Defines a transformation matrix. To transform a graph, you only need to set parameters of the matrix. The coordinates of the graph are multiplied by the matrix values to obtain new coordinates of the transformed graph. You can use the matrix to implement multiple transform effects.
> **NOTE** > **NOTE**
>
> The following formulas calculate coordinates of the transformed graph. **x** and **y** represent coordinates before transformation, and **x'** and **y'** represent coordinates after transformation. > The following formulas calculate coordinates of the transformed graph. **x** and **y** represent coordinates before transformation, and **x'** and **y'** represent coordinates after transformation.
> >
> - x' = scaleX \* x + skewY \* y + translateX > - x' = scaleX \* x + skewY \* y + translateX
> >
> - y' = skewX \* x + scaleY \* y + translateY > - y' = skewX \* x + scaleY \* y + translateY
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ---------- | ------ | --------- | ------------- | ------------------- |
| scaleX | number | Yes | 0 | X-axis scale. |
| skewX | number | Yes | 0 | X-axis skew. |
| skewY | number | Yes | 0 | Y-axis skew. |
| scaleY | number | Yes | 0 | Y-axis scale. |
| translateX | number | Yes | 0 | X-axis translation. |
| translateY | number | Yes | 0 | Y-axis translation. |
- Example | Name | Type | Mandatory | Default Value | Description |
| ---------- | ------ | ---- | ---- | -------- |
| a | number | Yes | 0 |X-axis scale.|
| b | number | Yes | 0 |X-axis skew.|
| c | number | Yes | 0 |Y-axis skew.|
| d | number | Yes | 0 |Y-axis scale.|
| e | number | Yes | 0 |X-axis translation.|
| f | number | Yes | 0 |Y-axis translation.|
**Example**
```ts ```ts
// xxx.ets // xxx.ets
...@@ -1783,21 +1810,22 @@ Defines a transformation matrix. To transform a graph, you only need to set para ...@@ -1783,21 +1810,22 @@ Defines a transformation matrix. To transform a graph, you only need to set para
### setTransform ### setTransform
setTransform(scaleX: number, skewX: number, skewY: number, scale: number, translateX: number, translateY: number): void setTransform(a: number, b: number, c: number, d: number, e: number, f: number): void
Resets the existing transformation matrix and creates a new transformation matrix by using the same parameters as the **transform()** function. Resets the existing transformation matrix and creates a new transformation matrix by using the same parameters as the **transform()** function.
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ---------- | ------ | --------- | ------------- | ------------------- | | Parameters | Type | Mandatory | Default Value | Description |
| scaleX | number | Yes | 0 | X-axis scale. | | ---------- | ------ | ---- | ---- | -------- |
| skewX | number | Yes | 0 | X-axis skew. | | a | number | Yes | 0 |X-axis scale.|
| skewY | number | Yes | 0 | Y-axis skew. | | b | number | Yes | 0 |X-axis skew.|
| scaleY | number | Yes | 0 | Y-axis scale. | | c | number | Yes | 0 |Y-axis skew.|
| translateX | number | Yes | 0 | X-axis translation. | | d | number | Yes | 0 |Y-axis scale.|
| translateY | number | Yes | 0 | Y-axis translation. | | e | number | Yes | 0 |X-axis translation.|
| f | number | Yes | 0 |Y-axis translation.|
- Example **Example**
```ts ```ts
// xxx.ets // xxx.ets
...@@ -1829,7 +1857,7 @@ Resets the existing transformation matrix and creates a new transformation matri ...@@ -1829,7 +1857,7 @@ Resets the existing transformation matrix and creates a new transformation matri
} }
``` ```
![en-us_image_0000001211898518](figures/en-us_image_0000001211898518.png) ![zh-cn_image_0000001193872526](figures/zh-cn_image_0000001193872526.png)
### translate ### translate
...@@ -1838,13 +1866,14 @@ translate(x: number, y: number): void ...@@ -1838,13 +1866,14 @@ translate(x: number, y: number): void
Moves the origin of the coordinate system. Moves the origin of the coordinate system.
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ---- | ------ | --------- | ------------- | ------------------- | | Parameters | Type | Mandatory | Default Value | Description |
| x | number | Yes | 0 | X-axis translation. | | ---- | ------ | ---- | ---- | -------- |
| y | number | Yes | 0 | Y-axis translation. | | x | number | Yes | 0 | X-axis translation.|
| y | number | Yes | 0 | Y-axis translation.|
- Example **Example**
```ts ```ts
// xxx.ets // xxx.ets
...@@ -1881,27 +1910,28 @@ Moves the origin of the coordinate system. ...@@ -1881,27 +1910,28 @@ Moves the origin of the coordinate system.
drawImage(image: ImageBitmap | PixelMap, dx: number, dy: number): void drawImage(image: ImageBitmap | PixelMap, dx: number, dy: number): void
drawImage(image: ImageBitmap | PixelMap, dx: number, dy: number, dWidth: number, dHeight: number): void drawImage(image: ImageBitmap | PixelMap, dx: number, dy: number, dw: number, dh: number): void
drawImage(image: ImageBitmap | PixelMap, sx: number, sy: number, sWidth: number, sHeight: number, dx: number, dy: number, dWidth: number, dHeight: number):void drawImage(image: ImageBitmap | PixelMap, sx: number, sy: number, sw: number, sh: number, dx: number, dy: number, dw: number, dh: number):void
Draws an image. Draws an image on the canvas.
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ------- | ---------------------------------------- | --------- | ------------- | ---------------------------------------- |
| image | [ImageBitmap](ts-components-canvas-imagebitmap.md) or [PixelMap](../apis/js-apis-image.md#pixelmap7) | Yes | null | Image resource. For details, see ImageBitmap. |
| sx | number | No | 0 | X-coordinate of the upper left corner of the rectangle used to crop the source image. |
| sy | number | No | 0 | Y-coordinate of the upper left corner of the rectangle used to crop the source image. |
| sWidth | number | No | 0 | Target width to crop the source image. |
| sHeight | number | No | 0 | Target height to crop the source image. |
| dx | number | Yes | 0 | X-coordinate of the upper left corner of the drawing area on the canvas. |
| dy | number | Yes | 0 | Y-coordinate of the upper left corner of the drawing area on the canvas. |
| dWidth | number | No | 0 | Width of the drawing area. |
| dHeight | number | No | 0 | Height of the drawing area. |
| Name | Type | Mandatory | Default Value | Description |
| ------- | ---------------------------------------- | ---- | ---- | -------------------- |
| image | [ImageBitmap](ts-components-canvas-imagebitmap.md) or [PixelMap](../apis/js-apis-image.md#pixelmap7)| Yes | null | Image resource. For details, see **ImageBitmap** or **PixelMap**.|
| sx | number | No | 0 | X-coordinate of the upper left corner of the rectangle used to crop the source image.|
| sy | number | No | 0 | Y-coordinate of the upper left corner of the rectangle used to crop the source image.|
| sw | number | No | 0 | Target width to crop the source image. |
| sh | number | No | 0 | Target height to crop the source image. |
| dx | number | Yes | 0 | X-coordinate of the upper left corner of the drawing area on the canvas. |
| dy | number | Yes | 0 | Y-coordinate of the upper left corner of the drawing area on the canvas.|
| dw | number | No | 0 | Width of the drawing area. |
| dh | number | No | 0 | Height of the drawing area. |
- Example
**Example**
```ts ```ts
// xxx.ets // xxx.ets
...@@ -1935,74 +1965,101 @@ Draws an image. ...@@ -1935,74 +1965,101 @@ Draws an image.
### createImageData ### createImageData
createImageData(width: number, height: number): Object createImageData(sw: number, sh: number): ImageData
Creates an **ImageData** object based on the width and height. For details, see [ImageData](ts-components-canvas-imagebitmap.md).
Creates an **ImageData** object based on the specified width and height. For details, see [ImageData](ts-components-canvas-imagebitmap.md). **Parameters**
- Parameters | Name | Type | Mandatory | Default Value | Description |
| Name | Type | Mandatory | Default Value | Description | | ------ | ------ | ---- | ---- | ------------- |
| ------ | ------ | --------- | ------------- | ----------------------------------- | | sw | number | Yes | 0 | Width of the **ImageData** object.|
| width | number | Yes | 0 | Width of the **ImageData** object. | | sh | number | Yes | 0 | Height of the **ImageData** object.|
| height | number | Yes | 0 | Height of the **ImageData** object. |
### createImageData ### createImageData
createImageData(imageData: ImageData): Object createImageData(imageData: ImageData): ImageData
Creates an **ImageData** object based on the given existing **ImageData** object. For details, see [ImageData](ts-components-canvas-imagebitmap.md).
**Parameters**
Creates an **ImageData** object by copying an existing **ImageData** object. For details, see [ImageData](ts-components-canvas-imagebitmap.md). | Name | Type | Mandatory | Default Value | Description |
| --------- | ---------------------------------------- | ---- | ---- | ---------------- |
| imagedata | [ImageData](ts-components-canvas-imagebitmap.md) | Yes | null | **ImageData** object to copy.|
- Parameters **Return value**
| Name | Type | Mandatory | Default Value | Description |
| --------- | ---------------------------------------- | --------- | ------------- | ----------------------------- | | Type | Description |
| imagedata | [ImageData](ts-components-canvas-imagebitmap.md) | Yes | null | **ImageData** object to copy. | | ---------- | ---------------------------------------- |
| [ImageData](ts-components-canvas-imagebitmap.md) | New **ImageData** object.|
### getPixelMap ### getPixelMap
getPixelMap(sx: number, sy: number, sw: number, sh: number): PixelMap getPixelMap(sx: number, sy: number, sw: number, sh: number): PixelMap
Obtains the **[PixelMap](../apis/js-apis-image.md#pixelmap7)** object created with the pixels within the specified area on the canvas. Obtains the **[PixelMap](../apis/js-apis-image.md#pixelmap7)** object created with the pixels within the specified area on the canvas.
- Parameters
| Name | Type | Mandatory | Default Value | Description | **Parameters**
| -------- | -------- | -------- | -------- | -------- |
| sx | number | Yes | 0 | X-coordinate of the upper left corner of the output area. | | Name| Type| Mandatory| Default Value| Description|
| sy | number | Yes | 0 | Y-coordinate of the upper left corner of the output area. | | -------- | -------- | -------- | -------- | -------- |
| sw | number | Yes | 0 | Width of the output area. | | sx | number | Yes| 0 | X-coordinate of the upper left corner of the output area.|
| sh | number | Yes | 0 | Height of the output area. | | sy | number | Yes| 0 | Y-coordinate of the upper left corner of the output area.|
| sw | number | Yes| 0 | Width of the output area.|
| sh | number | Yes| 0 | Height of the output area.|
**Return value**
| Type | Description |
| ---------- | ---------------------------------------- |
| [PixelMap](../apis/js-apis-image.md#pixelmap7) | **PixelMap** object.|
### getImageData ### getImageData
getImageData(sx: number, sy: number, sw: number, sh: number): Object getImageData(sx: number, sy: number, sw: number, sh: number): ImageData
Obtains the **[ImageData](ts-components-canvas-imagebitmap.md)** object created with the pixels within the specified area on the canvas. Obtains the **[ImageData](ts-components-canvas-imagebitmap.md)** object created with the pixels within the specified area on the canvas.
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ---- | ------ | --------- | ------------- | ---------------------------------------- | | Parameters | Type | Mandatory | Default Value | Description |
| sx | number | Yes | 0 | X-coordinate of the upper left corner of the output area. | | ---- | ------ | ---- | ---- | --------------- |
| sy | number | Yes | 0 | Y-coordinate of the upper left corner of the output area. | | sx | number | Yes | 0 | X-coordinate of the upper left corner of the output area.|
| sw | number | Yes | 0 | Width of the output area. | | sy | number | Yes | 0 | Y-coordinate of the upper left corner of the output area.|
| sh | number | Yes | 0 | Height of the output area. | | sw | number | Yes | 0 | Width of the output area. |
| sh | number | Yes | 0 | Height of the output area. |
**Return value**
| Type | Description |
| ---------- | ---------------------------------------- |
| [ImageData](ts-components-canvas-imagebitmap.md) | New **ImageData** object.|
### putImageData ### putImageData
putImageData(imageData: Object, dx: number, dy: number, dirtyX?: number, dirtyY?: number, dirtyWidth?: number, dirtyHeight?: number): void putImageData(imageData: Object, dx: number, dy: number): void
putImageData(imageData: Object, dx: number, dy: number, dirtyX: number, dirtyY: number, dirtyWidth?: number, dirtyHeight: number): void
Puts the [ImageData](ts-components-canvas-imagebitmap.md) onto a rectangular area on the canvas. Puts the [ImageData](ts-components-canvas-imagebitmap.md) onto a rectangular area on the canvas.
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ----------- | ------ | --------- | ---------------------------------- | ---------------------------------------- | | Parameters | Type | Mandatory | Default Value | Description |
| imagedata | Object | Yes | null | **ImageData** object with pixels to put onto the canvas. | | ----------- | ------ | ---- | ------------ | ----------------------------- |
| dx | number | Yes | 0 | X-axis offset of the rectangular area on the canvas. | | imagedata | Object | Yes | null | **ImageData** object with pixels to put onto the canvas. |
| dy | number | Yes | 0 | Y-axis offset of the rectangular area on the canvas. | | dx | number | Yes | 0 | X-axis offset of the rectangular area on the canvas. |
| dirtyX | number | No | 0 | X-axis offset of the upper left corner of the rectangular area relative to that of the source image. | | dy | number | Yes | 0 | Y-axis offset of the rectangular area on the canvas. |
| dirtyY | number | No | 0 | Y-axis offset of the upper left corner of the rectangular area relative to that of the source image. | | dirtyX | number | No | 0 | X-axis offset of the upper left corner of the rectangular area relative to that of the source image.|
| dirtyWidth | number | No | Width of the **ImageData** object | Width of the rectangular area to crop the source image. | | dirtyY | number | No | 0 | Y-axis offset of the upper left corner of the rectangular area relative to that of the source image.|
| dirtyHeight | number | No | Height of the **ImageData** object | Height of the rectangular area to crop the source image. | | dirtyWidth | number | No | Width of the **ImageData** object| Width of the rectangular area to crop the source image. |
| dirtyHeight | number | No | Height of the **ImageData** object| Height of the rectangular area to crop the source image. |
- Example **Example**
```ts ```ts
// xxx.ets // xxx.ets
...@@ -2039,6 +2096,225 @@ Puts the [ImageData](ts-components-canvas-imagebitmap.md) onto a rectangular are ...@@ -2039,6 +2096,225 @@ Puts the [ImageData](ts-components-canvas-imagebitmap.md) onto a rectangular are
![en-us_image_0000001212058496](figures/en-us_image_0000001212058496.png) ![en-us_image_0000001212058496](figures/en-us_image_0000001212058496.png)
### setLineDash
setLineDash(segments: number[]): void
Sets the dash line style.
**Parameters**
| Parameter | Type | Description |
| -------- | ----- | -------------------- |
| segments | number[] | An array of numbers that specify distances to alternately draw a line and a gap.|
**Example**
```ts
@Entry
@Component
struct SetLineDash {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings)
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context)
.width('100%')
.height('100%')
.backgroundColor('#ffff00')
.onReady(() =>{
this.offContext.arc(100, 75, 50, 0, 6.28)
this.offContext.setLineDash([10,20])
this.offContext.stroke();
var image = this.offContext.transferToImageBitmap()
this.context.transferFromImageBitmap(image)
})
}
.width('100%')
.height('100%')
}
}
```
![zh-cn_image_000000127777772](figures/zh-cn_image_000000127777772.png)
### getLineDash
getLineDash(): number[]
Obtains the dash line style.
**Return value**
| Type | Description |
| ----- | ------------------------ |
| number[] | An array describing the interval of alternate line segments and length of spacing.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct GetLineDash {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings)
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context)
.width('100%')
.height('100%')
.backgroundColor('#ffff00')
.onReady(() =>{
var grad = this.context.createLinearGradient(50,0, 300,100)
this.offContext.arc(100, 75, 50, 0, 6.28)
this.offContext.setLineDash([10,20])
this.offContext.stroke();
let res = this.offContext.getLineDash()
var image = this.offContext.transferToImageBitmap()
this.context.transferFromImageBitmap(image)
})
}
.width('100%')
.height('100%')
}
}
```
### transferFromImageBitmap
transferFromImageBitmap(bitmap: ImageBitmap): void
Displays the specified **ImageBitmap** object.
**Parameters**
| Parameters | Type | Description |
| ------ | ----------- | ------------------ |
| bitmap | [ImageData](ts-components-canvas-imagebitmap.md) | **ImageBitmap** object to display.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct GetLineDash {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings)
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context)
.width('100%')
.height('100%')
.backgroundColor('#ffff00')
.onReady(() =>{
this.offContext.fillRect(0, 0, 200, 200)
var image = this.offContext.transferToImageBitmap()
this.context.transferFromImageBitmap(image)
})
}
.width('100%')
.height('100%')
}
}
```
![zh-cn_image_000000127777773](figures/zh-cn_image_000000127777773.png)
### toDataURL
toDataURL(type?: string, quality?: number): string
Generates a URL containing image display information.
**Parameters**
| Name | Type | Mandatory | Description |
| ------- | ------ | ---- | ---------------------------------------- |
| type | string | No | Image format. The default value is **image/png**. |
| quality | number | No | Image quality, which ranges from 0 to 1, when the image format is **image/jpeg** or **image/webp**. If the set value is beyond the value range, the default value **0.92** is used.|
**Return value**
| Type | Description |
| ------ | --------- |
| string | Image URL.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct ToDataURL {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings)
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context)
.width('100%')
.height('100%')
.backgroundColor('#ffff00')
.onReady(() =>{
var dataURL = this.offContext.toDataURL();
})
}
.width('100%')
.height('100%')
}
}
```
### transferToImageBitmap
transferToImageBitmap(): ImageBitmap
Creates an **ImageBitmap** object on the most recently rendered image of the **OffscreenCanvas**.
**Return value**
| Type | Description |
| ---------------------------------------- | --------------- |
| [ImageData](ts-components-canvas-imagebitmap.md)| Pixel data rendered on the **OffscreenCanvas**.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct CanvasExample {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings)
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context)
.width('100%')
.height('100%')
.backgroundColor('#ffff00')
.onReady(() =>{
this.offContext.restore()
var image = this.offContext.transferToImageBitmap()
this.context.transferFromImageBitmap(image)
})
}
.width('100%')
.height('100%')
}
}
```
### restore ### restore
...@@ -2046,7 +2322,7 @@ restore(): void ...@@ -2046,7 +2322,7 @@ restore(): void
Restores the saved drawing context. Restores the saved drawing context.
- Example **Example**
```ts ```ts
// xxx.ets // xxx.ets
...@@ -2081,7 +2357,7 @@ save(): void ...@@ -2081,7 +2357,7 @@ save(): void
Saves the current drawing context. Saves the current drawing context.
- Example **Example**
```ts ```ts
// xxx.ets // xxx.ets
...@@ -2116,15 +2392,16 @@ createLinearGradient(x0: number, y0: number, x1: number, y1: number): void ...@@ -2116,15 +2392,16 @@ createLinearGradient(x0: number, y0: number, x1: number, y1: number): void
Creates a linear gradient. Creates a linear gradient.
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ---- | ------ | --------- | ------------- | -------------------------------- | | Name | Type | Mandatory | Default Value | Description |
| x0 | number | Yes | 0 | X-coordinate of the start point. | | ---- | ------ | ---- | ---- | -------- |
| y0 | number | Yes | 0 | Y-coordinate of the start point. | | x0 | number | Yes | 0 | X-coordinate of the start point.|
| x1 | number | Yes | 0 | X-coordinate of the end point. | | y0 | number | Yes | 0 | Y-coordinate of the start point.|
| y1 | number | Yes | 0 | Y-coordinate of the end point. | | x1 | number | Yes | 0 | X-coordinate of the end point.|
| y1 | number | Yes | 0 | Y-coordinate of the end point.|
- Example **Example**
```ts ```ts
// xxx.ets // xxx.ets
...@@ -2167,17 +2444,18 @@ createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number, ...@@ -2167,17 +2444,18 @@ createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number,
Creates a linear gradient. Creates a linear gradient.
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ---- | ------ | --------- | ------------- | ---------------------------------------- | | Name | Type | Mandatory | Default Value | Description |
| x0 | number | Yes | 0 | X-coordinate of the center of the start circle. | | ---- | ------ | ---- | ---- | ----------------- |
| y0 | number | Yes | 0 | Y-coordinate of the center of the start circle. | | x0 | number | Yes | 0 | X-coordinate of the center of the start circle. |
| r0 | number | Yes | 0 | Radius of the start circle, which must be a non-negative finite number. | | y0 | number | Yes | 0 | Y-coordinate of the center of the start circle. |
| x1 | number | Yes | 0 | X-coordinate of the center of the end circle. | | r0 | number | Yes | 0 | Radius of the start circle, which must be a non-negative finite number.|
| y1 | number | Yes | 0 | Y-coordinate of the center of the end circle. | | x1 | number | Yes | 0 | X-coordinate of the center of the end circle. |
| r1 | number | Yes | 0 | Radius of the end circle, which must be a non-negative finite number. | | y1 | number | Yes | 0 | Y-coordinate of the center of the end circle. |
| r1 | number | Yes | 0 | Radius of the end circle, which must be a non-negative finite number.|
- Example **Example**
```ts ```ts
// xxx.ets // xxx.ets
...@@ -2216,4 +2494,4 @@ Creates a linear gradient. ...@@ -2216,4 +2494,4 @@ Creates a linear gradient.
## CanvasPattern ## CanvasPattern
Defines an object created by using the [createPattern](#createpattern) method. Defines an object created using the **[createPattern](#createpattern)** API.
...@@ -7,56 +7,45 @@ The page transition navigates users between pages. You can customize page transi ...@@ -7,56 +7,45 @@ The page transition navigates users between pages. You can customize page transi
> This event is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > This event is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
| Name | Parameter | Description | | Name | Parameter | Description |
| ------------------- | ------ | ------------------------------- | | ------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| PageTransitionEnter | Object | Page entrance component, which is used to customize the entrance effect of the current page. For details, see animation parameters.| | PageTransitionEnter | {<br>type: RouteType,<br>duration: number,<br>curve: Curve \| Curves,<br>delay: number<br>} | Page entrance animation.<br>- **type**:If this parameter is not set, the reverse playback effect as **pop** switches to **push** is used.<br>- **duration**: animation duration, in milliseconds.<br>- **curve**: animation curve. For details about the valid values, see [Curve](ts-animatorproperty.md).<br>Default value: **Curve.Linear**<br>- **delay**: animation delay, in milliseconds. By default, the animation is played without delay.|
| PageTransitionExit | Object | Page exit component, which is used to customize the exit effect of the current page. For details, see animation parameters.| | PageTransitionExit | {<br>type: RouteType,<br>duration: number,<br>curve: Curve \| Curves,<br>delay: number<br>} | Page exit animation.<br>- **type**:If this parameter is not set, the reverse playback effect as **pop** switches to **push** is used.<br>- **duration**: animation duration, in milliseconds.<br>- **curve**: animation curve. For details about the valid values, see [Curve](ts-animatorproperty.md).<br>Default value: **Curve.Linear**<br>- **delay**: animation delay, in milliseconds. By default, the animation is played without delay.|
## RouteType enums
- Animation parameters | Name| Description |
| Name | Type | Default Value | Mandatory | Description | | ---- | ------------------------------------------------------------ |
| -------- | ------------------------- | ------ | ---- | ---------------------------------------- | | Pop | Redirects to a specified page. When the user is redirected from page A to page B, page A is Exit+Push, and page B is Enter+Push.|
| type | RouteType | - | No | Animation type. If this parameter is not set, the reverse playback effect as **pop** switches to **push** is used. | | Push | Redirects to the next page. When the user is redirected back from page B to page A, page A is Enter+Pop, and page B is Exit+Pop.|
| duration | number | 1000 | No | Animation duration, in ms. | | None | The page is not redirected. |
| curve | Curve \| Curves | Linear | No | Animation curve. For details about the valid values, see [Curve](ts-animatorproperty.md).|
| delay | number | 0 | No | Animation delay, in ms. Delayed animation is disabled by default. |
- RouteType enums
| Name| Description |
| ---- | ---------------- |
| Pop | Redirects to a specified page. When the user is redirected from page A to page B, page A is Exit+Push, and page B is Enter+Push.|
| Push | Redirects to the next page. When the user is redirected back from page B to page A, page A is Enter+Pop, and page B is Exit+Pop.|
## Attributes ## Attributes
The **PageTransitionEnter** and **PageTransitionExit** parameters support the following attributes: | Name | Type | Mandatory| Description |
| --------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| slide | SlideEffect | No | Slide effect during page transition.<br>Default value: **SlideEffect.Right**|
| translate | {<br>x? : number \| string,<br>y? : number \| string,<br>z? : number \| string<br>} | No | Translation effect during page transition, which is the value of the start point of entrance and the end point of exit. When this parameter is set together with **slide**, the latter takes effect by default.<br>- **x**: translation distance along the x-axis.<br>- **y**: translation distance along the y-axis.<br>- **z**: translation distance along the y-axis.|
| scale | {<br>x? : number,<br>y? : number,<br>z? : number,<br>centerX? : number \| string,<br>centerY? : number \| string<br>} | No | Scaling effect during page transition, which is the value of the start point of entrance and the end point of exit.<br>- **x**: scale ratio along the x-axis.<br>- **y**: scale ratio along the y-axis.<br>- **z**: scale ratio along the z-axis.<br>- **centerX** and **centerY**: scale center point.<br>- If the center point is 0, it refers to the upper left corner of the component.<br>|
| opacity | number | No | Opacity, which is the opacity value of the start point of entrance or the end point of exit.<br>Default value: **1**|
| Name | Type | Default Value | Mandatory | Description | ## SlideEffect
| --------- | ---------------------------------------- | ----------------- | ---- | ---------------------------------------- |
| slide | SlideEffect | SlideEffect.Right | No | Slide effect during page transition. For details about the valid values, see **SlideEffect** enums. |
| translate | {<br>x? : number \| string,<br>y? : number \| string,<br>z? : number \| string<br>} | - | No | Translation effect during page transition, which is the value of the start point of entrance and the end point of exit. When this parameter is set together with **slide**, the latter takes effect by default.|
| scale | {<br>x? : number,<br>y? : number,<br>z? : number,<br>centerX? : number \| string,<br>centerY? : number \| string<br>} | - | No | Scaling effect during page transition, which is the value of the start point of entrance and the end point of exit. |
| opacity | number | 1 | No | Opacity, which is the opacity value of the start point of entrance or the end point of exit. |
- SlideEffect enums | Name | Description |
| Name | Description | | ------ | ------------------------- |
| ------ | ------------------------- | | Left | When set to Enter, slides in from the left. When set to Exit, slides out to the left.|
| Left | When set to Enter, slides in from the left. When set to Exit, slides out to the left.| | Right | When set to Enter, slides in from the right. When set to Exit, slides out to the right.|
| Right | When set to Enter, slides in from the right. When set to Exit, slides out to the right.| | Top | When set to Enter, slides in from the top. When set to Exit, slides out to the top.|
| Top | When set to Enter, slides in from the top. When set to Exit, slides out to the top.| | Bottom | When set to Enter, slides in from the bottom. When set to Exit, slides out to the bottom.|
| Bottom | When set to Enter, slides in from the bottom. When set to Exit, slides out to the bottom.|
## Events ## Events
The **PageTransitionEnter** and **PageTransitionExit** parameters support the following events: | Name | Description |
| ------------------------------------------------------------ | ------------------------------------------------------------ |
| Name | Description | | onEnter(event: (type?: RouteType, progress?: number) =&gt; void) | The callback input parameter is the normalized progress of the current entrance animation. The value range is 0–1.<br>- **type**: route type.<br>- **progress**: current progress.|
| ---------------------------------------- | ----------------------------------- | | onExit(event: (type?: RouteType, progress?: number) =&gt; void) | The callback input parameter is the normalized progress of the current exit animation. The value range is 0–1.<br>- **type**: route type.<br>- **progress**: current progress.|
| onEnter(type: RouteType, progress: number) =&gt; void | The callback input parameter is the normalized progress of the current entrance animation. The value range is 0–1.|
| onExit(type: RouteType, progress: number) =&gt; void | The callback input parameter is the normalized progress of the current exit animation. The value range is 0–1.|
## Example ## Example
......
# Component Transition # Component Transition
Configure the component transition animations for when a component is inserted or deleted. This feature takes effect only when **animateTo** is used. The animation duration, curve, and delay are the same as those configured in **animateTo**. Configure the component transition animations for when a component is inserted or deleted. This feature takes effect only when [animateTo](ts-explicit-animation.md) is used. The animation duration, curve, and delay are the same as those configured in **animateTo**.
> **NOTE** > **NOTE**
> >
...@@ -10,18 +10,19 @@ Configure the component transition animations for when a component is inserted o ...@@ -10,18 +10,19 @@ Configure the component transition animations for when a component is inserted o
## Attributes ## Attributes
| Name| Type| Default Value| Description| | Name| Type| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- |
| transition | Object | - | All parameters are optional. For details, see **transition**.| | transition | TransitionOptions | Transition parameters, which are all optional. For details, see **TransitionOptions**.|
## TransitionOptions
- transition | Name| Type| Mandatory| Description|
| Name| Type| Default Value| Mandatory| Description| | -------- | -------- | -------- | -------- |
| -------- | -------- | -------- | -------- | -------- | | type | [TransitionType](ts-appendix-enums.md#transitiontype) | No| Transition type, which includes component addition and deletion by default.<br>Default value: **TransitionType.All**<br>**NOTE**<br>If **type** is not specified, insertion and deletion use the same transition type.|
| type | [TransitionType](ts-appendix-enums.md#transitiontype) | TransitionType.All | No| Transition type, which includes component addition and deletion by default.<br>**NOTE**<br>If **type** is not specified, insertion and deletion use the same transition type.| | opacity | number | No| Opacity of the component during transition, which is the value of the start point of insertion and the end point of deletion.<br>Default value: **1**|
| opacity | number | 1 | No| Opacity of the component during transition, which is the value of the start point of insertion and the end point of deletion.| | translate | {<br>x? : number,<br>y? : number,<br>z? : number<br>} | No| Translation of the component during transition, which is the value of the start point of insertion and the end point of deletion.<br>-**x**: distance to translate along the x-axis.<br>-**y**: distance to translate along the y-axis.<br>-**z**: distance to translate along the z-axis.|
| translate | {<br>x? : number,<br>y? : number,<br>z? : number<br>} | - | No| Translation of the component during transition, which is the value of the start point of insertion and the end point of deletion.<br>-**x**: distance to translate along the x-axis.<br>-**y**: distance to translate along the y-axis.<br>-**z**: distance to translate along the z-axis.| | scale | {<br>x? : number,<br>y? : number,<br>z? : number,<br>centerX? : number,<br>centerY? : number<br>} | No| Scaling of the component during transition, which is the value of the start point of insertion and the end point of deletion.<br>- **x**: scale factor along the x-axis.<br>- **y**: scale factor along the y-axis.<br>- **z**: scale factor along the z-axis.<br>- **centerX** and **centerY**: x coordinate and y coordinate of the scale center, respectively.<br>- If the center point is 0, it indicates the upper left corner of the component.<br>|
| scale | {<br>x? : number,<br>y? : number,<br>z? : number,<br>centerX? : number,<br>centerY? : number<br>} | - | No| Scaling of the component during transition, which is the value of the start point of insertion and the end point of deletion.<br>- **x**: scale factor along the x-axis.<br>- **y**: scale factor along the y-axis.<br>- **z**: scale factor along the z-axis.<br>- **centerX** and **centerY**: x coordinate and y coordinate of the scale center, respectively.<br>- If the center point is 0, it indicates the upper left corner of the component. | | rotate | {<br>x?: number,<br>y?: number,<br>z?: number,<br>angle?: Angle,<br>centerX?: Length,<br>centerY?: Length<br>} | No| Rotation of the component during transition, which is the value of the start point of insertion and the end point of deletion.<br>- **x**: rotation vector along the x-axis.<br>- **y**: rotation vector along the y-axis.<br>- **z**: rotation vector along the z-axis.<br>- **centerX** and **centerY**: x coordinate and y coordinate of the rotation center, respectively.<br>- If the center point is (0, 0), it indicates the upper left corner of the component.|
| rotate | {<br>x?: number,<br>y?: number,<br>z?: number,<br>angle?: Angle,<br>centerX?: Length,<br>centerY?: Length<br>} | - | No| Rotation of the component during transition, which is the value of the start point of insertion and the end point of deletion.<br>- **x**: rotation vector along the x-axis.<br>- **y**: rotation vector along the y-axis.<br>- **z**: rotation vector along the z-axis.<br>- **centerX** and **centerY**: x coordinate and y coordinate of the rotation center, respectively.<br>- If the center point is (0, 0), it indicates the upper left corner of the component.|
## Example ## Example
......
...@@ -4,27 +4,20 @@ Shared element transition can be used for transition between pages, for example, ...@@ -4,27 +4,20 @@ Shared element transition can be used for transition between pages, for example,
> **NOTE** > **NOTE**
> >
> This animationis supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > The APIs of this module are supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Attributes ## Attributes
| Name | Type | Default Value | Description |
| -------- | -------- | -------- | -------- |
| sharedTransition | id: string,<br/>options?: Object | - | If the same ID is configured for a component on the two pages, this shared component is transited. If this parameter is set to an empty string, no shared elements are transited. |
- options parameters | Name | Parameters | Description |
| Name | Type | Default Value | Mandatory | Description | | ---------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| -------- | -------- | -------- | -------- | -------- | | sharedTransition | id: string,<br>{<br>duration?: number,<br>curve?: Curve \| string,<br>delay?: number,<br>motionPath?: <br>{<br>path: string,<br>form?: number,<br>to?: number,<br>rotatable?: boolean<br>},<br>zIndex?: number,<br>type?: [SharedTransitionEffectType](ts-appendix-enums.md#sharedtransitioneffecttype)<br>} | Transition of the shared element. If the same **id** value is configured for a component on the two pages, this component is considered as a shared element of the pages. If the **id** value is an empty string, no transition will be applied to the component.<br>- **id**: component ID.<br>- **duration**: Animation duration, in ms. The default duration is 1000 ms.<br>- **curve**: animation curve. The default curve is **Linear**. For details about the valid values, see [Curve](ts-animatorproperty.md).<br>- **delay**: Delay of animation playback, in ms. By default, the playback is not delayed.<br>- **motionPath**: motion path information.<br>- **path**: path.<br>- **from**: start value.<br>- **to**: end value.<br>- **rotatable**: whether to rotate.<br>- **zIndex**: z-axis.<br>- **type**: animation type.|
| duration | number | 1000 | No | Animation duration, in ms. The default duration is 1000 ms. |
| curve | Curve \| Curves | Linear | No | The default curve is linear. For details about the valid values, see **Curve enums**. |
| delay | number | 0 | No | Delay of animation playback, in ms. By default, the playback is not delayed. |
## Example ## Example
The example shows the transition of a shared element from a page and page B. The example implements the custom transition of a shared image during redirection from one page to another, which is triggered by a click on the image.
```ts ```ts
// xxx.ets // xxx.ets
...@@ -58,6 +51,7 @@ struct SharedTransitionExample { ...@@ -58,6 +51,7 @@ struct SharedTransitionExample {
@Entry @Entry
@Component @Component
struct BExample { struct BExample {
build() { build() {
Stack() { Stack() {
Image($r('app.media.ic_health_heart')).width(150).height(150).sharedTransition('sharedImage1') Image($r('app.media.ic_health_heart')).width(150).height(150).sharedTransition('sharedImage1')
......
# Types
## Resource
The **Resource** type is used to reference resources for setting component attribute values.
If a **Resource** object is created using `$r` or `$rawfile`, modifying attribute values of the object is prohibited.
- `$r('belonging.type.name')`
**belonging**: system or application resource. The value can be **'sys'** or **'app'**.
**type**: resource type, which can be **'color'**, **'float'**, **'string'**, or **'media'**.
**name**: resource name, which is determined during resource definition.
- `$rawfile('filename')`
**filename**: name of the file in **resources/rawfile** of the project.
## Length
The **Length** type is used to represent a size unit.
| Type | Description |
| -------- | -------------------------------------- |
| string | String type. Explicitly specify the length unit, for example, **'10px'**, or the length in percentage, for example, **'100%'**.|
| number | Number type. The default unit is vp. |
| [Resource](#resource) | Size referenced from system or application resources. |
## ResourceStr
The **ResourceStr** type is used to represent the types that can be used by input parameters of the string type.
| Type | Description |
| -------- | ---------------------------- |
| string | String type. |
| [Resource](#resource) | String referenced from system or application resources.|
## Padding
The **Padding** type is used to describe the padding areas in different directions of a component.
| Name | Type | Mandatory | Description |
| ------ | ------ | ---- | --------------- |
| top | [Length](#length) | No | Height of the padding area on the top of the component. |
| right | [Length](#length) | No | Width of the padding area on the right of the component.|
| bottom | [Length](#length) | No | Height of the padding area at the bottom of the component. |
| left | [Length](#length) | No | Width of the padding area on the left of the component.|
## Margin
The **Margin** type is used to describe the margin areas in different directions of a component.
| Name | Type | Mandatory | Description |
| ------ | ------ | ---- | --------------- |
| top | [Length](#length) | No | Height of the margin area above the component. |
| right | [Length](#length) | No | Width of the margin area on the right of the component.|
| bottom | [Length](#length) | No | Height of the margin area below the component. |
| left | [Length](#length) | No | Width of the margin area on the left of the component.|
## EdgeWidths<sup>9+</sup>
The **EdgeWidths** type is used to describe the edge widths in different directions of a component.
| Name | Type | Mandatory | Description |
| ------ | ------ | ---- | -------- |
| top | [Length](#length) | No | Width of the top edge of the component.|
| right | [Length](#length) | No | Width of the right edge of the component.|
| bottom | [Length](#length) | No | Width of the bottom edge of the component.|
| left | [Length](#length) | No | Width of the left edge of the component.|
## BorderRadiuses<sup>9+</sup>
The **BorderRadiuses** type is used to describe the radius of the rounded corners of a component.
| Name | Type | Mandatory | Description |
| ----------- | ------ | ---- | ---------- |
| topLeft | [Length](#length) | No | Radius of the top left rounded corner of the component.|
| topRight | [Length](#length) | No | Radius of the top right rounded corner of the component.|
| bottomLeft | [Length](#length) | No | Radius of the bottom left rounded corner of the component.|
| bottomRight | [Length](#length) | No | Radius of the bottom right rounded corner of the component.|
## EdgeColors<sup>9+</sup>
The **EdgeColors** type is used to describe the edge colors of a component.
| Name | Type | Mandatory | Description |
| ------ | ------------- | ---- | -------- |
| top | [ResourceColor](#resourcecolor) | No | Color of the top edge of the component.|
| right | [ResourceColor](#resourcecolor) | No | Color of the right edge of the component.|
| bottom | [ResourceColor](#resourcecolor) | No | Color of the bottom edge of the component.|
| left | [ResourceColor](#resourcecolor) | No | Color of the left edge of the component.|
## EdgeStyles<sup>9+</sup>
The **EdgeStyles** type is used to describe the edge styles of a component.
| Name | Type | Mandatory | Description |
| ------ | ----------- | ---- | -------- |
| top | [BorderStyle](ts-appendix-enums.md#borderstyle) | No | Style of the top edge of the component.|
| right | [BorderStyle](ts-appendix-enums.md#borderstyle) | No | Style of the right edge of the component.|
| bottom | [BorderStyle](ts-appendix-enums.md#borderstyle) | No | Style of the bottom edge of the component.|
| left | [BorderStyle](ts-appendix-enums.md#borderstyle) | No | Style of the left edge of the component.|
## Offset
The **Offset** type is used to describe the offset coordinates of a component in the layout.
| Name | Type | Mandatory | Description |
| ---- | ------ | ---- | -------- |
| dx | [Length](#length) | Yes | Horizontal offset.|
| dy | [Length](#length) | Yes | Vertical offset.|
## ResourceColor
The **ResourceColor** type is used to describe the color types of resources.
| Type | Description |
| ---------------------------------------- | ------------------------------------------------- |
| [Color](ts-appendix-enums.md#color) | Color enum. |
| number | Color in the hexadecimal notation. |
| string | Color in the RGB or RGBA notion. |
| [Resource](#resource) | Color referenced from system or application resources.|
## LengthConstrain
The **LengthConstrain** type is used to limit the maximum and minimum lengths of a component.
| Name | Type | Mandatory | Description |
| --------- | ------ | ---- | ------- |
| minLength | [Length](#length) | Yes | Minimum length of the component.|
| maxLength | [Length](#length) | Yes | Maximum length of the component.|
## Font
The **Font** type is used to set the text style.
| Name | Type | Mandatory | Description |
| ------ | ---------------------------------------- | ---- | ---------------------------------------- |
| size | [Length](#length) | No | Font size. If the value is of the number type, the unit fp is used. |
| weight | [FontWeight](ts-appendix-enums.md#fontweight) \| number \| string | No | Font weight. For the number type, the value ranges from 100 to 900, at an interval of 100. The default value is **400**. A larger value indicates a larger font weight.|
| family | string \| [Resource](#resource) | No | Font family of the text. Use commas (,) to separate multiple fonts. The priority of the fonts is the sequence in which they are placed. An example value is **'Arial, sans-serif'**.|
| style | [FontStyle](ts-appendix-enums.md#fontstyle) | No | Font style. |
## Area<sup>8+</sup>
The **Area** type is used to describe the area information of the target element.
| Name | Type | Description |
| -------------- | ---------------------- | ------------------------------ |
| width | [Length](#length) | Width of the target element. The value is of the number type when being used as the return value and the unit is vp.|
| height | [Length](#length) | Height of the target element. The value is of the number type when being used as the return value and the unit is vp.|
| position | [Position](#position8) | Position of the upper left corner of the target element relative to that of the parent element. |
| globalPosition | [Position](#position8) | Position of the upper left corner of the target element relative to that of the page. |
## Position<sup>8+</sup>
The **Position** type is used to represent coordinates of a point.
| Name | Type | Mandatory | Description |
| ---- | ------ | ---- | --------------------------- |
| x | [Length](#length) | No | X coordinate. The value is of the number type when being used as the return value and the unit is vp.|
| y | [Length](#length) | No | Y coordinate. The value is of the number type when being used as the return value and the unit is vp.|
## ConstraintSizeOptions
The **ConstraintSizeOptions** type is used to set the constraint size of a component, thereby limiting the size range during component layout.
| Name | Type | Mandatory | Description |
| --------- | ------ | ---- | ------- |
| minWidth | [Length](#length) | No | Minimum width of the element.|
| maxWidth | [Length](#length) | No | Maximum width of the element.|
| minHeight | [Length](#length) | No | Minimum height of the element.|
| maxHeight | [Length](#length) | No | Maximum height of the element.|
## SizeOptions
The **SizeOptions** type is used to set the width and height.
| Name | Type | Mandatory | Description |
| ------ | ------ | ---- | ----- |
| width | [Length](#length) | No | Width of the element.|
| height | [Length](#length) | No | Height of the element.|
## BorderOptions
The **BorderOptions** type is used to provide border information.
| Name | Type | Mandatory | Description |
| ------ | ---------------------------------------- | ---- | ------- |
| width | [Length](#length) \| [EdgeWidths](#edgewidths9)<sup>9+</sup> | No | Border width. |
| color | [ResourceColor](#resourcecolor) \| [EdgeColors](#edgecolors9)<sup>9+</sup> | No | Border color. |
| radius | [Length](#length) \| [BorderRadiuses](#borderradiuses9)<sup>9+</sup> | No | Radius of the rounded corner border.|
| style | [BorderStyle](ts-appendix-enums.md#borderstyle) \| EdgeStyles<sup>9+</sup> | No | Border style. |
## ColorFilter<sup>9+</sup>
The **ColorFilter** type is used to create a color filter with a 4*5 matrix.
| Name | Type | Mandatory | Description |
| ----------- | -------- | ---- | ---------------------------------------- |
| constructor | number[] | Yes | Constructor for creating a color filter with a 4\*5 matrix. The input parameter is [m\*n], which is the matrix value in row m and column n. The matrix is row-first.|
## CustomBuilder<sup>8+</sup>
The **CustomBuilder** type is used to define custom UI descriptions in component attribute methods.
| Name | Type | Description |
| ------------- | ---------------------- | ---------------------------------------- |
| CustomBuilder | ()&nbsp;=&gt;&nbsp;any | Must be decorated by **@Builder**. For details, see [@Builder](../../ui/ts-component-based-builder.md).|
...@@ -2,26 +2,18 @@ ...@@ -2,26 +2,18 @@
You can set the background of a component. You can set the background of a component.
> **NOTE** > **NOTE**
> >
> This attribute is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > The APIs of this module are supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
None
## Attributes ## Attributes
| Name| Type| Description|
| Name | Type | Default Value | Description | | -------- | -------- | -------- |
| -------- | -------- | -------- | -------- | | backgroundColor | [ResourceColor](ts-types.md#resourcecolor) | The table below describes the attributes used to set the background color of a component.|
| backgroundColor | [ResourceColor](../../ui/ts-types.md) | - | Background color of a component. | | backgroundImage | src: [ResourceStr](ts-types.md#resourcestr),<br>repeat?: [ImageRepeat](ts-appendix-enums.md#imagerepeat) | **src**: image address, which can be the address of an Internet or a local image. (SVG images are not supported.)<br>**repeat**: whether the background image is repeatedly used. By default, the background image is not repeatedly used.|
| backgroundImage | src: [ResourceStr](../../ui/ts-types.md),<br/>repeat?: [ImageRepeat](ts-appendix-enums.md#imagerepeat) | - | **src**: image address, which can be the address of an Internet or a local image. (SVG images are not supported.)<br/>**repeat**: whether the background image is repeatedly used. By default, the background image is not repeatedly used. | | backgroundImageSize | {<br>width?: [Length](ts-types.md#length),<br>height?: [Length](ts-types.md#length)<br>} \| [ImageSize](ts-appendix-enums.md#imagesize) | Width and height of the background image. If the input is a **{width: Length, height: Length}** object and only one attribute is set, the other attribute is the set value multiplied by the original aspect ratio of the image. By default, the original image aspect ratio remains unchanged.<br>Default value: **ImageSize.Auto**|
| backgroundImageSize | {<br/>width?: Length,<br/>height?: Length<br/>} \| [ImageSize](ts-appendix-enums.md#imagesize) | Auto | Width and height of the background image. When the input is a **{width: Length, height: Length}** object, if only one attribute is set, the other attribute is the set value multiplied by the original aspect ratio of the image. By default, the original image aspect ratio remains unchanged. | | backgroundImagePosition | [Position](ts-types.md#position8) \| [Alignment](ts-appendix-enums.md#alignment) | Position of the background image in the component.<br>Default value:<br>{<br>x: 0,<br>y: 0<br>} |
| backgroundImagePosition | {<br/>x?: Length,<br/>y?: Length<br/>} \| [Alignment](ts-appendix-enums.md#alignment) | {<br/>x: 0,<br/>y: 0<br/>} | Position of the background image in the component. |
## Example ## Example
......
...@@ -6,25 +6,19 @@ You can apply background blur effects to a component. ...@@ -6,25 +6,19 @@ You can apply background blur effects to a component.
> >
>The APIs of this module are supported since API version 9. Updates will be marked with a superscript to indicate their earliest API version. >The APIs of this module are supported since API version 9. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
None
## Attributes ## Attributes
| Name | Type | Default Value | Description | | Name | Type | Description |
| ------------ | ------------- | ----------------------- | ------------------------ | | -------------------- | ----------------------- | ------------------------ |
| backgroundBlurStyle | [BlurStyle](#blurstyle) | - | Style of the blur between the background and content for the current component. The input parameter indicates a blur material.| | backgroundBlurStyle | [BlurStyle](#blurstyle) | Style of the blur between the background and content for the current component. The input parameter indicates a blur material.|
## BlurStyle ## BlurStyle
| Name | Description | | Name | Description |
| ------ | ----------------------------------------------- | | ------- | ---------- |
| Thin | Thin material.| | Thin | Thin material. |
| Regular | Regular material. | | Regular | Regular material. |
| Thick | Thick material. | | Thick | Thick material. |
## Example ## Example
...@@ -32,7 +26,6 @@ None ...@@ -32,7 +26,6 @@ None
// xxx.ets // xxx.ets
@Entry @Entry
@Component @Component
struct Index { struct Index {
build() { build() {
Column() { Column() {
...@@ -42,12 +35,13 @@ struct Index { ...@@ -42,12 +35,13 @@ struct Index {
.width(350) .width(350)
.height(300) .height(300)
.backgroundBlurStyle(BlurStyle.Thin) .backgroundBlurStyle(BlurStyle.Thin)
.position({x: "15%", y: "30%"}) .position({ x: "15%", y: "30%" })
} }
.height('100%') .height('100%')
.width('100%') .width('100%')
.backgroundImage($r('app.media.bg')) .backgroundImage($r('app.media.bg'))
.backgroundImageSize(ImageSize.Cover) .backgroundImageSize(ImageSize.Cover)
} }
}
``` ```
![en-us_image_background_blur_style](figures/en-us_image_background_blur_style.png) ![en-us_image_background_blur_style](figures/en-us_image_background_blur_style.png)
...@@ -4,41 +4,44 @@ You can draw an image around a component. ...@@ -4,41 +4,44 @@ You can draw an image around a component.
> **NOTE** > **NOTE**
> >
> The APIs of this module are supported since API version 9. Updates will be marked with a superscript to indicate their earliest API version. > The APIs of this module are supported since API version 9. Updates will be marked with a superscript to indicate their earliest API version.
## Attributes ## Attributes
| Name | Type | Description |
| ---------- | ---------------------------------------- | --------------------------------------- |
| borderImage | BorderImageOption | Border image or border gradient. |
| Name| Type| Description| ## BorderImageOption
| -------- | -------- | -------- |
| source | string \| [Resource](../../ui/ts-types.md) \| [linearGradient](ts-universal-attributes-gradient-color.md) | Source or gradient color of the border image.|
| slice | [Length](../../ui/ts-types.md#length)\| EdgeWidth | Slice width of the border image.<br>Default value: **0**|
| width | [Length](../../ui/ts-types.md#length)\| EdgeWidth | Width of the border image.<br>Default value: **0**|
| outset | [Length](../../ui/ts-types.md#length)\| EdgeWidth | Amount by which the border image is extended beyond the border box.<br>Default value: **0**|
| RepeatMode | RepeatMode | Repeat mode of the border image.<br>Default value: **RepeatMode.Stretch**|
| fill | boolean | Whether to fill the center of the border image.<br>Default value: **false**|
## EdgeWidth
At least one parameter must be passed to reference an **EdgeWidth** object. | Name | Type | Description |
| ---------- | ---------------------------------------- | --------------------------------------- |
| source | string \| [Resource](ts-types.md#resource) \| [linearGradient](ts-universal-attributes-gradient-color.md) | Source or gradient color of the border image. |
| slice | [Length](ts-types.md#length)\| EdgeWidths | Slice width of the border image.<br>Default value: **0** |
| width | [Length](ts-types.md#length)\| EdgeWidths | Width of the border image.<br>Default value: **0** |
| outset | [Length](ts-types.md#length)\| EdgeWidths | Amount by which the border image is extended beyond the border box.<br>Default value: **0** |
| RepeatMode | RepeatMode | Repeat mode of the border image.<br>Default value: **RepeatMode.Stretch**|
| fill | boolean | Whether to fill the center of the border image.<br>Default value: **false** |
## EdgeWidths
At least one parameter must be passed to reference an **EdgeWidth** object.
| Name| Type| Mandatory|Description| | Name| Type| Mandatory|Description|
| -------- | -------- |-------- |-------- | | -------- | -------- |-------- |-------- |
| left | [Length](../../ui/ts-types.md#length) | No| Distance on the left.| | left | [Length](ts-types.md#length) | No| Distance on the left.|
| right | [Length](../../ui/ts-types.md#length) | No| Distance on the right.| | right | [Length](ts-types.md#length) | No| Distance on the right.|
| top | [Length](../../ui/ts-types.md#length) | No| Distance at the top.| | top | [Length](ts-types.md#length) | No| Distance at the top.|
| bottom | [Length](../../ui/ts-types.md#length) | No| Distance on the bottom.| | bottom | [Length](ts-types.md#length) | No| Distance on the bottom.|
## RepeatMode ## RepeatMode
| Name| Description| | Name | Description |
| -------- | -------- | | ------- | ----------------------------------- |
| Repeat | The source image's slices are tiled. Tiles beyond the border box will be clipped.| | Repeat | The source image's slices are tiled. Tiles beyond the border box will be clipped. |
| Stretch | The source image's slices stretched to fill the border box.| | Stretch | The source image's slices stretched to fill the border box. |
| Round | The source image's slices are tiled to fill the border box. Tiles may be compressed when needed.| | Round | The source image's slices are tiled to fill the border box. Tiles may be compressed when needed.|
| Space | The source image's slices are tiled to fill the border box. Extra space will be filled in between tiles.| | Space | The source image's slices are tiled to fill the border box. Extra space will be filled in between tiles. |
## Example ## Example
......
...@@ -11,58 +11,57 @@ The border attributes are used to set border styles for components. ...@@ -11,58 +11,57 @@ The border attributes are used to set border styles for components.
## Attributes ## Attributes
| Name | Type | Description | | Name | Type | Description |
| ------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | | ------------ | ------------------------------------------------------------ | ------------------------------------------------------------ |
| border | {<br>width?: [Length](../../ui/ts-types.md#length) \| EdgeWidth<sup>9+</sup>,<br>color?: [ResourceColor](../../ui/ts-types.md) \| EdgeColor<sup>9+</sup>,<br>radius?: [Length](../../ui/ts-types.md#length) \| BorderRadiuses<sup>9+</sup>,<br>style?: [BorderStyle](ts-appendix-enums.md#borderstyle) \| EdgeStyle<sup>9+</sup><br>} | Unified border style.<br>- **width**: border width.<br>- **color**: border color.<br>- **radius**: radius of the rounded corner of the border.<br>- **style**: border style.| | border | {<br>width?: [Length](ts-types.md#length) \| EdgeWidths<sup>9+</sup>,<br>color?: [ResourceColor](ts-types.md#resourcecolor) \| EdgeColors<sup>9+</sup>,<br>radius?: [Length](ts-types.md#length) \| BorderRadiuses<sup>9+</sup>,<br>style?: [BorderStyle](ts-appendix-enums.md#borderstyle) \| EdgeStyles<sup>9+</sup><br>} | Unified border style.<br>- **width**: border width.<br>- **color**: border color.<br>- **radius**: radius of the rounded corner of the border.<br>- **style**: border style.|
| borderStyle | [BorderStyle](ts-appendix-enums.md#borderstyle) \| EdgeStyle<sup>9+</sup> | Border style of an element.<br>Default value: **BorderStyle.Solid** | | borderStyle | [BorderStyle](ts-appendix-enums.md#borderstyle) \| EdgeStyles<sup>9+</sup> | Border style of an element.<br>Default value: **BorderStyle.Solid** |
| borderWidth | [Length](../../ui/ts-types.md) \| EdgeWidth<sup>9+</sup> | Border width of an element. | | borderWidth | [Length](ts-types.md#length) \| EdgeWidths<sup>9+</sup> | Border width. The percentage format is not supported. |
| borderColor | [ResourceColor](../../ui/ts-types.md) \| EdgeColor<sup>9+</sup> | Border color of an element. | | borderColor | [ResourceColor](ts-types.md#resourcecolor) \| EdgeColors<sup>9+</sup> | Border color of an element. |
| borderRadius | [Length](../../ui/ts-types.md) \| BorderRadiuses<sup>9+</sup> | Border radius of an element. | | borderRadius | [Length](ts-types.md#length) \| BorderRadiuses<sup>9+</sup> | Border radius. The percentage format is not supported. |
## EdgeWidth<sup>9+</sup> ## EdgeWidths<sup>9+</sup>
To reference this object, at least one parameter must be passed. To reference this object, at least one parameter must be passed.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory | Description |
| ------ | ------------------------------------- | ---- | -------------- | | ------ | ---------------------------- | ---- | ------- |
| left | [Length](../../ui/ts-types.md#length) | No | Width of the left border.| | left | [Length](ts-types.md#length) | No | Width of the left border.|
| right | [Length](../../ui/ts-types.md#length) | No | Width of the right border.| | right | [Length](ts-types.md#length) | No | Width of the right border.|
| top | [Length](../../ui/ts-types.md#length) | No | Width of the top border.| | top | [Length](ts-types.md#length) | No | Width of the top border.|
| bottom | [Length](../../ui/ts-types.md#length) | No | Width of the bottom border.| | bottom | [Length](ts-types.md#length) | No | Width of the bottom border.|
## EdgeColor<sup>9+</sup> ## EdgeColors<sup>9+</sup>
To reference this object, at least one parameter must be passed. To reference this object, at least one parameter must be passed.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory | Description |
| ------ | ------------------------------------- | ---- | -------------- | | ------ | ---------------------------------------- | ---- | ------- |
| left | [ResourceColor](../../ui/ts-types.md) | No | Color of the left border.| | left | [ResourceColor](ts-types.md#resourcecolor) | No | Color of the left border.|
| right | [ResourceColor](../../ui/ts-types.md) | No | Color of the right border.| | right | [ResourceColor](ts-types.md#resourcecolor) | No | Color of the right border.|
| top | [ResourceColor](../../ui/ts-types.md) | No | Color of the top border.| | top | [ResourceColor](ts-types.md#resourcecolor) | No | Color of the top border.|
| bottom | [ResourceColor](../../ui/ts-types.md) | No | Color of the bottom border.| | bottom | [ResourceColor](ts-types.md#resourcecolor) | No | Color of the bottom border.|
## BorderRadiuses<sup>9+</sup> ## BorderRadiuses<sup>9+</sup>
To reference this object, at least one parameter must be passed. To reference this object, at least one parameter must be passed.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory | Description |
| ----------- | ------------------------------------- | ---- | ---------------- | | ----------- | ---------------------------- | ---- | -------- |
| topLeft | [Length](../../ui/ts-types.md#length) | No | Radius of the upper-left rounded corner.| | topLeft | [Length](ts-types.md#length) | No | Radius of the upper-left rounded corner.|
| topRight | [Length](../../ui/ts-types.md#length) | No | Radius of the upper-right rounded corner.| | topRight | [Length](ts-types.md#length) | No | Radius of the upper-right rounded corner.|
| bottomLeft | [Length](../../ui/ts-types.md#length) | No | Radius of the lower-left rounded corner.| | bottomLeft | [Length](ts-types.md#length) | No | Radius of the lower-left rounded corner.|
| bottomRight | [Length](../../ui/ts-types.md#length) | No | Radius of the lower-right rounded corner.| | bottomRight | [Length](ts-types.md#length) | No | Radius of the lower-right rounded corner.|
## EdgeStyle<sup>9+</sup> ## EdgeStyles<sup>9+</sup>
To reference this object, at least one parameter must be passed. To reference this object, at least one parameter must be passed.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory | Description |
| ------ | ----------------------------------------------- | ---- | -------------- | | ------ | ---------------------------------------- | ---- | ------- |
| left | [BorderStyle](ts-appendix-enums.md#borderstyle) | No | Style of the left border.| | left | [BorderStyle](ts-appendix-enums.md#borderstyle) | No | Style of the left border.|
| right | [BorderStyle](ts-appendix-enums.md#borderstyle) | No | Style of the right border.| | right | [BorderStyle](ts-appendix-enums.md#borderstyle) | No | Style of the right border.|
| top | [BorderStyle](ts-appendix-enums.md#borderstyle) | No | Style of the top border.| | top | [BorderStyle](ts-appendix-enums.md#borderstyle) | No | Style of the top border.|
| bottom | [BorderStyle](ts-appendix-enums.md#borderstyle) | No | Style of the bottom border.| | bottom | [BorderStyle](ts-appendix-enums.md#borderstyle) | No | Style of the bottom border.|
## Example ## Example
......
...@@ -7,17 +7,12 @@ Click control attributes are used to set whether a component can respond to fing ...@@ -7,17 +7,12 @@ Click control attributes are used to set whether a component can respond to fing
> The APIs of this module are supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > The APIs of this module are supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
None
## Attributes ## Attributes
| Name | Type| Default Value| Description | | Name | Type| Description |
| --------- | -------- | ------- | -------------- | | ----------- | -------- | ------------------------ |
| touchable | boolean | true | Whether the component can respond to finger interactions such as click and touch events.| | touchable | boolean | Whether the component can respond to finger interactions such as click and touch events.<br>Default value: **true**|
## Example ## Example
......
...@@ -4,19 +4,14 @@ ...@@ -4,19 +4,14 @@
> **NOTE** > **NOTE**
> >
> The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. > The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
None
## Attributes ## Attributes
| Name| Type| Default Value| Description| | Name | Type | Description |
| -------- | -------- | -------- | -------- | | -----| -------- | ----------------------------- |
| id | string | '' | Unique ID you assigned to the component.| | id | string | Unique ID you assigned to the component.<br>Default value: **''**|
## APIs ## APIs
...@@ -28,15 +23,17 @@ getInspectorByKey(id: string): string ...@@ -28,15 +23,17 @@ getInspectorByKey(id: string): string
Obtains all attributes of the component with the specified ID, excluding the information about child components. Obtains all attributes of the component with the specified ID, excluding the information about child components.
- Parameters **Parameters**
| Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- | | Name | Type | Mandatory | Description |
| id | string | Yes| - | ID of the component whose attributes are to be obtained.| | ---- | -------- | ---- | -------------|
| id | string | Yes | ID of the component whose attributes are to be obtained.|
- Return value **Return value**
| Type| Description|
| -------- | -------- | | Type | Description |
| string | JSON string of the component attribute list.| | -------| -------------- |
| string | JSON string of the component attribute list.|
### getInspectorTree<sup>9+</sup> ### getInspectorTree<sup>9+</sup>
...@@ -44,11 +41,11 @@ getInspectorTree(): string ...@@ -44,11 +41,11 @@ getInspectorTree(): string
Obtains the component tree and component attributes. Obtains the component tree and component attributes.
- Return value **Return value**
| Type | Description | | Type | Description |
| ------ | ---------------------------------- | | ------ | --------------------------- |
| string | JSON string of the component tree and component attribute list.| | string | JSON string of the component tree and component attribute list.|
### sendEventByKey<sup>9+</sup> ### sendEventByKey<sup>9+</sup>
...@@ -56,17 +53,19 @@ sendEventByKey(id: string, action: number, params: string): boolean ...@@ -56,17 +53,19 @@ sendEventByKey(id: string, action: number, params: string): boolean
Sends an event to the component with the specified ID. Sends an event to the component with the specified ID.
- Parameters **Parameters**
| Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- | | Name | Type | Mandatory | Description |
| id | string | Yes| - | ID of the component to which the event is to be sent.| | ------ | -------| ---- | -------------------------- |
| action | number | Yes| - | Type of the event to be sent. The options are as follows:<br>- **10**: click event.<br>- **11**: long-click event.| | id | string | Yes | ID of the component to which the event is to be sent. |
| params | string | Yes| - | Event parameters. If there is no parameter, pass an empty string **""**.| | action | number | Yes | Type of the event to be sent. The options are as follows:<br>- **10**: click event.<br>- **11**: long-click event.|
| params | string | Yes | Event parameters. If there is no parameter, pass an empty string **""**. |
**Return value**
- Return value | Type | Description |
| Type| Description| | -------- | --------------------------|
| -------- | -------- | | boolean | Returns **true** if the component with the specified ID is found; returns **false** otherwise.|
| boolean | Returns **true** if the component with the specified ID is found; returns **false** otherwise.|
### sendTouchEvent<sup>9+</sup> ### sendTouchEvent<sup>9+</sup>
...@@ -74,17 +73,17 @@ sendTouchEvent(event: TouchObject): boolean ...@@ -74,17 +73,17 @@ sendTouchEvent(event: TouchObject): boolean
Sends a touch event. Sends a touch event.
- Parameters **Parameters**
| Name | Type | Mandatory| Default Value| Description | | Name | Type | Mandatory | Description |
| ----- | ----------- | ---- | ------ | ------------------------------------------------------------ | | ----- | ----------- | ---- | ------------------------------------------------------------ |
| event | TouchObject | Yes | - | Location where a touch event is triggered. For details, see [TouchEvent](ts-universal-events-touch.md#touchevent).| | event | TouchObject | Yes | Location where a touch event is triggered. For details, see [TouchEvent](ts-universal-events-touch.md#touchevent).|
- Return value **Return value**
| Type | Description | | Type | Description |
| ------- | ------------------------------------------- | | ------- | ---------------------------|
| boolean | Returns **true** if the event is sent successfully; returns **false** otherwise.| | boolean | Returns **true** if the event is sent successfully; returns **false** otherwise.|
### sendKeyEvent<sup>9+</sup> ### sendKeyEvent<sup>9+</sup>
...@@ -92,17 +91,17 @@ sendKeyEvent(event: KeyEvent): boolean ...@@ -92,17 +91,17 @@ sendKeyEvent(event: KeyEvent): boolean
Sends a key event. Sends a key event.
- Parameters **Parameters**
| Name | Type | Mandatory| Default Value| Description | | Name | Type | Mandatory | Description |
| ----- | -------- | ---- | ------ | ------------------------------------------------------------ | | ----- | -------- | ---- | ------------------------------------------------------------ |
| event | KeyEvent | Yes | - | Key event. For details, see [KeyEvent](ts-universal-events-key.md#keyevent).| | event | KeyEvent | Yes | Key event. For details, see [KeyEvent](ts-universal-events-key.md#keyevent).|
- Return value **Return value**
| Type | Description | | Type | Description |
| ------- | --------------------------------------------- | | ------- | ------------------------------|
| boolean | Returns **true** if the event is sent successfully; returns **false** otherwise.| | boolean | Returns **true** if the event is sent successfully; returns **false** otherwise.|
### sendMouseEvent<sup>9+</sup> ### sendMouseEvent<sup>9+</sup>
...@@ -110,17 +109,17 @@ sendMouseEvent(event: MouseEvent): boolean ...@@ -110,17 +109,17 @@ sendMouseEvent(event: MouseEvent): boolean
Sends a mouse event. Sends a mouse event.
- Parameters **Parameters**
| Name | Type | Mandatory| Default Value| Description | | Name | Type | Mandatory | Description |
| ----- | ---------- | ---- | ------ | ------------------------------------------------------------ | | ----- | ---------- | ---- | --------------------------------------- |
| event | MouseEvent | Yes | - | Mouse event. For details, see [MouseEvent](ts-universal-mouse-key.md#mouseevent).| | event | MouseEvent | Yes | Mouse event. For details, see [MouseEvent](ts-universal-mouse-key.md#mouseevent).|
- Return value **Return value**
| Type | Description | | Type | Description |
| ------- | --------------------------------------------- | | ------- | ---------------------------------- |
| boolean | Returns **true** if the event is sent successfully; returns **false** otherwise.| | boolean | Returns **true** if the event is sent successfully; returns **false** otherwise.|
## Example ## Example
......
...@@ -12,7 +12,7 @@ The **enabled** attribute sets whether a component responds to user interactions ...@@ -12,7 +12,7 @@ The **enabled** attribute sets whether a component responds to user interactions
| Name | Type | Description | | Name | Type | Description |
| ------- | ------- | ---------------------------------------- | | ------- | ------- | ---------------------------------------- |
| enabled | boolean | Whether the component responds to user interactions, including clicks and touches. The value **true** means that the component responds to user interactions, and **false** means the opposite.<br>Default value: **true** | | enabled | boolean | Whether the component responds to user interactions, including clicks and touches. The value **true** means that the component responds to user interactions,<br>and **false** means the opposite.<br>Default value: **true**|
## Example ## Example
......
# Flex Layout # Flex Layout
> **NOTE** > **NOTE**
> - The APIs of this module are supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > - The APIs of this module are supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
> >
> - The flex layout attributes are valid only when the parent component is a **\<Flex>** component. > - The flex layout is valid only when the parent component is a **\<Flex>**, **\<Column>**, or **\<Row>** component.
## Required Permissions
None
## Attributes ## Attributes
| Name | Type | Description |
| Name| Type| Default Value| Description| | ---------- | ---------------------------------------- | ---------------------------------------- |
| -------- | -------- | -------- | -------- | | flexBasis | number \| string | Base size of a component in the main axis of the parent container.<br>Default value: **'auto'** (indicating that the base size of the component in the main axis is the original size of the component)|
| flexBasis | 'auto' \| Length | 'auto' | Base dimension of the component in the main axis of the flex layout.| | flexGrow | number | Percentage of the parent container's remaining space that is allocated to the component.<br>Default value: **0** |
| flexGrow | number | 0 | Percentage of the flex layout's remaining space that is allocated to the component.| | flexShrink | number | Percentage of the parent container's shrink size that is allocated to the component.<br>When the parent container is **\<Row>** or **\<Column>**, the default value is **0**.<br> When the parent container is **\<Flex>**, the default value is **1**. |
| flexShrink | number | 1 | Percentage of the flex layout's shrink size that is allocated to the component.| | alignSelf | [ItemAlign](ts-appendix-enums.md#itemalign) | Alignment mode of the child components along the cross axis, which overwrites the default **alignItems** configuration in the parent container.<br>Default value: **ItemAlign.Auto**|
| alignSelf | [ItemAlign](ts-appendix-enums.md#itemalign)| Auto | Alignment mode, which overwrites the default **alignItems** configuration in the flex layout.|
## Example ## Example
...@@ -33,8 +27,8 @@ struct FlexExample { ...@@ -33,8 +27,8 @@ struct FlexExample {
build() { build() {
Column({ space: 5 }) { Column({ space: 5 }) {
Text('flexBasis').fontSize(9).fontColor(0xCCCCCC).width('90%') Text('flexBasis').fontSize(9).fontColor(0xCCCCCC).width('90%')
// Base dimension in the main axis // Base size in the main axis
// flexBasis() can be 'auto' (default value), which indicates the original component size. If the value is of the number type, it is similar to .width()/.height(). The value is based on the main axis. // The value of flexBasis() can be 'auto' or a number, which is equivalent to .width()/.height().
Flex() { Flex() {
Text('flexBasis(100)') Text('flexBasis(100)')
.flexBasis('100').height(100).lineHeight(70) .flexBasis('100').height(100).lineHeight(70)
......
# Focus Control # Focus Control
> **NOTE** Focus control attributes set whether a component is focusable, how it participates in sequential keyboard navigation,
> **NOTE**<br>
> >
> The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. > The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions ## Attributes
None | Name | Type| Description |
| -------------------- | -------- | ---------------------------------------- |
| focusable | boolean | Whether the current component is focusable.<br>**NOTE**<br>Components that have default interaction logic, such as **\<Button>** and **\<TextInput>**, are focusable by default. Other components, such as **\<Text>** and **\<Image>**, are not focusable by default. |
| tabIndex<sup>9+<sup> | number | How the current component participates in sequential keyboard navigation.<br>- **tabIndex** >= 0: The component is focusable in sequential keyboard navigation, with its order defined by the value. A component with a larger value is focused after one with a smaller value. If multiple components share the same **tabIndex** value, their focus order follows their position in the component tree.<br>- **tabIndex** < 0 (usually **tabIndex** = -1): The component is focusable, but cannot be reached through sequential keyboard navigation.<br>Default value: **0**|
| defaultFocus<sup>9+<sup> | boolean | Whether to set the current component as the default focus of the page. This attribute takes effect only when the page is new and accessed for the first time.<br>Default value: **false**|
| groupDefaultFocus<sup>9+<sup> | boolean | Whether to set the current component as the default focus of the parent container. This attribute takes effect only when the container is new and has focus for the first time.<br>Default value: **false**<br>**NOTE**<br>This attribute must be used together with **tabIndex**. When **tabIndex** is set for a container and **groupDefaultFocus** is set for a component in the container, the focus is automatically shifted to that component when the container obtains the focus for the first time.<br>|
| focusOnTouch<sup>9+<sup> | boolean | Whether the current component is focusable on touch.<br>Default value: **false**<br>**NOTE**<br>The component can obtain focus only when it is touchable or clickable.|
## focusControl<sup>9+</sup>
## Attributes ### requestFocus<sup>9+</sup>
| Name| Type| Default Value| Description| requestFocus(value: string): boolean
| -------- | -------- | -------- | -------- |
| focusable | boolean | false | Whether the current component is focusable.|
| tabIndex<sup>9+<sup> | number | 0 | How the current component participates in sequential keyboard navigation.<br>- **tabIndex** >= 0: The component is focusable in sequential keyboard navigation, with its order defined by the value. A component with a larger value is focused after one with a smaller value. If multiple components share the same **tabIndex** value, their focus order follows their position in the component tree.<br>- **tabIndex** < 0 (usually **tabIndex** = -1): The component is focusable, but cannot be reached through sequential keyboard navigation. |
> **NOTE** Requests the focus to move to the specified component. This API can be used in global method statements.
>
> The following components support focus control: **\<Button>**, **\<Text>**, **\<Image>**, **\<List>**, and **\<Grid>**. **Parameters**
| Name| Type| Mandatory| Description|
| ----- | ------ | ---- | ---- |
| value | string | Yes | String bound to the target component using the **key(value: string)**.|
**Return value**
| Type| Description|
| ------- | ---- |
| boolean | Returns whether the focus is successfully moved to the target component. Returns **true** if the specified component exists and the focus is successfully moved to the target component; returns **false** otherwise.|
> **NOTE**<br>
> The following components support focus control: **\<Button>**, **\<Text>**, **\<Image>**, **\<List>**, and **\<Grid>**. Currently, the running effect of the focus event can be displayed only on a real device.
## Example ## Example
The effects of focus events can only be checked on real devices. ### Example 1
defaultFocus/groupDefaultFocus/focusOnTouch:
**defaultFocus** sets the bound component as the initial focus of the page after the page is created. **groupDefaultFocus** sets the bound component as the initial focus of the **tabIndex** container after the container is created. **focusOnTouch** sets the bound component to obtain focus upon being clicked.
```ts ```ts
// xxx.ets // focusTest.ets
@Entry @Entry
@Component @Component
struct FocusableExample { struct FocusableExample {
@State text1: string = 'TabIndex=3' @State inputValue: string = ''
@State text2: string = 'TabIndex=2'
@State text3: string = 'focusable=false' build() {
@State text4: string = 'TabIndex=-1' Scroll() {
@State text5: string = 'TabIndex=1' Row({ space: 20 }) {
@State text6: string = 'TabIndex=1' Column({ space: 20 }) {
@State text7: string = 'focusable=true' Column({ space: 5 }) {
@State text8: string = 'focusable=true' Button('Group1')
.width(165)
.height(40)
.fontColor(Color.White)
.focusOnTouch(true) // The button is focusable on touch.
Row({ space: 5 }) {
Button()
.width(80)
.height(40)
.fontColor(Color.White)
Button()
.width(80)
.height(40)
.fontColor(Color.White)
.focusOnTouch(true) // The button is focusable on touch.
}
Row({ space: 5 }) {
Button()
.width(80)
.height(40)
.fontColor(Color.White)
Button()
.width(80)
.height(40)
.fontColor(Color.White)
}
}.borderWidth(2).borderColor(Color.Red).borderStyle(BorderStyle.Dashed)
.tabIndex(1) // This column is the initial component to have focus in sequential keyboard navigation.
Column({ space: 5 }) {
Button('Group2')
.width(165)
.height(40)
.fontColor(Color.White)
Row({ space: 5 }) {
Button()
.width(80)
.height(40)
.fontColor(Color.White)
Button()
.width(80)
.height(40)
.fontColor(Color.White)
.groupDefaultFocus(true) // The button obtains focus when its upper-level column is in focus.
}
Row({ space: 5 }) {
Button()
.width(80)
.height(40)
.fontColor(Color.White)
Button()
.width(80)
.height(40)
.fontColor(Color.White)
}
}.borderWidth(2).borderColor(Color.Green).borderStyle(BorderStyle.Dashed)
.tabIndex(2) // This column is the second component to have focus in sequential keyboard navigation.
}
Column({ space: 5 }) {
TextInput({placeholder: 'input', text: this.inputValue})
.onChange((value: string) => {
this.inputValue = value
})
.defaultFocus(true) // This <TextInput> component is the initial default focus of the page.
Button('Group3')
.width(165)
.height(40)
.fontColor(Color.White)
Row({ space: 5 }) {
Button()
.width(80)
.height(40)
.fontColor(Color.White)
Button()
.width(80)
.height(40)
.fontColor(Color.White)
}
Button()
.width(165)
.height(40)
.fontColor(Color.White)
Row({ space: 5 }) {
Button()
.width(80)
.height(40)
.fontColor(Color.White)
Button()
.width(80)
.height(40)
.fontColor(Color.White)
}
Button()
.width(165)
.height(40)
.fontColor(Color.White)
Row({ space: 5 }) {
Button()
.width(80)
.height(40)
.fontColor(Color.White)
Button()
.width(80)
.height(40)
.fontColor(Color.White)
}
}.borderWidth(2).borderColor(Color.Orange).borderStyle(BorderStyle.Dashed)
.tabIndex(3) // This column is the third component to have focus in sequential keyboard navigation.
}.alignItems(VerticalAlign.Top)
}
}
}
```
Diagrams:
When you press the Tab button for the first time, the focus switches to the component bound to **defaultFocus**.
![defaultFocus](figures/defaultFocus.png)
When you press Tab button for the second time, the focus switches to the container that matches **tabIndex(1)** and automatically moves to the component bound to **groupDefaultFocus**.
![groupDefaultFocus1](figures/groupDefaultFocus1.png)
When you press Tab button for the third time, the focus switches to the container that matches **tabIndex(2)** and automatically moves to the component bound to **groupDefaultFocus**.
![groupDefaultFocus2](figures/groupDefaultFocus2.png)
When you press Tab button for the fourth time, the focus switches to the container that matches **tabIndex(3)** and automatically moves to the component bound to **groupDefaultFocus**.
![groupDefaultFocus3](figures/groupDefaultFocus3.png)
Click the component bound to **focusOnTouch**. The component then obtains the focus.
![focusOnTouch](figures/focusOnTouch.png)
### Example 2
Sample code for **focusControl.requestFocus**:
Use the **focusContrl.requestFocus** API to enable a specified component to obtain the focus.
```ts
// requestFocus.ets
import prompt from '@system.prompt';
@Entry
@Component
struct RequestFocusExample {
@State idList: string[] = ['A', 'B', 'C', 'D', 'E', 'F', 'LastPageId']
@State selectId: string = 'LastPageId'
build() { build() {
Column({ space:20 }){ Column({ space:20 }){
Button(this.text1) // This component is the fourth component that is focused when the Tab key is pressed. Row({space: 5}) {
.width(300).height(70).fontColor(Color.Black) Button("id: " + this.idList[0] + " focusable(false)")
.tabIndex(3) .width(200).height(70).fontColor(Color.White)
Button(this.text2) // This component is the third component that is focused when the Tab key is pressed. .key(this.idList[0])
.width(300).height(70).fontColor(Color.Black) .focusable(false)
.tabIndex(2) Button("id: " + this.idList[1])
Button(this.text3) // This component is not focusable. .width(200).height(70).fontColor(Color.White)
.width(300).height(70).fontColor(Color.Black) .key(this.idList[1])
.focusable(false) }
Button(this.text4) // This component is focusable, but cannot be reached through sequential keyboard navigation. Row({space: 5}) {
.width(300).height(70).fontColor(Color.Black) Button("id: " + this.idList[2])
.tabIndex(-1) .width(200).height(70).fontColor(Color.White)
Button(this.text5) // This component is the first component that is focused when the Tab key is pressed. .key(this.idList[2])
.width(300).height(70).fontColor(Color.Black) Button("id: " + this.idList[3])
.tabIndex(1) .width(200).height(70).fontColor(Color.White)
Button(this.text6) // This component is the second component that is focused when the Tab key is pressed. .key(this.idList[3])
.width(300).height(70).fontColor(Color.Black) }
.tabIndex(1) Row({space: 5}) {
Button(this.text7) // This component is the fifth component that is focused when the Tab key is pressed. Button("id: " + this.idList[4])
.width(300).height(70).fontColor(Color.Black) .width(200).height(70).fontColor(Color.White)
.focusable(true) .key(this.idList[4])
Button(this.text8) // This component is the sixth component that is focused when the Tab key is pressed. Button("id: " + this.idList[5])
.width(300).height(70).fontColor(Color.Black) .width(200).height(70).fontColor(Color.White)
.focusable(true) .key(this.idList[5])
}
Row({space: 5}) {
Select([{value: this.idList[0]},
{value: this.idList[1]},
{value: this.idList[2]},
{value: this.idList[3]},
{value: this.idList[4]},
{value: this.idList[5]},
{value: this.idList[6]}])
.value(this.selectId)
.onSelect((index: number) => {
this.selectId = this.idList[index]
})
Button("RequestFocus")
.width(200).height(70).fontColor(Color.White)
.onClick(() => {
var res = focusControl.requestFocus(this.selectId) // Enable the component selected by this.selectId to obtain the focus.
if (res) {
prompt.showToast({message: 'Request success'})
} else {
prompt.showToast({message: 'Request failed'})
}
})
}
}.width('100%').margin({ top:20 }) }.width('100%').margin({ top:20 })
} }
} }
``` ```
![focus](figures/focus.png) Diagrams:
\ No newline at end of file
Press the Tab button to activate the focus state.
Request focus for a component that does not exist.
![requestFocus1](figures/requestFocus1.png)
Request focus for a component that is not focusable.
![requestFocus2](figures/requestFocus2.png)
Request focus for a focusable component.
![requestFocus3](figures/requestFocus3.png)
...@@ -17,9 +17,9 @@ None ...@@ -17,9 +17,9 @@ None
| Name| Type| Default Value| Description| | Name| Type| Default Value| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| linearGradient | {<br>angle?: [Angle](../../ui/ts-types.md),<br>direction?: [GradientDirection](ts-appendix-enums.md#gradientdirection),<br>colors: Array&lt;[ColorStop](../../ui/ts-types.md)&gt;<br>repeating?: boolean<br>} | - | Linear gradient.<br>**angle**: angle of the linear gradient.<br>**direction**: direction of the linear gradient. It does not take effect when **angle** is set.<br>**colors**: description of the gradient colors.<br>**repeating**: whether the colors are repeated.| | linearGradient | {<br>angle?: number \| string,<br>direction?: [GradientDirection](ts-appendix-enums.md#gradientdirection),<br>colors: Array&lt;[ColorStop](ts-basic-components-gauge.md#colorstop)&gt;,<br>repeating?: boolean<br>} | - | Linear gradient.<br>**angle**: angle of the linear gradient.<br>**direction**: direction of the linear gradient. It does not take effect when **angle** is set.<br>**colors**: description of the gradient colors.<br>**repeating**: whether the colors are repeated.|
| sweepGradient | {<br>center: Point,<br>start?: angle,<br>end?: angle,<br>colors: Array&lt;[ColorStop](../../ui/ts-types.md)&gt;<br>repeating?: boolean<br>} | - | Angle gradient.<br>**center**: center point of the angle gradient.<br>**start**: start point of the angle gradient.<br>**end**: end point of the angle gradient.<br>**colors**: description of the gradient colors.<br>**repeating**: whether the colors are repeated.| | sweepGradient | {<br>center: Point,<br>start?: number \| string,<br>end?: number \| string,<br>rotation?: number\|string,<br>colors: Array&lt;[ColorStop](ts-basic-components-gauge.md#colorstop)&gt;,<br>repeating?: boolean<br>} | - | Angle gradient.<br>**center**: center point of the angle gradient.<br>**start**: start point of the angle gradient.<br>**end**: end point of the angle gradient.<br>**rotation**: rotation angle of the angle gradient.<br>**colors**: description of the gradient colors.<br>**repeating**: whether the colors are repeated.|
| radialGradient | {<br>center: Point,<br>radius: Length,<br>colors: Array&lt;[ColorStop](../../ui/ts-types.md)&gt;<br>repeating: boolean<br>} | - | Radial gradient.<br>**center**: center point of the radial gradient.<br>**radius**: radius of the radial gradient.<br>**colors**: description of the gradient colors.<br>**repeating**: whether the colors are repeated.| | radialGradient | {<br>center: Point,<br>radius: number \| string,<br>colors: Array&lt;[ColorStop](ts-basic-components-gauge.md#colorstop)&gt;,<br>repeating?: boolean<br>} | - | Radial gradient.<br>**center**: center point of the radial gradient.<br>**radius**: radius of the radial gradient.<br>**colors**: description of the gradient colors.<br>**repeating**: whether the colors are repeated.|
## Example ## Example
......
# Grid # Grid
> **NOTE**
> **NOTE** > - The APIs of this module are supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
> >
> - This attribute is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
>
> - The column width and column gap in the grid layout are determined by the nearest parent component **GridContainer**. The component tree that uses grid attributes must contain one **GridContainer** or more. > - The column width and column gap in the grid layout are determined by the nearest parent component **GridContainer**. The component tree that uses grid attributes must contain one **GridContainer** or more.
## Required Permissions
None
## Attributes ## Attributes
| Name | Type | Default Value | Description | | Name | Type | Description |
| -------- | -------- | -------- | -------- | | ----------- | --------------------------| ----------------------------------------------- |
| useSizeType | {<br/>xs?: number \| { span: number, offset: number },<br/>sm?: number \| { span: number, offset: number },<br/>md?: number \| { span: number, offset: number },<br/>lg?: number \| { span: number, offset: number }<br/>} | - | Number of occupied columns and offset columns for a specific device width type. **span** indicates the number of occupied columns, and **offset** indicates the number of offset columns.<br/>If the value is of the number type, only the number of columns can be set. If the value is in the format of {"span": 1, "offset": 0}, both the number of occupied columns and the number of offset columns need to be set.<br/>- **xs** indicates that the device width type is **SizeType.XS**.<br/>- **sm** indicates that the device width type is **SizeType.SM**.<br/>- **md** indicates that the device width type is **SizeType.MD**.<br/>- **lg** indicates that the device width type is **SizeType.LG**. | | useSizeType | {<br>xs?: number \| { span: number, offset: number },<br>sm?: number \| { span: number, offset: number },<br>md?: number \| { span: number, offset: number },<br>lg?: number \| { span: number, offset: number }<br>} | Number of occupied columns and offset columns for a specific device width type. **span** indicates the number of occupied columns, and **offset** indicates the number of offset columns.<br>If the value is of the number type, only the number of columns can be set. If the value is in the format of {"span": 1, "offset": 0}, both the number of occupied columns and the number of offset columns need to be set.<br>- **xs** indicates that the device width type is **SizeType.XS**.<br>- **sm** indicates that the device width type is **SizeType.SM**.<br>- **md** indicates that the device width type is **SizeType.MD**.<br>- **lg** indicates that the device width type is **SizeType.LG**.|
| gridSpan | number | 1 | Default number of occupied columns, that is, the number of occupied columns when **span** in **useSizeType** is not set.<br/>> **NOTE**<br/>> If the **span** attribute is set, the component width is determined by the grid layout. | | gridSpan | number | Default number of occupied columns, that is, the number of occupied columns when **span** in **useSizeType** is not set.<br>**NOTE**<br>If the **span** attribute is set, the component width is determined by the grid layout.<br>Default value: **1**|
| gridOffset | number | 0 | Default number of offset columns, that is, the number of offset columns in the start direction of the parent component (which is also the nth column that the component is in) when **offset** in **useSizeType** is not set.<br/>> **NOTE**<br/>> 1. After this attribute is set, the horizontal layout of the current component does not follow the original layout of the parent component. Instead, it offsets along the start direction of the parent component.<br/>> 2. Offset = (Column width + Gap) x Number of columns<br/>> 3. After this attribute is set, sibling components will be arranged relatively to this component, as in the relative layout. | | gridOffset | number | Default number of offset columns, that is, the number of offset columns in the start direction of the parent component (which is also the nth column that the component is in) when **offset** in **useSizeType** is not set.<br>**NOTE**<br>- After this attribute is set, the horizontal layout of the current component does not follow the original layout of the parent component. Instead, it offsets along the start direction of the parent component.<br>- Offset = (Column width + Gap) \* Number of columns.<br>- After this attribute is set, sibling components will be arranged relatively to this component, as in the relative layout.<br>Default value: **0**|
## Example ## Example
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
@Component @Component
struct GridContainerExample1 { struct GridContainerExample1 {
build(){ build(){
GridContainer() { GridContainer() {
Row({}) { Row({}) {
...@@ -70,14 +63,14 @@ struct GridContainerExample1 { ...@@ -70,14 +63,14 @@ struct GridContainerExample1 {
} }
``` ```
**Figure 1** Device width type SM **Figure 1** Device width type SM
![en-us_image_0000001256858405](figures/en-us_image_0000001256858405.png) ![en-us_image_0000001256858405](figures/en-us_image_0000001256858405.png)
**Figure 2** Device width type MD **Figure 2** Device width type MD
![en-us_image_0000001257058415](figures/en-us_image_0000001257058415.png) ![en-us_image_0000001257058415](figures/en-us_image_0000001257058415.png)
**Figure 3** Device width type LG **Figure 3** Device width type LG
![en-us_image_0000001212378416](figures/en-us_image_0000001212378416.png) ![en-us_image_0000001212378416](figures/en-us_image_0000001212378416.png)
# Hit Test Control
Hit test control allows you to configure hit testing for components. When processing a touch event, ArkUI performs hit testing on the touch points and component area before the touch event is triggered, in order to determine the component that needs to respond to the touch event, and then distributes the touch event based on the hit test result. The **hitTestBehavior** attribute sets the behavior during hit testing. The settings will affect the hit test result of the component and thereby the subsequent touch event distribution. For details, see **HitTestMode**.
> **NOTE**
> - The APIs of this module are supported since API version 9. Updates will be marked with a superscript to indicate their earliest API version.
> - When the touch areas of nodes, for example, two nodes, in the **\<Stack>** component overlap, hit testing is performed only on the node displayed at the top layer by default. To perform hit testing on the node at the lower layer, set **hitTestBehavior** to **HitTestMode.Transparent** for the upper-layer node.
## Attributes
| Name | Type | Description |
| -------------------- | -------- | ---------------------------------------- |
| hitTestBehavior | HitTestMode | How the component behaves during hit testing.<br>Default value: **HitTestMode.Default**|
## HitTestMode
| Name | Description |
| ------------| ----------------------------------------- |
| Default | Both the node and its child node respond to the hit test of a touch event, but its sibling node is blocked from the hit test.|
| Block | The node responds to the hit test of a touch event, but its child node and sibling node are blocked from the hit test.|
| Transparent | Both the node and its child node respond to the hit test of a touch event, and its sibling node is also considered during the hit test.|
| None | The node does not respond to the hit test of a touch event, but its child node and sibling node are considered during the hit test.|
## Example
Set **hitTestBehavior** to **HitTestMode.Transparent** for the **\<Text>** component, which means that the inner-layer **\<Stack>** component is also considered during hit testing. Therefore, both the **\<Text>** and **\<Stack>** components respond to the **onTouch** event.
Set **hitTestBehavior** to **HitTestMode.Block** for the inner-layer **\<Stack>** component, which means that its child nodes and sibling node **\<Button>** are blocked from hit testing. Therefore, neither the inner-layer or out-layer **\<Button>** components respond to the **onTouch** event.
```ts
// xxx.ets
@Entry
@Component
struct HitTestBehaviorExample {
build() {
// outer stack
Stack() {
Button('outer button')
.onTouch((event) => {
console.info('outer button touched type: ' + event.type)
})
// inner stack
Stack() {
Button('inner button')
.onTouch((event) => {
console.info('inner button touched type: ' + event.type)
})
}
.width("100%").height("100%")
.hitTestBehavior(HitTestMode.Block)
.onTouch((event) => {
console.info('stack touched type: ' + event.type)
})
Text('Transparent')
.hitTestBehavior(HitTestMode.Transparent)
.width("100%").height("100%")
.onTouch((event) => {
console.info('text touched type: ' + event.type)
})
}.width(300).height(300)
}
}
```
...@@ -2,21 +2,16 @@ ...@@ -2,21 +2,16 @@
The hover effect is applied to a component in hover state. The hover effect is applied to a component in hover state.
> **NOTE** > **NOTE**
> >
> The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. > The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
None
## Attributes ## Attributes
| Name| Type| Default Value| Description| | Name | Type | Description |
| -------- | -------- | -------- | -------- | | ----------- | --------------------------------------------------| ------------------------------------------------ |
| hoverEffect | [HoverEffect](ts-appendix-enums.md#hovereffect8) | HoverEffect.Auto | Hover effect of the component in hover state.| | hoverEffect | [HoverEffect](ts-appendix-enums.md#hovereffect8) | Hover effect of the component in hover state.<br>Default value: **HoverEffect.Auto**|
## Example ## Example
......
...@@ -2,9 +2,9 @@ ...@@ -2,9 +2,9 @@
Image effects include background blur, content blur, grayscale, and much more. Image effects include background blur, content blur, grayscale, and much more.
> **NOTE** > **NOTE**
> >
> This attribute is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > The APIs of this module are supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions ## Required Permissions
...@@ -15,20 +15,19 @@ None ...@@ -15,20 +15,19 @@ None
## Attributes ## Attributes
| Name | Type | Default Value | Description | | Name | Type | Default Value| Description |
| -------- | -------- | -------- | -------- | | ----------------------------- | ------------------------------------------------------------ | ------ | ------------------------------------------------------------ |
| blur | number | - | Adds the content blur effect to the current component. The input parameter is the blur radius. The larger the radius is, the more blurred the content is. If the value is **0**, the content is not blurred. | | blur | number | - | Blur effect of the current component' content. The input parameter is the blur radius. The larger the radius is, the more blurred the content is. If the value is **0**, the content is not blurred.|
| backdropBlur | number | - | Adds the background blur effect to the current component. The input parameter is the blur radius. The larger the radius is, the more blurred the background is. If the value is **0**, the background is not blurred. | | backdropBlur | number | - | Blur effect of the current component' background. The input parameter is the blur radius. The larger the radius is, the more blurred the background is. If the value is **0**, the background is not blurred.|
| shadow | {<br/>radius: number,<br/>color?: Color \| string \| [Resource](../../ui/ts-types.md#resource-type),<br/>offsetX?: number,<br/>offsetY?: number<br/>} | - | Adds the shadow effect to the current component. The input parameters are the fuzzy radius (mandatory), shadow color (optional; gray by default), X-axis offset (optional and 0 by default), and Y-axis offset (optional; 0 by default). The offset unit is px. | | shadow | {<br>radius: number \| [Resource](ts-types.md#resource),<br>color?: Color \| string \| Resource,<br>offsetX?: number \| Resource,<br>offsetY?: number \| Resource<br>} | - | Adds the shadow effect to the current component. The input parameters are the fuzzy radius (mandatory), shadow color (optional; gray by default), x-axis offset (optional; 0 by default), and y-axis offset (optional; 0 by default). The offset unit is px.|
| grayscale | number | 0.0 | Converts the input image to grayscale. The value indicates the grayscale conversion ratio. If the input value is **1.0**, the image is converted into a grayscale image. If the input value is **0.0**, the image does not change. If the input value is between **0.0** and **1.0**, the effect changes in linear mode. The unit is percentage. The unit is percentage. | | grayscale | number | 0.0 | Converts the input image to grayscale. The value indicates the grayscale conversion ratio. If the input value is **1.0**, the image is converted into a grayscale image. If the input value is **0.0**, the image does not change. If the input value is between **0.0** and **1.0**, the effect changes in linear mode. The unit is percentage.|
| brightness | number | 1.0 | Adds a brightness to the current component. The input parameter is a brightness ratio. The value **1** indicates no effects. The value **0** indicates the complete darkness. If the value is less than **1**, the brightness decreases. If the value is greater than **1**, the brightness increases. A larger value indicates a higher brightness. | | brightness | number | 1.0 | Adds a brightness to the current component. The input parameter is a brightness ratio. The value **1** indicates no effects. The value **0** indicates the complete darkness. If the value is less than **1**, the brightness decreases. If the value is greater than **1**, the brightness increases. A larger value indicates a higher brightness.|
| saturate | number | 1.0 | Adds the saturation effect to the current component. The saturation is the ratio of the chromatic component to the achromatic component (gray) in a color. When the input value is **1**, the source image is displayed. When the input value is greater than **1**, a higher percentage of the chromatic component indicates a higher saturation. When the input value is less than **1**, a higher percentage of the achromatic component indicates a lower saturation. The unit is percentage. | | saturate | number | 1.0 | Adds the saturation effect to the current component. The saturation is the ratio of the chromatic component to the achromatic component (gray) in a color. When the input value is **1**, the source image is displayed. When the input value is greater than **1**, a higher percentage of the chromatic component indicates a higher saturation. When the input value is less than **1**, a higher percentage of the achromatic component indicates a lower saturation. The unit is percentage.|
| contrast | number | 1.0 | Adds the contrast effect to the current component. The input parameter is a contrast value. If the value is **1**, the source image is displayed. If the value is greater than **1**, a larger value indicates a higher contrast and a clearer image. If the value is less than **1**, a smaller value indicates a lower contrast is. If the value is **0**, the image becomes all gray. The unit is percentage. | | contrast | number | 1.0 | Adds the contrast effect to the current component. The input parameter is a contrast value. If the value is **1**, the source image is displayed. If the value is greater than **1**, a larger value indicates a higher contrast and a clearer image. If the value is less than **1**, a smaller value indicates a lower contrast is. If the value is **0**, the image becomes all gray. The unit is percentage.|
| invert | number | 0 | Inverts the input image. The input parameter is an image inversion ratio. The value **1** indicates complete inversion. The value **0** indicates that the image does not change. The unit is percentage. | | invert | number | 0 | Inverts the input image. The input parameter is an image inversion ratio. The value **1** indicates complete inversion. The value **0** indicates that the image does not change. The unit is percentage.|
| colorBlend<sup>8+</sup> | Color \| string \| [Resource](../../ui/ts-types.md#resource-type) | - | Adds the color blend effect to the current component. The input parameter is the blended color. | | colorBlend <sup>8+</sup> | Color \| string \| [Resource](ts-types.md#resource) | - | Adds the color blend effect to the current component. The input parameter is the blended color. |
| sepia | number | 0 | Converts the image color to sepia. The input parameter is an image inversion ratio. The value **1** indicates the image is completely sepia. The value **0** indicates that the image does not change. The unit is percentage. | | sepia | number | 0 | Converts the image color to sepia. The input parameter is an image inversion ratio. The value **1** indicates the image is completely sepia. The value **0** indicates that the image does not change. The unit is percentage.|
| hueRotate | number \| string | '0deg' | Adds the hue rotation effect to the current component. The input parameter is a rotation angle. If the input value is **0deg**, the image does not change (because the default rotation angle is **0deg**). The input parameter does not have the maximum value. If the value exceeds **360deg**, the image is rotated for one more circle. In other words, the value **370deg** has the same effect as **10deg**.| | hueRotate | number\|string | '0deg' | Adds the hue rotation effect to the current component. The input parameter is a rotation angle. |
## Example ## Example
...@@ -39,6 +38,7 @@ You can preview how this component looks on a real device. The preview is not ye ...@@ -39,6 +38,7 @@ You can preview how this component looks on a real device. The preview is not ye
@Entry @Entry
@Component @Component
struct ImageEffectsExample { struct ImageEffectsExample {
build() { build() {
Column({space: 10}) { Column({space: 10}) {
// Blur the font. // Blur the font.
...@@ -78,4 +78,4 @@ struct ImageEffectsExample { ...@@ -78,4 +78,4 @@ struct ImageEffectsExample {
} }
``` ```
<img src="figures/image-effect.png" alt="image-effect" />
# Layout Constraints # Layout Constraints
Layout constraints refer to constraints on the aspect ratio and display priority of components.
> **NOTE** > **NOTE**
> >
> This attribute is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > The APIs of this module are supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
None
## Attributes ## Attributes
| Name | Type | Description |
| Name | Type | Default Value | Description | | --------------- | ------ | ---------------------------------------- |
| -------- | -------- | -------- | -------- | | aspectRatio | number | Aspect ratio of the component. |
| aspectRatio | number | - | Aspect ratio of the current component. | | displayPriority | number | Display priority for the component in the layout container. When the space of the parent container is insufficient, the component with a lower priority is hidden.<br>**NOTE**<br>This attribute is valid only for the **\<Row>**, **\<Column>**, and **\<Flex>** (single-row) container components.|
| displayPriority | number | - | Display priority of the current component in the container. When the space of the parent container is insufficient, the component with a lower priority is hidden.<br/>**NOTE**<br/>This attribute is valid only for the **\<Row>**, **\<Column>**, and **\<Flex>** (single-row) container components. |
## Example ## Example
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
...@@ -72,11 +66,11 @@ struct AspectRatioExample { ...@@ -72,11 +66,11 @@ struct AspectRatioExample {
} }
``` ```
**Figure1** Portrait display **Figure 1** Portrait display
![en-us_image_0000001256978379](figures/en-us_image_0000001256978379.gif) ![en-us_image_0000001256978379](figures/en-us_image_0000001256978379.gif)
**Figure2** Landscape display **Figure 2** Landscape display
![en-us_image_0000001212218476](figures/en-us_image_0000001212218476.gif) ![en-us_image_0000001212218476](figures/en-us_image_0000001212218476.gif)
```ts ```ts
class ContainerInfo { class ContainerInfo {
...@@ -131,4 +125,4 @@ struct DisplayPriorityExample { ...@@ -131,4 +125,4 @@ struct DisplayPriorityExample {
``` ```
![en-us_image_0000001212058504](figures/en-us_image_0000001212058504.gif) ![en-us_image_0000001212058504](figures/en-us_image_0000001212058504.gif)
...@@ -7,21 +7,17 @@ The location attribute sets the alignment mode, layout direction, and position o ...@@ -7,21 +7,17 @@ The location attribute sets the alignment mode, layout direction, and position o
> This event is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > This event is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
None
## Attributes ## Attributes
| Name| Type| Default Value| Description| | Name| Type| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- |
| align | [Alignment](ts-appendix-enums.md#alignment) | Center | Alignment of the component content. This attribute is valid only when the values of **width** and **height** are greater than the size of the component content.| | align | [Alignment](ts-appendix-enums.md#alignment) | Alignment of the component content. This attribute is valid only when the values of **width** and **height** are greater than the size of the component content.<br>Default value: **Alignment.Center**|
| direction | [Direction](ts-appendix-enums.md#direction) | Auto | Horizontal layout of the component. For details about the options, see **Direction** enums.| | direction | [Direction](ts-appendix-enums.md#direction) | Horizontal layout of the component.<br>Default value: **Direction.Auto**|
| position | {<br>x: Length,<br>y: Length<br>} | - | Offset of the component anchor point relative to the top start edge of the parent component. The offset is expressed using absolute values. When laying out components, this attribute does not affect the layout of the parent component. It only adjusts the component position during drawing.| | position | [Position](ts-types.md#position8) | Offset of the component anchor point relative to the top start edge of the parent component. The offset is expressed using absolute values. When laying out components, this attribute does not affect the layout of the parent component. It only adjusts the component position during drawing.|
| markAnchor | {<br>x: Length,<br>y: Length<br>} | {<br>x: 0,<br>y: 0<br>} | Anchor point of the component for positioning. The top start edge of the component is used as the reference point for offset.| | markAnchor | [Position](ts-types.md#position8) | Anchor point of the component for positioning. The top start edge of the component is used as the reference point for offset.<br>Default value:<br>{<br>x: 0,<br>y: 1<br>} |
| offset | {<br>x: Length,<br>y: Length<br>} | {<br>x: 0,<br>y: 0<br>} | Coordinate offset of the relative layout. This attribute does not affect the layout of the parent component. It only adjusts the component position during drawing.| | offset | [Position](ts-types.md#position8) | Coordinate offset of the relative layout. This attribute does not affect the layout of the parent component. It only adjusts the component position during drawing.<br>Default value:<br>{<br>x: 0,<br>y: 1<br>} |
| alignRules<sup>9+</sup> | {<br>left?: { anchor: string, align: [HorizontalAlign](ts-appendix-enums.md#horizontalalign) };<br>right?: { anchor: string, align: [HorizontalAlign](ts-appendix-enums.md#horizontalalign) };<br>middle?: { anchor: string, align: [HorizontalAlign](ts-appendix-enums.md#horizontalalign) };<br>top?: { anchor: string, align: [VerticalAlign](ts-appendix-enums.md#verticalalign) };<br>bottom?: { anchor: string, align: [VerticalAlign](ts-appendix-enums.md#verticalalign) };<br>center?: { anchor: string, align: [VerticalAlign](ts-appendix-enums.md#verticalalign) }<br>} | Alignment rules relative to the container.<br>- **left**: left-aligned.<br>- **right**: right-aligned.<br>- **middle**: center-aligned.<br>- **top**: top-aligned.<br>- **bottom**: bottom-aligned.<br>- **center**: center-aligned.<br>**NOTE**<br>- **anchor**: ID of the component that functions as the anchor point.<br>- **align**: alignment mode relative to the anchor component.|
## Example ## Example
......
...@@ -2,30 +2,25 @@ ...@@ -2,30 +2,25 @@
A menu – a vertical list of items – can be bound to a component and displayed by long-pressing, clicking, or right-clicking the component. A menu – a vertical list of items – can be bound to a component and displayed by long-pressing, clicking, or right-clicking the component.
> **NOTE** > **NOTE**
> >
> The APIs of this module are supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > The APIs of this module are supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
None
## Attributes ## Attributes
| Name | Type | Default Value | Description | | Name | Type | Description |
| ---------------------------- | ---------------------------------------- | ---- | ---------------------------------- | | ---------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| bindMenu | Array<MenuItem&gt; \| [CustomBuilder](../../ui/ts-types.md)<sup>8+</sup> | - | Menu bound to the component, which is displayed when you click the component. Textual and custom menu items are supported.| | bindMenu | Array<MenuItem&gt; \| [CustomBuilder](ts-types.md#custombuilder8) | Menu bound to the component, which is displayed when you click the component. Textual and custom menu items are supported.|
| bindContextMenu<sup>8+</sup> | content: [CustomBuilder](../../ui/ts-types.md),<br>responseType: [ResponseType](ts-appendix-enums.md#responsetype8) | - | Context menu bound to the component, which is displayed when you long-press or right-click the component. Only custom menu items are supported. | | bindContextMenu<sup>8+</sup> | content: [CustomBuilder](ts-types.md#custombuilder8),<br>responseType: [ResponseType](ts-appendix-enums.md#responsetype8) | Context menu bound to the component, which is displayed when you long-press or right-click the component. Only custom menu items are supported.|
## MenuItem
- MenuItem | Name | Type | Description |
| Name | Type | Description | | ------ | ----------------------- | ----------- |
| ------ | ----------------------- | ----------- | | value | string | Menu item text. |
| value | string | Menu item text. | | action | () =&gt; void | Action triggered when a menu item is clicked.|
| action | () =&gt; void | Action triggered when a menu item is clicked.|
## Example ## Example
......
# Opacity # Opacity
> **NOTE**
>
> This attribute is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
You can set the opacity of a component. You can set the opacity of a component.
> **NOTE**
## Required Permissions >
> The APIs of this module are supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
None
## Attributes ## Attributes
| Name | Type | Default Value | Description | | Name | Type | Description |
| -------- | -------- | -------- | -------- | | ------- | ---------------------------------------- | ---------------------------------------- |
| opacity | number&nbsp;\|&nbsp;[Resource](../../ui/ts-types.md) | 1 | Opacity of a component. The value ranges from **0** to **1**. The value **1** means opaque, and **0** means completely transparent. | | opacity | number \| [Resource](ts-types.md#resource) | Opacity of a component. The value ranges from **0** to **1**. The value **1** means opaque, and **0** means completely transparent.<br>Default value: **1**|
## Example ## Example
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
......
# Overlay # Overlay
You can set overlay text for a component.
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** > **NOTE**
> This attribute is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. >
> The APIs of this module are supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
None
## Attributes ## Attributes
| Name | Type | Description |
| Name | Type | Default Value | Description | | ------- | ----------------------------- | ------------------------- |
| -------- | -------- | -------- | -------- | | overlay | value: string,<br>options?: {<br>align?: [Alignment](ts-appendix-enums.md#alignment), <br>offset?: {<br> x?: number,<br> y?: number<br> }<br>} | Overlay added to the component. The overlay has the same layout as the component.<br>Default value:<br>{<br>align: Alignment.Center,<br>offset: {0, 0}<br>} |
| overlay | title: string,<br/>options: {<br/>align?: [Alignment](ts-appendix-enums.md#alignment-enums),<br/>offset?: {x: number, y: number}<br/>} | {<br/>align: Alignment.Center,<br/>offset: {0, 0}<br/>} | Mask added to the component. The mask has the same layout as the component. |
## Example ## Example
```ts
``` // xxx.ets
@Entry @Entry
@Component @Component
struct OverlayExample { struct OverlayExample {
......
# Polymorphic Style # Polymorphic Style
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
You can set state-specific styles for components. You can set state-specific styles for components.
> **NOTE**
>
> The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
None ## Attributes
| Style| Type| Description|
| -------- | -------- | -------- |
| stateStyles | StateStyles | Styles of the component for different states.|
## Attributes ## StateStyles
| Name | Type | Default Value | Description | | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| stateStyles | StateStyles | - | Styles of a component for different states. | | normal | ()=&gt;void | No| Style of the component when being stateless.|
| pressed | ()=&gt;void | No| Style of the component in the pressed state.|
- StateStyles<sup>8+</sup> | disabled | ()=&gt;void | No| Style of the component in disabled state.|
| Name | Type | Mandatory | Default Value | Description | | focused | ()=&gt;void | No| Style of the component in focused state.|
| -------- | -------- | -------- | -------- | -------- | | clicked | ()=&gt;void | No| Style of the component in clicked state.|
| normal | ()=&gt;void | No | - | Style of the component when stateless. |
| pressed | ()=&gt;void | No | - | Style of the component in the pressed state. |
| disabled | ()=&gt;void | No | - | Style of the component in disabled state. |
## Example ## Example
```ts
``` // xxx.ets
@Entry @Entry
@Component @Component
struct StyleExample { struct StyleExample {
......
...@@ -7,40 +7,36 @@ The popup attribute defines the popup displayed when a component is clicked. ...@@ -7,40 +7,36 @@ The popup attribute defines the popup displayed when a component is clicked.
> This attribute is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > This attribute is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions ## APIs
None
| Name | Type | Description |
| ---------- | ------------------------------------- | --------------------------------------- |
## Attributes | bindPopup | show: boolean,<br>popup: PopupOptions \| CustomPopupOptions<sup>8+</sup> | Settings of the popup bound to the component.<br>**show**: whether to display the popup on the creation page by default. The default value is **false**.<br>**popup**: parameters of the popup.|
## PopupOptions
| Name| Type| Default Value| Description|
| -------- | -------- | -------- | -------- | | Name | Type | Mandatory | Description |
| bindPopup | show: boolean,<br>popup: PopupOptions \| CustomPopupOptions | - | Settings of the popup bound to the component.<br>**show**: whether to display the popup on the creation page by default. The default value is **false**.<br>**popup**: parameters of the popup.| | -------------------------| ------------------------------------------------| -----| ----------------------------------------- |
| message | string | Yes | Content of the popup message. |
| placementOnTop | boolean | No | Whether to display the popup above the component. The default value is **false**. |
- PopupOptions | arrowOffset<sup>9+</sup> | [Length](ts-types.md#length) | No | Offset of the popup arrow in the popup window. When residing above or below the popup, the arrow is offset to the left by default. When residing on the left or right side of the popup, the arrow is offset to the top by default. |
| Name| Type| Mandatory| Default Value| Description| | primaryButton | {<br>value: string,<br>action: () =&gt; void<br>} | No | Primary button.<br>**value**: text of the primary button in the popup.<br>**action**: callback for clicking the primary button.|
| -------- | -------- | -------- | -------- | -------- | | secondaryButton | {<br>value: string,<br>action: () =&gt; void<br>} | No | Secondary button.<br>**value**: text of the secondary button in the popup.<br>**action**: callback for clicking the secondary button.|
| message | string | Yes| - | Content of the popup message.| | onStateChange | (event: { isVisible: boolean }) =&gt; void | No | Callback for the popup status change event. The parameter **isVisible** indicates whether the popup is visible. |
| placementOnTop | boolean | No| false | Whether to display the popup above the component. The default value is **false**.|
| arrowOffset<sup>9+</sup> | Length | No| - | Offset of the popup arrow in the popup window. When above or below the popup, the arrow is offset to the left by default. When on the left or right side of the popup, the arrow is offset to the top by default.| ## CustomPopupOptions<sup>8+</sup>
| primaryButton | {<br>value: string,<br>action: () =&gt; void<br>} | No| - | Primary button.<br>**value**: text of the primary button in the popup.<br>**action**: callback for clicking the primary button.|
| secondaryButton | {<br>value: string,<br>action: () =&gt; void<br>} | No| - | Secondary button.<br>**value**: text of the secondary button in the popup.<br>**action**: callback for clicking the secondary button.| | Name | Type | Mandatory | Description |
| onStateChange | (isVisible: boolean) =&gt; void | No| - | Callback for the popup status change event. The parameter **isVisible** indicates whether the popup is visible.| | -------------------------| ------------------------- | ---- | ---------------------------------------------------- |
| builder | [CustomBuilder](ts-types.md#custombuilder8) | Yes | Builder of the popup content. |
- CustomPopupOptions<sup>8+</sup> | placement | [Placement](ts-appendix-enums.md#placement8) | No | Preferred position of the popup. If the set position is insufficient for holding the popup, it will be automatically adjusted.<br>Default value: **Placement.Bottom** |
| Name| Type| Mandatory| Default Value| Description| | arrowOffset<sup>9+</sup> | [Length](ts-types.md#length) | No | Offset of the popup arrow in the popup window. When residing above or below the popup, the arrow is offset to the left by default. When residing on the left or right side of the popup, the arrow is offset to the top by default. |
| -------- | -------- | -------- | -------- | -------- | | maskColor | [ResourceColor](ts-types.md#resourcecolor) | No | Color of the popup mask. |
| builder | () =&gt; any | Yes| - | Builder of the popup content.| | popupColor | [ResourceColor](ts-types.md#resourcecolor) | No | Color of the popup. |
| placement | [Placement](ts-appendix-enums.md#placement8) | No| Placement.Bottom | Preferred position of the popup. If the set position is insufficient for holding the popup, it will be automatically adjusted.| | enableArrow | boolean | No | Whether to display an arrow.<br>Since API version 9, if the location set for the popup arrow is not large enough, the arrow will not be displayed. For example, if **placement** is set to **Left** and the popup height is less than the arrow width (32 vp), the arrow will not be displayed.<br>Default value: **true**|
| arrowOffset<sup>9+</sup> | Length | No| - | Offset of the popup arrow in the popup window. When above or below the popup, the arrow is offset to the left by default. When on the left or right side of the popup, the arrow is offset to the top by default.| | autoCancel | boolean | No | Whether to automatically close the popup when an operation is performed on the page.<br>Default value: **true** |
| maskColor | [ResourceColor](../../ui/ts-types.md) | No| - | Color of the popup mask.| | onStateChange | (event: { isVisible: boolean }) =&gt; void | No | Callback for the popup status change event. The parameter **isVisible** indicates whether the popup is visible.|
| popupColor | [ResourceColor](../../ui/ts-types.md) | No| - | Color of the popup.|
| enableArrow | boolean | No| true | Whether to display an arrow.<br>Since API version 9, if the location set for the popup arrow is not large enough, the arrow will not be displayed. For example, if **placement** is set to **Left** and the popup height is less than the arrow width (32 vp), the arrow will not be displayed.|
| autoCancel | boolean | No| true | Whether to automatically close the popup when an operation is performed on the page.|
| onStateChange | (isVisible: boolean) =&gt; void | No| - | Callback for the popup status change event. The parameter **isVisible** indicates whether the popup is visible.|
## Example ## Example
......
# restoreId
The **restoreId** attribute identifies a component in distributed migration scenarios. It can be used to restore the component to a specific state on a remote device.
> **NOTE**
>
> The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
## Attributes
| Name| Type| Description|
| -------- | -------- | -------- |
| restoreId | number | ID of the component used for matching during distributed migration. This ID must be unique within an application.|
## Components with Distributed Migration Support
| Name| Initial Version| Migration Status|
| -------- | -------- | -------- |
| List | 8 | The sequence number of the item displayed on the top of the current device will be migrated to the remote device. After the migration, the item is completely displayed on the top of the remote device.|
| Grid | 9 | The sequence number of the item displayed on the top of the current device will be migrated to the remote device. After the migration, the item is completely displayed on the top of the remote device. The position of the scrollbar cannot be migrated.|
| Scroll | 9 | The absolute distance with the top edge for scrolling will be migrated. Due to layout inconsistency resulting from differences in the display specifications between devices, the migration effect may be affected.|
| TextArea | 9 | The text content and the position of the caret will be migrated.|
| TextInput | 9 | The text content and the position of the caret will be migrated.|
## Example
```ts
// xxx.ets
@Entry
@Component
struct RestoreIdExample {
private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
build() {
Column() {
List({ space: 20 }) {
ForEach(this.arr, (item) => {
ListItem() {
Text('' + item)
.width('100%')
.height(100)
.fontSize(16)
.fontColor(0xFFFFFF)
.textAlign(TextAlign.Center)
.borderRadius(10)
.backgroundColor(Color.Pink)
}
}, item => item)
}
.restoreId(1)
}
}
}
```
# Shape Clipping # Shape Clipping
Shape clipping changes the visible portion of a component through clipping or masking.
> **NOTE** > **NOTE**
> >
> This attribute is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > The APIs of this module are supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
None
## Attributes ## Attributes
| Name | Type | Default Value | Description | | Name | Type | Description |
| -------- | -------- | -------- | -------- | | -----| ------------------------------------------ | ------------------------------------ |
| clip | Shape \| boolean | false | Clip mode. The value **Shape** indicates that the current component is cropped based on the specified shape. The value **boolean** specifies whether to clip the component based on the edge outline. | | clip | [Circle](ts-drawing-components-circle.md) \| [Ellipse](ts-drawing-components-ellipse.md) \| [Path](ts-drawing-components-path.md) \| [Rect](ts-drawing-components-rect.md) \| boolean | Specifies a clip mode. The value **Shape** indicates that the current component is cropped based on the specified shape. The value **boolean** specifies whether to clip the component based on the edge outline.<br>Default value: **false**|
| mask | Shape | - | Mask of the specified shape for the current component. | | mask | [Circle](ts-drawing-components-circle.md) \| [Ellipse](ts-drawing-components-ellipse.md) \| [Path](ts-drawing-components-path.md) \| [Rect](ts-drawing-components-rect.md) | Adds a mask of the specified shape to the current component.|
## Example ## Example
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
......
...@@ -7,23 +7,18 @@ The size attributes are used to set the width, height, padding, and margin of a ...@@ -7,23 +7,18 @@ The size attributes are used to set the width, height, padding, and margin of a
> The APIs of this module are supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > The APIs of this module are supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
None
## Attributes ## Attributes
| Name| Type| Default Value| Description| | Name | Type | Description |
| -------- | -------- | -------- | -------- | | -------------- | ---------------------------------------- | ---------------------------------------- |
| width | Length | - | Width of the component. By default, the width required to fully hold the component content is used.| | width | [Length](ts-types.md#length) | Width of the component. By default, the width required to fully hold the component content is used. If the width of the component is greater than that of the parent container, the range of the parent container is drawn. |
| height | Length | - | Height of the component. By default, the height required to fully hold the component content is used.| | height | [Length](ts-types.md#length) | Height of the component. By default, the height required to fully hold the component content is used. If the height of the component is greater than that of the parent container, the range of the parent container is drawn. |
| size | {<br>width?: Length,<br>height?: Length<br>} | - | Size of the component.| | size | {<br>width?: [Length](ts-types.md#length),<br>height?: [Length](ts-types.md#length)<br>} | Size of the component. |
| padding | {<br>top?: Length,<br>right?: Length,<br>bottom?: Length,<br>left?: Length<br>} \| Length | 0 | Padding of the component.<br>When the parameter is of the **Length** type, the four paddings take effect.| | padding | [Padding](ts-types.md#padding) \| [Length](ts-types.md#length) | Padding of the component.<br>When the parameter is of the **Length** type, the four paddings take effect.<br>Default value: **0**<br>When **padding** is set to a percentage, the width of the parent container is used as the basic value.|
| margin | {<br>top?: Length,<br>right?: Length,<br>bottom?: Length,<br>left?: Length<br>}<br>\| Length | 0 | Margin of the component.<br>When the parameter is of the **Length** type, the four margins take effect.| | margin | [Margin](ts-types.md#margin)) \| [Length](ts-types.md#length) | Margin of the component.<br>When the parameter is of the **Length** type, the four margins take effect.<br>Default value: **0**<br>When **margin** is set to a percentage, the width of the parent container is used as the basic value.|
| constraintSize | {<br>minWidth?: Length,<br>maxWidth?: Length,<br>minHeight?: Length,<br>maxHeight?: Length<br>} | {<br>minWidth: 0,<br>maxWidth: Infinity,<br>minHeight: 0,<br>maxHeight: Infinity<br>} | Constraint size of the component, which is used to limit the size range during component layout. **constraintSize** takes precedence over **width** and **height**.| | constraintSize | {<br>minWidth?: [Length](ts-types.md#length),<br>maxWidth?: [Length](ts-types.md#length),<br>minHeight?: [Length](ts-types.md#length),<br>maxHeight?: [Length](ts-types.md#length)<br>} | Constraint size of the component, which is used to limit the size range during component layout. **constraintSize** takes precedence over **width** and **height**.<br>Default value:<br>{<br>minWidth: 0,<br>maxWidth: Infinity,<br>minHeight: 0,<br>maxHeight: Infinity<br>} |
| layoutWeight | number \| string | 0 | Weight of the component during layout. When the container size is determined, the layout of the component and sibling components is allocated based on the weight along the main axis. The component size setting is ignored.<br>> **NOTE**<br>> This attribute is valid only for the **Row**, **Column**, and **Flex** layouts.| | layoutWeight | number \| string | Weight of the component during layout. When the container size is determined, the layout of the component and sibling components is allocated based on the weight along the main axis. The component size setting is ignored.<br>**NOTE**<br>This attribute is valid only for the **\<Row>**, **\<Column>**, and **\<Flex>** layouts.<br>Default value: **0**|
## Example ## Example
......
# Text Style # Text Style
The text style attribute is used to set the style for text in a component.
> **NOTE**
>
> This attribute is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
The text style attributes are used to set the style for text in a component.
## Required Permissions > **NOTE**
>
None > The APIs of this module are supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Attributes ## Attributes
| Name | Type | Default Value | Description | | Name | Type | Description |
| -------- | -------- | -------- | -------- | | -----------| ---------------------------------------- | ------------------------------------ |
| fontColor | [ResourceColor](../../ui/ts-types.md) | - | Text color. | | fontColor | [ResourceColor](ts-types.md#resourcecolor) | Font color. |
| fontSize | Length&nbsp;\|&nbsp;[Resource](../../ui/ts-types.md) | - | Text size. If the value is of the number type, the unit fp is used. | | fontSize | Length \| [Resource](ts-types.md#resource) | Font size. If the value is of the number type, the unit fp is used. |
| fontStyle | [FontStyle](ts-appendix-enums.md#fontstyle) | FontStyle.Normal | Font style of the text. | | fontStyle | [FontStyle](ts-appendix-enums.md#fontstyle) | Font style.<br>Default value: **FontStyle.Normal** |
| fontWeight | number&nbsp;\|&nbsp;[FontWeight](ts-appendix-enums.md#fontweight)&nbsp;\|&nbsp;string | FontWeight.FontWeightNormal | Font weight. For the number type, the value ranges from 100 to 900, at an interval of 100. The default value is **400**. A larger value indicates a larger font weight.<br/>For common values of the **FontWeight** type, see **FontWeight** enums. | | fontWeight | number \| [FontWeight](ts-appendix-enums.md#fontweight) \| string | Font weight. For the number type, the value ranges from 100 to 900, at an interval of 100. The default value is **400**. A larger value indicates a larger font weight. The string type supports only the string of the number type, for example, 400, "bold", "bolder", "lighter", "regular", and "medium", which correspond to the enumerated values in FontWeight.<br>Default value: **FontWeight.Normal** |
| fontFamily | string&nbsp;\|&nbsp;[Resource](../../ui/ts-types.md#resource-type) | - | Font family of the text. Use commas (,) to separate multiple fonts. The priority the fonts is the sequence in which they are placed. An example value is **Arial, sans-serif**. | | fontFamily | string \| [Resource](ts-types.md#resource) | Font family. Use commas (,) to separate multiple fonts, for example, **'Arial, sans-serif'**. The priority of the fonts is the sequence in which they are placed.|
## Example ## Example
......
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
You can set the touch target for components that support universal click events, touch events, and gestures. You can set the touch target for components that support universal click events, touch events, and gestures.
> **NOTE**<br> > **NOTE**
> >
> The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. > The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
...@@ -10,20 +10,20 @@ You can set the touch target for components that support universal click events, ...@@ -10,20 +10,20 @@ You can set the touch target for components that support universal click events,
## Attributes ## Attributes
| Name| Type| Description| | Name | Type | Description |
| -------- | -------- | -------- | | -------------- | --------------------------------------------- | ----------------------------------------- |
| responseRegion | Array&lt;Rectangle&gt; \| Rectangle | One or more touch targets, including their location and size.<br>Default value:<br>{<br>x: 0,<br>y: 0,<br>width: '100%',<br>height: '100%'<br>} | | responseRegion | Array&lt;Rectangle&gt; \| Rectangle | One or more touch targets, including their location and size.<br>Default value:<br>{<br>x: 0,<br>y: 0,<br>width: '100%',<br>height: '100%'<br>} |
### Rectangle ### Rectangle
| Name| Type| Mandatory| Description| | Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- | | ------ | ----------------------------- | -----| -------------------------------- |
| x | [Length](../../ui/ts-types.md) | No| X coordinate of the touch point relative to the left edge of the component.<br>Default value: **0vp**| | x | [Length](ts-types.md#length) | No | X coordinate of the touch point relative to the left edge of the component.<br>Default value: **0vp**|
| y | [Length](../../ui/ts-types.md) | No| Y coordinate of the touch point relative to the left edge of the component.<br>Default value: **0vp**| | y | [Length](ts-types.md#length) | No | Y coordinate of the touch point relative to the left edge of the component.<br>Default value: **0vp**|
| width | [Length](../../ui/ts-types.md) | No| Width of the touch target.<br>Default value: **100%**| | width | [Length](ts-types.md#length) | No | Width of the touch target.<br>Default value: **100%**|
| height | [Length](../../ui/ts-types.md) | No| Height of the touch target.<br>Default value: **100%**| | height | [Length](ts-types.md#length) | No | Height of the touch target.<br>Default value: **100%**|
> **NOTE** > **NOTE**<br>
> >
> **x** and **y** can be set to a positive or negative percentage value. For example, when **x** is set to **'100%'**, the touch target is the offset from the right edge of the component by the component's width. When **x** is set to **'-100%'**, the touch target is the offset from the left edge of the component by the component's width. When **y** is set to **'100%'**, the touch target is the offset from the bottom edge of the component by the component's height. When **y** is set to **'-100%'**, the touch target is the offset from the top edge of the component by the component's height. > **x** and **y** can be set to a positive or negative percentage value. For example, when **x** is set to **'100%'**, the touch target is the offset from the right edge of the component by the component's width. When **x** is set to **'-100%'**, the touch target is the offset from the left edge of the component by the component's width. When **y** is set to **'100%'**, the touch target is the offset from the bottom edge of the component by the component's height. When **y** is set to **'-100%'**, the touch target is the offset from the top edge of the component by the component's height.
> >
......
# Transformation # Transformation
Transformation attributes allow you to rotate, translate, scale, or transform a component.
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** > **NOTE**
> This attribute is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. >
> The APIs of this module are supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
None
## Attributes ## Attributes
| Name | Type | Default Value | Description | | Name | Type | Description |
| -------- | -------- | -------- | -------- | | --------- | ------------------------------------------------------------------------ | ---------------------------------------- |
| rotate | {<br/>x?: number,<br/>y?: number,<br/>z?: number,<br/>angle?: Angle,<br/>centerX?: Length,<br/>centerY?: Length<br/>} | {<br/>x: 0,<br/>y: 0,<br/>z: 0,<br/>angle: 0,<br/>centerX: '50%',<br/>centerY: '50%'<br/>} | The vector (x, y, z) specifies a rotation axis. A positive angle indicates a clockwise rotation, and a negative angle indicates a counterclockwise rotation. The default value is **0**. **centerX** and **centerY** are used to set the rotation center point. | | rotate | {<br>x?: number,<br>y?: number,<br>z?: number,<br>angle?: Angle,<br>centerX?: number \| string,<br>centerY?: number \| string<br>} | Rotation axis. A positive angle indicates a clockwise rotation, and a negative angle indicates a counterclockwise rotation. The default value is **0**. **centerX** and **centerY** are used to set the rotation center point.<br>Default value:<br>{<br>x: 0,<br>y: 0,<br>z: 0,<br>angle: 0,<br>centerX: '50%',<br>centerY: '50%'<br>} |
| translate | {<br/>x?: Length,<br/>y?: Length,<br/>z? : Length<br/>} | {<br/>x: 0,<br/>y: 0,<br/>z: 0<br/>} | Translation distance along the x-, y-, and z-axis. The translation direction is determined by the positive and negative values. The default value is **0**. | | translate | {<br>x?: number \| string,<br>y?: number \| string,<br>z? : number \| string<br>} | Translation distance along the x-, y-, and z-axis. The translation direction is determined by the positive and negative values. The value cannot be a percentage.<br>Default value:<br>{<br>x: 0,<br>y: 0,<br>z: 0<br>}|
| scale | {<br/>x?: number,<br/>y?: number,<br/>z?: number,<br/>centerX?: Length,<br/>centerY?: Length<br/>} | {<br/>x: 1,<br/>y: 1,<br/>z: 1,<br/>centerX:'50%',<br/>centerY:'50%'<br/>} | Scale ratio of the x-, y-, and z-axis. The default value is **1**. **centerX** and **centerY** are used to set the scale center point. | | scale | {<br>x?: number,<br>y?: number,<br>z?: number,<br>centerX?: number \| string,<br>centerY?: number \| string<br>} | Scale ratio of the x-, y-, and z-axis. The default value is **1**. **centerX** and **centerY** are used to set the scale center point.<br>Default value:<br>{<br>x: 1,<br>y: 1,<br>z: 1,<br>centerX:'50%',<br>centerY:'50%'<br>} |
| transform | matrix: Matrix4 | - | Transformation matrix of the component. | | transform | Matrix4Transit | Transformation matrix of the component. |
## Example ## Example
```ts
``` // xxx.ets
import Matrix4 from '@ohos.matrix4' import Matrix4 from '@ohos.matrix4'
@Entry @Entry
......
...@@ -2,22 +2,15 @@ ...@@ -2,22 +2,15 @@
The visibility attribute controls whether a component is visible. The visibility attribute controls whether a component is visible.
> **NOTE** > **NOTE**
> >
> This event is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > This event is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
None
## Attributes ## Attributes
| Name | Type | Description |
| Name| Type| Default Value| Description| | ---------- | ---------------------------- | ------------------------------------------ |
| -------- | -------- | -------- | -------- | | visibility | [Visibility](ts-appendix-enums.md#visibility) | Whether the component is visible. Note that even if a component is hidden, it needs to be re-created when the page is refreshed. Therefore, you are advised to use [conditional rendering](../../ui/ts-rending-control-syntax-if-else.md) instead under scenarios where consistently high performance is required.<br>Default value: **Visibility.Visible**|
| visibility | [Visibility](ts-appendix-enums.md#visibility) | Visibility.Visible | Whether the component is visible. Note that even if a component is hidden, it needs to be re-created when the page is refreshed. Therefore, you are advised to use [conditional rendering](../../ui/ts-rending-control-syntax-if-else.md) instead under scenarios where consistently high performance is required. |
## Example ## Example
......
...@@ -2,26 +2,21 @@ ...@@ -2,26 +2,21 @@
The **zIndex** attribute sets the z-order of a component in the stacking context. The **zIndex** attribute sets the z-order of a component in the stacking context.
> **NOTE** > **NOTE**
> This attribute is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. >
> The APIs of this module are supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
None
## Attributes ## Attributes
| Name | Type | Default Value | Description | | Name| Type| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- |
| zIndex | number | 0 | Hierarchy of sibling components in a container. A larger value indicates a higher display level. | | zIndex | number | Hierarchy of sibling components in a container. A larger value indicates a higher display level.|
## Example ## Example
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
......
...@@ -2,26 +2,20 @@ ...@@ -2,26 +2,20 @@
The area change event is triggered when the component's size, position, or any other attribute that may affect its display area changes. The area change event is triggered when the component's size, position, or any other attribute that may affect its display area changes.
> **NOTE** > **NOTE**
> >
> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. > The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
None
## Events ## Events
| Name | Bubble Supported | Description | | Name | Bubbling Supported| Description |
| -------- | -------- | -------- | | ---------------------------------------- | ---- | ---------------------------------------- |
| onAreaChange(event: (oldValue: Area, newValue: Area) =&gt; void) | No | Triggered when the component area changes. For details about the **Area** type, see **Area** attributes. | | onAreaChange(event: (oldValue: Area, newValue: Area) =&gt; void) | No | Triggered when the component area changes. For details about the **Area** type, see [Area](ts-types.md#area8).|
## Example ## Example
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
......
...@@ -4,17 +4,13 @@ The visible area change event of a component refers to the change in the visual ...@@ -4,17 +4,13 @@ The visible area change event of a component refers to the change in the visual
> **NOTE** > **NOTE**
> >
> The APIs of this module are supported since API version 9. Updates will be marked with a superscript to indicate their earliest API version. > The APIs of this module are supported since API version 9. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
None
## Events ## Events
| Name| Description| | Name | Description |
| -------- | -------- | | ---------------------------------------- | ---------------------------------------- |
| onVisibleAreaChange(ratios: Array\<number>, event: (isVisible: boolean, currentRatio: number) => void) | Called when the visual area of the component changes.<br>- **ratios**: threshold array. Each threshold represents a ratio of the component's visible area (that is, the area of the component that is visible on screen) to the component's total area. This callback is invoked when the ratio of the component's visible area to its total area is greater than or less than the threshold. The value range of the threshold is [0.0, 1.0]. If the threshold set exceeds this range, the value **0.0** or **1.0** will be used.<br>- **isVisible**: indicates whether the ratio of the component's visible area to its total area is greater than the threshold. The value **true** means that the ratio is greater than the threshold, and **false** means that the ratio is less than the threshold.<br>- **currentRatio**: ratio of the component's visible area to its total area when this callback is invoked.| | onVisibleAreaChange(ratios: Array\<number>, event: (isVisible: boolean, currentRatio: number) => void) | Called when the visual area of the component changes.<br>- **ratios**: threshold array. Each threshold represents a ratio of the component's visible area (that is, the area of the component that is visible on screen) to the component's total area. This callback is invoked when the ratio of the component's visible area to its total area is greater than or less than the threshold. The value range of the threshold is [0.0, 1.0]. If the threshold set exceeds this range, the value **0.0** or **1.0** will be used.<br>- **isVisible**: indicates whether the ratio of the component's visible area to its total area is greater than the threshold. The value **true** means that the ratio is greater than the threshold, and **false** means that the ratio is less than the threshold.<br>- **currentRatio**: ratio of the component's visible area to its total area when this callback is invoked.|
......
...@@ -2,59 +2,37 @@ ...@@ -2,59 +2,37 @@
A click event is triggered when a component is clicked. A click event is triggered when a component is clicked.
> **NOTE** > **NOTE**
> >
> This event is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > The APIs of this module are supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
None
## Events ## Events
| Name | Bubbling Supported | Description | | Name | Bubbling Supported| Description |
| -------- | -------- | -------- | | ---------------------------------------- | ---- | --------------------------------- |
| onClick(callback: (event?: ClickEvent) =&gt; void) | No | Called when a click event occurs. For details about the event parameters, see **ClickEvent**. | | onClick(event: (event?: ClickEvent) =&gt; void) | No | Called when a click event occurs. For details about the event parameters, see **ClickEvent**.|
## ClickEvent ## ClickEvent
| Name | Type | Description |
| Name | Type | Description | | ------------------- | ------------------------------------ | -------------------------------------------------------- |
| -------- | -------- | -------- | | screenX | number | X coordinate of the click relative to the upper left corner of the application window. |
| screenX | number | X coordinate of the click relative to the left edge of the screen. | | screenY | number | Y coordinate of the click relative to the upper left corner of the application window. |
| screenY | number | Y coordinate of the click relative to the upper edge of the screen. | | x | number | X coordinate of the click relative to the upper left corner of the component being clicked. |
| x | number | X coordinate of the click relative to the left edge of the component being clicked. | | y | number | Y coordinate of the click relative to the upper left corner of the component being clicked. |
| y | number | Y coordinate of the click relative to the upper edge of the component being clicked. | | target<sup>8+</sup> | [EventTarget](#eventtarget8) | Target element that is clicked. |
| target<sup>8+</sup> | [EventTarget](#eventtarget8) | Target element that is clicked. | | timestamp | number | Timestamp of the event. It is interval between the time when the event is triggered and the time when the system starts, in nanoseconds.|
| timestamp | number | Timestamp of the event. |
## EventTarget<sup>8+</sup> ## EventTarget<sup>8+</sup>
| Name | Type | Description | | Name | Type | Description |
| -------- | -------- | -------- | | ---- | ------------------------- | ---------- |
| area | [Area](#area8) | Area information of the target element.| | area | [Area](ts-types.md#area8) | Area information of the target element.|
## Area<sup>8+</sup>
| Name | Type | Description |
| -------- | -------- | -------- |
| width | number | Width of the target element, in vp. |
| height | number | Height of the target element, in vp. |
| position | Position | Position of the upper left corner of the target element relative to that of the parent element. |
| globalPosition | Position | Position of the upper left corner of the target element relative to that of the page. |
## Position<sup>8+</sup>
| Name | Type | Description |
| -------- | -------- | -------- |
| x | number | X-coordinate, in vp. |
| y | number | Y-coordinate, in vp. |
## Example ## Example
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
......
...@@ -2,39 +2,46 @@ ...@@ -2,39 +2,46 @@
A drag event is triggered when a component is dragged. A drag event is triggered when a component is dragged.
> **NOTE** > **NOTE**
> >
> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. > The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
## Events
| Name | Bubbling Supported | Description | | Name | Bubbling Supported| Description |
| -------- | -------- | -------- | | ---------------------------------------- | ---- | ---------------------------------------- |
| onDragStart(callback: (event: DragEvent, extraParams?: string) =&gt;\|[Custom Builder](../../ui/ts-types.md)) | No | Triggered when the component bound to the event is dragged for the first time.<br/>- **event**: information about the drag event, including the coordinates of the item that is being dragged.<br/>- **extraParams**: additional information about the drag event. For details, see **extraParam**.<br/>Return value: object being dragged, which is used for prompts displayed when the object is dragged.<br/>A drag event can be triggered by a 150 ms long press.<br/>If the duration of a long-press gesture is set to less than or equal to 150 ms, the callback for the long-press gesture takes precedence. Otherwise, the callback for the drag event takes precedence. | | onDragStart(event: (event?: DragEvent, extraParams?: string) =&gt; [CustomBuilder](ts-types.md#custombuilder8) \| DragItemInfo) | No | Triggered when the component bound to the event is dragged for the first time.<br>- **event**: information about the drag event, including the coordinates of the item that is being dragged.<br>- **extraParams**: additional information about the drag event. For details, see extraParam.<br>Return value: object being dragged, which is used for prompts displayed when the object is dragged.<br>A drag event can be triggered by a 150 ms long press. If the duration of a long-press gesture is set to less than or equal to 150 ms, the callback for the long-press gesture takes precedence. Otherwise, the callback for the drag event takes precedence.|
| onDragEnter(callback: (event: DragEvent, extraParams?: string) =&gt; void) | No | Triggered when the dragged item enters a valid drop target.<br/>- **event**: information about the drag event, including the coordinates of the item that is being dragged.<br/>- **extraParams**: additional information about the drag event. For details, see **extraParam**.<br/>This event is valid only when the **onDrop** event is listened to. | | onDragEnter(event: (event?: DragEvent, extraParams?: string) =&gt; void) | No | Triggered when the dragged item enters a valid drop target.<br>- **event**: information about the drag event, including the coordinates of the item that is being dragged.<br>- **extraParams**: additional information about the drag event. For details, see extraParam.<br>This event is valid only when the **onDrop** event is listened to.|
| onDragMove(callback: (event: DragEvent, extraParams?: string) =&gt; void) | No | Triggered when the dragged item moves in a valid drop target.<br/>- **event**: information about the drag event, including the coordinates of the item that is being dragged.<br/>- **extraParams**: additional information about the drag event. For details, see **extraParam**.<br/>This event is valid only when the **onDrop** event is listened to. | | onDragMove(event: (event?: DragEvent, extraParams?: string) =&gt; void) | No | Triggered when the dragged item moves in a valid drop target.<br>- **event**: information about the drag event, including the coordinates of the item that is being dragged.<br>- **extraParams**: additional information about the drag event. For details, see extraParam.<br>This event is valid only when the **onDrop** event is listened to.|
| onDragLeave(callback: (event: DragEvent, extraParams?: string) =&gt; void) | No | Triggered when the dragged item leaves a valid drop target.<br/>- **event**: information about the drag event, including the coordinates of the item that is being dragged.<br/>- **extraParams**: additional information about the drag event. For details, see **extraParam**.<br/>This event is valid only when the **onDrop** event is listened to. | | onDragLeave(event: (event?: DragEvent, extraParams?: string) =&gt; void) | No | Triggered when the dragged item leaves a valid drop target.<br>- **event**: information about the drag event, including the coordinates of the item that is being dragged.<br>- **extraParams**: additional information about the drag event. For details, see extraParam.<br>This event is valid only when the **onDrop** event is listened to.|
| onDrop(callback: (event:DragEvent, extraParams?: string) =&gt; void) | No | Triggered when the dragged item is dropped on a valid drop target.<br/>- **event**: information about the drag event, including the coordinates of the item that is being dragged.<br/>- **extraParams**: additional information about the drag event. For details, see **extraParam**. | | onDrop(event: (event?: DragEvent, extraParams?: string) =&gt; void) | No | Triggered when the dragged item is dropped on a valid drop target.<br>- **event**: information about the drag event, including the coordinates of the item that is being dragged.<br>- **extraParams**: additional information about the drag event. For details, see extraParam.|
## DragItemInfo
- extraParam | Name | Type | Mandatory | Description |
| --------- | ---------------------------------------- | ---- | --------------------------------- |
Returns additional information required for dragging an item. | pixelMap | [PixelMap](../apis/js-apis-image.md#pixelmap7) | No | Image to be displayed during dragging. |
| builder | [CustomBuilder](ts-types.md#custombuilder8) | No | Custom building for drawing. If **pixelMap** is set, this attribute is ignored.|
**extraParam** is a string converted from a JSON object. You can obtain the following attributes using the JSON object converted from **Json.parse**. | extraInfo | string | No | Extra information of the dragged item. |
| Name | Type | Description |
| -------- | -------- | -------- | ## extraParam
| selectedIndex | number | Index of the dragged item in the parent container. The value of **selectedIndex** starts from **0**.<br/>This attribute is valid only in the **\<ListItem>** component. |
| insertIndex | number | Index of the element into which the dragged item is dropped in the **List** component. The value of **insertIndex** starts from **0**.<br/>This attribute is valid only in the drag event of the **\<List>** component. |
Provides additional information required for dragging an item.
**extraParam** is a string converted from a JSON object. You can obtain the following attributes using the JSON object converted from **Json.parse**.
### DragEvent | Name | Type | Description |
| ------------- | ------ | ---------------------------------------- |
| selectedIndex | number | Index of the dragged item in the parent container. The value of **selectedindex** starts from **0**.<br>This attribute is valid only in the **ListItem** component.|
| insertIndex | number | Index of the element into which the dragged item is dropped in the **List** component. The value of **insertIndex** starts from **0**.<br>This attribute is valid only in the drag event of the **List** component.|
| Name | Return Value Type | Description | ## DragEvent
| -------- | -------- | -------- |
| getX() | number | X-coordinate of the item that is being dragged, in vp. |
| getY() | number | Y-coordinate of the item that is being dragged, in vp. |
| Sample Code | Return Value Type | Description |
| ------ | ------ | ---------------- |
| getX() | number | X-coordinate of the item that is being dragged, in vp.|
| getY() | number | Y-coordinate of the item that is being dragged, in vp.|
## Example ## Example
......
...@@ -2,42 +2,30 @@ ...@@ -2,42 +2,30 @@
A key event is triggered when a component interacts with a keyboard, remote control, or any other input device with keys. A key event is triggered when a component interacts with a keyboard, remote control, or any other input device with keys.
> **NOTE** > **NOTE**
> >
> This event is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > The APIs of this module are supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
None
## Events ## Events
| Name | Bubbling Supported | Description | | Name | Bubbling Supported| Description |
| -------- | -------- | -------- | | ---------------------------------------- | ---- | ---------------------------------------- |
| onKeyEvent(event: (event?: KeyEvent) =&gt; void) | Yes | Called when a key event occurs. For details about **event**, see [KeyEvent](#keyevent). | | onKeyEvent(event: (event?: KeyEvent) =&gt; void) | Yes | Triggered when a key event occurs. For details about **event**, see [KeyEvent](#keyevent).|
## KeyEvent ## KeyEvent
- Attributes | Name | Type | Description |
| Name | Type | Description | | ------------------------------------- | ---------------------------------------- | -------------------------- |
| ------------------------------------- | --------------------------- | -------------------------- | | type | [KeyType](ts-appendix-enums.md#keytype) | Key type. |
| type | [KeyType](ts-appendix-enums.md#keytype) | Type of a key. | | [keyCode](../apis/js-apis-keycode.md) | number | Key code. |
| [keyCode](../apis/js-apis-keycode.md) | number | Key code. | | keyText | string | Key value. |
| keyText | string | Key value. | | keySource | [KeySource](ts-appendix-enums.md#keysource) | Type of the input device that triggers the key event. |
| keySource | [KeySource](ts-appendix-enums.md#keysource) | Type of the input device that triggers the key event. | | deviceId | number | ID of the input device that triggers the key event. |
| deviceId | number | ID of the input device that triggers the key event. | | metaKey | number | State of the metakey when the key is pressed. The value **1** means the pressed state, and **0** means the unpressed state.|
| metaKey | number | State of the metakey when the key is pressed. The value **1** means the pressed state, and **0** means the unpressed state. | | timestamp | number | Timestamp when the key is pressed. |
| timestamp | number | Timestamp when the key is pressed. | | stopPropagation | () => void | Stops the event from bubbling upwards or downwards. |
- APIs
| Name | Description |
| -------- | -------- |
| stopPropagation(): void | Stops the event from bubbling upwards or downwards. |
## Example ## Example
......
# Show/Hide Event # Show/Hide Event
The show/hide event is triggered when a component is mounted or unmounted from the component tree. A component appears when mounted to the component tree and disappears when unmounted from the component tree.
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** > **NOTE**
> This method is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. >
> The APIs of this module are supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
None
## Events ## Events
| Name | Bubble Supported | Description | | Name | Bubbling Supported| Description |
| -------- | -------- | -------- | | ------------------------------------------------ | -------- | -------------------------- |
| onAppear(callback: () =&gt; void) | No | Called when the component is displayed. | | onAppear(event: () =&gt; void) | No | Triggered when the component is displayed.|
| onDisappear(callback: () =&gt; void) | No | Called when the component disappears. | | onDisappear(event: () =&gt; void) | No | Triggered when the component disappears.|
## Example ## Example
```ts
``` // xxx.ets
import prompt from '@system.prompt' import prompt from '@system.prompt'
@Entry @Entry
......
...@@ -7,45 +7,36 @@ A touch event is triggered when a finger is pressed, slides, or is lifted from a ...@@ -7,45 +7,36 @@ A touch event is triggered when a finger is pressed, slides, or is lifted from a
> This event is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > This event is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
None
## Events ## Events
| Name | Bubbling Supported| Description | | Name | Bubbling Supported| Description |
| ---------------------------------------- | ---- | ---------------------------------------- | | ------------------------------------------------------------ | -------- | ------------------------------------------------------------ |
| onTouch(callback:&nbsp;(event?:&nbsp;TouchEvent)&nbsp;=&gt;&nbsp;void) | Yes | Invoked when a touch action is triggered. For details about **event**, see [TouchEvent](#touchevent).| | onTouch(event: (event?: TouchEvent) =&gt; void) | Yes | Invoked when a touch action is triggered. For details about **event**, see [TouchEvent](#touchevent).|
## TouchEvent ## TouchEvent
- Attributes | Name | Type | Description |
| Name | Type | Description | | ------------------- | ---------------------------------------- | ------------ |
| ------------------- | ---------------------------------------- | ------------ | | type | [TouchType](ts-appendix-enums.md#touchtype) | Type of the touch event. |
| type | [TouchType](ts-appendix-enums.md#touchtype) | Type of the touch event. | | touches | Array&lt;[TouchObject](#touchobject)&gt; | All finger information. |
| touches | Array&lt;[TouchObject](#touchobject)&gt; | All finger information. | | changedTouches | Array&lt;[TouchObject](#touchobject)&gt; | Finger information changed.|
| changedTouches | Array&lt;[TouchObject](#touchobject)&gt; | Finger information changed.| | stopPropagation | () => void | Stops the event from bubbling upwards or downwards.|
| timestamp | number | Timestamp of the event. | | timestamp<sup>8+</sup> | number | Timestamp of the event. It is interval between the time when the event is triggered and the time when the system starts, in nanoseconds.|
| target<sup>8+</sup> | [EventTarget](ts-universal-events-click.md#eventtarget8) | Target of the event. | | target<sup>8+</sup> | [EventTarget](ts-universal-events-click.md) | Display area of the element that triggers the gesture event.|
| source<sup>8+</sup> | [SourceType](ts-gesture-settings.md) | Event input device.|
- APIs
| Name | Description |
| ---------------------- | ------- |
| stopPropagation(): void| Stops the event from bubbling upwards or downwards.|
## TouchObject ## TouchObject
| Name | Type | Description |
| ------- | --------------------------- | ------------------- | | Name | Type | Description |
| type | [TouchType](ts-appendix-enums.md#touchtype) | Type of the touch event. | | ------- | ------------------------------------------- | ------------------------------------- |
| id | number | Unique identifier of a finger. | | type | [TouchType](ts-appendix-enums.md#touchtype) | Type of the touch event. |
| screenX | number | X-coordinate of the touch point relative to the left edge of the screen. | | id | number | Unique identifier of a finger. |
| screenY | number | Y-coordinate of the touch point relative to the upper edge of the device screen. | | screenX | number | X coordinate of the touch point relative to the upper left corner of the application window. |
| x | number | X-coordinate of the touch point relative to the left edge of the element being touched. | | screenY | number | Y coordinate of the touch point relative to the upper left corner of the application window. |
| y | number | Y-coordinate of the touch point relative to the upper edge of the element being touched. | | x | number | X coordinate of the touch point relative to the upper left corner of the component being touched.|
| y | number | Y coordinate of the touch point relative to the upper left corner of the component being touched.|
## Example ## Example
......
# Focus Event # Focus Event
A focus event is triggered when the page focus moves between components. It can be used to change the content of a component.
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** > **NOTE**
> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. >
> - The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
> - Currently, only the Tab button and arrow buttons on the external keyboard can be used to trigger the focus event.
## Required Permissions
None
## Events ## Events
| **Name** | **Bubble Supported** | **Description** | | Name | Bubbling Supported| Description |
| -------- | -------- | -------- | | ---------------------------------------- | -------- | --------------- |
| onFocus(callback: () =&gt; void) | No | Triggered when the current component obtains focus. | | onFocus(event: () =&gt; void) | No | Triggered when the current component obtains focus.|
| onBlur(callback:() =&gt; void) | No | Triggered when the current component loses focus. | | onBlur(event:() =&gt; void) | No | Triggered when the current component loses focus.|
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** > **NOTE**
> The following components support focus events: **&lt;Button&gt;**, **&lt;Text&gt;**, **&lt;Image&gt;**, **&lt;List&gt;**, and **&lt;Grid&gt;**. >
> The following components support focus events: **\<Button>**, **\<Text>**, **\<Image>**, **\<List>**, and **\<Grid>**.
## Example ## Example
```ts
``` // xxx.ets
@Entry @Entry
@Component @Component
struct FocusEventExample { struct FocusEventExample {
......
...@@ -2,35 +2,33 @@ ...@@ -2,35 +2,33 @@
If an action triggers multiple events, the order of these events is fixed. By default, mouse events are transmitted transparently. If an action triggers multiple events, the order of these events is fixed. By default, mouse events are transmitted transparently.
> **NOTE** > **NOTE**
> >
> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. > The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
None
## Events ## Events
| Name | Bubbling Supported | Description | | Name | Bubbling Supported| Description |
| -------- | -------- | -------- | | ------------------------------------------------------------ | -------- | ------------------------------------------------------------ |
| onHover(callback: (isHover?: boolean) =&gt; void) | No | Triggered when the mouse cursor enters or leaves the component.<br/>**isHover**: whether the mouse cursor hovers over the component. The value **true** means that the mouse cursor enters the component, and the value **false** means that the mouse cursor leaves the component. | | onHover(event: (isHover?: boolean) =&gt; void) | No | Triggered when the mouse cursor enters or leaves the component.<br>**isHover**: whether the mouse cursor hovers over the component. The value **true** means that the mouse cursor enters the component, and the value **false** means that the mouse cursor leaves the component.|
| onMouse(callback: (event?: MouseEvent) =&gt; void) | Yes | Triggered when the component is clicked by a mouse button or the mouse cursor moves on the component. The **event** parameter indicates the timestamp, mouse button, action, coordinates of the clicked point on the entire screen, and coordinates of the clicked point relative to the component when the event is triggered. | | onMouse(event: (event?: MouseEvent) =&gt; void) | Yes | Triggered when the component is clicked by a mouse button or the mouse cursor moves on the component. The **event** parameter indicates the timestamp, mouse button, action, coordinates of the clicked point on the entire screen, and coordinates of the clicked point relative to the component when the event is triggered.|
## MouseEvent ## MouseEvent
| Name | Type | Description | | Name | Type | Description |
| -------- | -------- | -------- | | --------- | ------------------------------- | -------------------- |
| timestamp | number | Timestamp when the event is triggered. | | screenX | number | X coordinate of the click point relative to the upper left corner of the application window.|
| screenX | number | X-coordinate of the clicked point relative to the upper left corner of the screen. | | screenY | number | Y coordinate of the click point relative to the upper left corner of the application window.|
| screenY | number | Y-coordinate of the clicked point relative to the upper left corner of the screen. | | x | number | X coordinate of the click point relative to the upper left corner of the component being clicked.|
| x | number | X-coordinate of the clicked point relative to the upper left corner of the component. | | y | number | Y coordinate of the click point relative to the upper left corner of the component being clicked.|
| y | number | Y-coordinate of the clicked point relative to the upper left corner of the component. | | button | [MouseButton](ts-appendix-enums.md#mousebutton) | Mouse button. |
| button | [MouseButton](ts-appendix-enums.md#mousebutton) | Mouse button. | | action | [MouseAction](ts-appendix-enums.md#mouseaction) | Event action. |
| action | [MouseAction](ts-appendix-enums.md#mouseaction) | Event action. | | stopPropagation | () => void | Stops the event from bubbling upwards or downwards. |
| timestamp<sup>8+</sup> | number | Timestamp of the event. It is interval between the time when the event is triggered and the time when the system starts, in nanoseconds. |
| target<sup>8+</sup> | [EventTarget](ts-universal-events-click.md) | Display area of the component that triggers the event.|
| source<sup>8+</sup> | [SourceType](ts-gesture-settings.md) | Event input device. |
## Example ## Example
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册