提交 9d852a92 编写于 作者: E ester.zhou 提交者: Gitee

Merge branch 'OpenHarmony-3.1-Release' of gitee.com:openharmony/docs into C1-1018

Signed-off-by: Nester.zhou <ester.zhou@huawei.com>
......@@ -256,12 +256,12 @@ zh-cn/application-dev/reference/apis/js-apis-hidebug.md @zengyawen
zh-cn/application-dev/reference/apis/js-apis-hilog.md @zengyawen
zh-cn/application-dev/reference/apis/js-apis-hitracechain.md @zengyawen
zh-cn/application-dev/reference/apis/js-apis-hitracemeter.md @zengyawen
zh-cn/application-dev/reference/apis/js-apis-inputmethod.md @sun-yue14
zh-cn/application-dev/reference/apis/js-apis-inputmethodengine.md @sun-yue14
zh-cn/application-dev/reference/apis/js-apis-inputmethod.md @ge-yafang
zh-cn/application-dev/reference/apis/js-apis-inputmethodengine.md @ge-yafang
zh-cn/application-dev/reference/apis/js-apis-pasteboard.md @ge-yafang
zh-cn/application-dev/reference/apis/js-apis-screen-lock.md @sun-yue14
zh-cn/application-dev/reference/apis/js-apis-system-time.md @sun-yue14
zh-cn/application-dev/reference/apis/js-apis-wallpaper.md @sun-yue14
zh-cn/application-dev/reference/apis/js-apis-screen-lock.md @ge-yafang
zh-cn/application-dev/reference/apis/js-apis-system-time.md @ge-yafang
zh-cn/application-dev/reference/apis/js-apis-wallpaper.md @ge-yafang
zh-cn/application-dev/reference/apis/js-apis-timer.md @HelloCrease
zh-cn/application-dev/reference/apis/js-apis-battery-info.md @sun-yue14
zh-cn/application-dev/reference/apis/js-apis-brightness.md @sun-yue14
......
# Development References
- [JavaScript-based Web-like Development Paradigm](arkui-js/Readme-EN.md)
- [Component Reference (ArkTS-based Declarative Development Paradigm)](arkui-ts/Readme-EN.md)
- [TypeScript-based Declarative Development Paradigm](arkui-ts/Readme-EN.md)
- APIs
- [JS and TS APIs](apis/Readme-EN.md)
- Native APIs
- [Standard Libraries](native-lib/third_party_libc/musl.md)
- [Component Reference (JavaScript-compatible Web-like Development Paradigm)](arkui-js/Readme-EN.md)
- [API Reference (JS and TS APIs)](apis/Readme-EN.md)
- API Reference (Native APIs)
- [Standard Libraries Supported by Native APIs](native-lib/third_party_libc/musl.md)
- [Node_API](native-lib/third_party_napi/napi.md)
......
# JavaScript-based Web-like Development Paradigm
# JavaScript-compatible Web-like Development Paradigm
- Universal Component Information
- [Universal Attributes](js-components-common-attributes.md)
......
# picker
> **NOTE**
>
> This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version.
The **\<picker>** component supports common, date, time, data and time, and multi-column text selectors.
## Required Permissions
None
## Child Component
None
## Child Components
## Attributes
Not supported
In addition to the attributes in [Universal Attributes](js-components-common-attributes.md), the following attributes are supported.
## Attributes
In addition to the [universal attributes](../arkui-js/js-components-common-attributes.md), the following attributes are supported.
| Name | Type | Default Value | Mandatory | Description |
| ---- | ------ | ------------- | --------- | ------------------------------------------------------------ |
| type | string | - | No | Dynamic modification is not supported. Available values include:<br/>-**text**: text selector<br/>-**data**: date selector<br/>-**time**: time selector<br/>-**datetime**: date and time selector<br/>-**multi-text**: multi-column text selector |
### Text Selector
| ---- | ------ | ---- | ---- | ---------------------------------------- |
| type | string | - | No | Picker type. Dynamic modification is not supported. The options are as follows:<br>- **text**: text selector.<br>- **date**: date selector.<br>- **time**: time selector.<br>- **datetime**: date and time selector.<br>- **multi-text**: multi-column text selector.|
When **type** is set to **text**, a text selector is used.
### Common Selector
When **type** is set to **text**, a common selector is used.
| Name | Type | Default Value | Mandatory | Description |
| -------- | ------ | ------------- | --------- | ------------------------------------------------------------ |
| range | Array | - | No | Value range of the common selector, for example, **["15", "20", "25"]**.NOTE:Use the data binding mode, for example, range = {{data}}. Declare the corresponding variable **data: ["15", "20", "25"]** in the JavaScript. |
| selected | string | 0 | No | Default value of the common selector. The value should be the index of **range**. |
| -------- | ------ | ---- | ---- | ---------------------------------------- |
| range | Array | - | No | Value range of the common selector, for example, **["15", "20", "25"]**.<br>Use the data binding mode, for example, `range = {{data}}`. Declare the corresponding variable `data: ["15", "20", "25"]` in JavaScript.|
| selected | string | 0 | No | Default value of the common selector. The value should be the index of **range**.|
| value | string | - | No | Value of the common selector. |
### Date Selector
When **type** is set to **date**, a date selector is used.
| Name | Type | Default Value | Mandatory | Description |
| ----------- | ------- | ------------- | --------- | ------------------------------------------------------------ |
| start | \<time> | 1970-1-1 | No | Start date of the date selector, in the format of YYYY-MM-DD. |
| end | \<time> | 2100-12-31 | No | End date of the date selector, in the format of YYYY-MM-DD. |
| selected | string | Current date | No | Default value of the date selector, in format of YYYY-MM-DD. |
| ------------------ | ------------ | ---------- | ---- | ---------------------------------------- |
| start | &lt;time&gt; | 1970-1-1 | No | Start date of the date selector, in the format of YYYY-MM-DD. |
| end | &lt;time&gt; | 2100-12-31 | No | End date of the date selector, in the format of YYYY-MM-DD. |
| selected | string | Current date | No | Default value of the date selector, in format of YYYY-MM-DD.|
| value | string | - | Yes | Value of the date selector. |
| lunar5+ | boolean | false | No | Whether the pop-up window displays the lunar calendar. |
| lunarswitch | boolean | false | No | Whether the date selector displays the lunar calendar switch, which is used to switch between the Gregorian calendar and lunar calendar. The value **true** means to display the lunar calendar switch for users to switch between the Gregorian calendar and lunar calendar. The value **false** means not to display the lunar calendar switch.NOTE:When both **lunarswitch** and **lunar** are set to **true**, the switch is selected. |
| lunar<sup>5+</sup> | boolean | false | No | Whether the pop-up window displays the lunar calendar. |
| lunarswitch | boolean | false | No | Whether the date selector displays the lunar calendar switch, which is used to switch between the Gregorian calendar and lunar calendar. The value **true** means to display the lunar calendar switch for users to switch between the Gregorian calendar and lunar calendar. The value **false** means not to display the lunar calendar switch.<br>When both **lunarswitch** and **lunar** are set to **true**, the switch is selected.|
### Time Selector
When **type** is set to **time**, a time selector is used.
| Name | Type | Default Value | Mandatory | Description |
| ------------- | ------- | ------------- | --------- | ------------------------------------------------------------ |
| ------------- | ------- | ----------------------------------- | ---- | ---------------------------------------- |
| containsecond | boolean | false | No | Whether seconds are contained. |
| selected | string | Current time | No | Default value of the time selector, in the format of HH:mm. If seconds are contained, the format is HH:mm:ss. |
| selected | string | Current time | No | Default value of the time selector, in format of HH:mm. If seconds are contained, the format is HH:mm:ss. |
| value | string | - | No | Value of the time selector. |
| hours | number | 241-4-5+ | No | Time format used by the time selector. Available values include:<br/>-**12**: displayed in 12-hour format and distinguished by a.m. and p.m.<br/>-**24**: displayed in 24-hour formatNOTE:The default value is the most commonly-used hour format in the current locale. 5+ |
| hours | number | 24<sup>1-4</sup><br>-<sup>5+</sup> | No | Time format used by the time selector. Available values are as follows:<br>- **12**: displayed in 12-hour format and distinguished by a.m. and p.m.<br>- **24**: displayed in 24-hour format.<br>Since API version 5, the default value is the most commonly-used hour format in the current locale.|
### Date and Time Selector
When **type** is set to **datetime**, a date and time selector is used.
| Name | Type | Default Value | Mandatory | Description |
| ----------- | ------- | --------------------- | --------- | ------------------------------------------------------------ |
| selected | string | Current date and time | No | Default value of the date and time selector. The value can be in either of the following formats:<br/>-MM-DD-HH-mm<br/>-YYYY-MM-DD-HH-mmIf the year is not set, the current year is used by default. <br/>-The value you set is the date selected by default in the pop-up window. |
| ------------------ | ------- | ----------------------------------- | ---- | ---------------------------------------- |
| selected | string | Current date and time | No | Default value of the date and time selector. The value can be in either of the following formats:<br>- MM-DD-HH-mm<br>- YYYY-MM-DD-HH-mm<br>If the year is not set, the current year is used by default. The value you set is the date selected by default in the pop-up window.|
| value | string | - | Yes | Value of the date and time selector. |
| hours | number | 241-4-5+ | No | Time format used by the date and time selector. Available values include:<br/>-**12**: displayed in 12-hour format and distinguished by a.m. and p.m.<br/>-**24**: displayed in 24-hour format<br/>NOTE:The default value is the most commonly-used hour format in the current locale. 5+ |
| lunar5+ | boolean | false | No | Whether the pop-up window displays the lunar calendar. |
| lunarswitch | boolean | false | No | Whether the date selector displays the lunar calendar switch, which is used to switch between the Gregorian calendar and lunar calendar. The value **true** means to display the lunar calendar switch for users to switch between the Gregorian calendar and lunar calendar. The value **false** means not to display the lunar calendar switch.NOTE:When both **lunarswitch** and **lunar** are set to **true**, the switch is selected. |
| hours | number | 24<sup>1-4</sup><br>-<sup>5+</sup> | No | Time format used by the date and time selector. Available values are as follows:<br>- **12**: displayed in 12-hour format and distinguished by a.m. and p.m.<br>- **24**: displayed in 24-hour format.<br>Since API version 5, the default value is the most commonly-used hour format in the current locale.|
| lunar<sup>5+</sup> | boolean | false | No | Whether the pop-up window displays the lunar calendar. |
| lunarswitch | boolean | false | No | Whether the date selector displays the lunar calendar switch, which is used to switch between the Gregorian calendar and lunar calendar. The value **true** means to display the lunar calendar switch for users to switch between the Gregorian calendar and lunar calendar. The value **false** means not to display the lunar calendar switch.<br>When both **lunarswitch** and **lunar** are set to **true**, the switch is selected.|
### Multi-Column Text Selector
When **type** is set to **multi-text**, a multi-column text selector is used.
| Name | Type | Default Value | Mandatory | Description |
| -------- | --------------------- | ------------- | --------- | ------------------------------------------------------------ |
| -------- | ------- | --------- | ---- | ---------------------------------------- |
| columns | number | - | Yes | Number of columns in the multi-column text selector. |
| range | Two-dimensional array | - | No | Items of the multi-column text selector. **range** is a two-dimensional array that indicates the number of columns. Each item in the array indicates the data of each column, for example, **[["a","b"], ["c","d"]]**.NOTE:Use the data binding mode, for example, range = {{data}}. Declare the corresponding variable **data: [["a","b"], ["c","d"]]** in the JavaScript. |
| selected | Array | 0,0,0,... | No | Default value of the multi-column text selector, which is an array consisting of the indexes of the selected items in each column. |
| range | Two-dimensional array| - | No | Items of the multi-column text selector. **range** is a two-dimensional array that indicates the number of columns. Each item in the array indicates the data of each column, for example, **[["a", "b"], ["c", "d"]]**.<br>Use the data binding mode, for example, `range = {{data}}`. Declare the corresponding variable `data: ["15", "20", "25"]` in JavaScript.|
| selected | Array | [0,0,0, ...]| No | Default value of the multi-column text selector, which is an array consisting of the indexes of the selected items in each column.|
| value | Array | - | No | Value of the multi-column text selector, which is an array consisting of the values of the selected items in each column. |
## Styles
In addition to the styles in [Universal Styles](js-components-common-styles.md), the following styles are supported.
## Styles
In addition to the [universal styles](../arkui-js/js-components-common-styles.md), the following styles are supported.
| Name | Type | Default Value | Mandatory | Description |
| --------------- | ---------------- | ------------- | --------- | ------------------------------------------------------------ |
| text-color | \<color> | - | No | Text color of the selector. |
| font-size | \<length> | - | No | Font size of the selector. |
| allow-scale | boolean | true | No | Whether the font size changes with the system's font size settings.NOTE:If the **config-changes** tag of **fontSize** is configured for abilities in the **config.json** file, the setting takes effect without application restart. |
| letter-spacing | \<length> | 0 | No | Letter spacing of the selector. For details, see [letter-spacing](js-components-basic-text.md#section5775351116) of the **text** component. |
| text-decoration | string | - | No | Text decoration of the selector. For details, see [text-decoration](js-components-basic-text.md) of the **text** component. |
| font-style | string | normal | No | Font style of the selector. For details, see [font-style](js-components-basic-text.md) of the **text** component. |
| font-weight | number \| string | normal | No | Font weight of the selector. For details, see [font-weight](js-components-basic-text.md) of the **text** component. |
| font-family | string | sans-serif | No | Font family, in which fonts are separated by commas (,). Each font is set using a font name or font family name. The first font that exists in the system or the font specified by [Custom Font Styles](js-components-common-customizing-font.md) in the family is selected as the font for the text. |
| line-height | \<length> | 0px | No | Text line height of the selector. |
| column-height5+ | \<length> | - | No | Height of the selector option list. |
| -------------------------- | -------------------------- | ---------- | ---- | ---------------------------------------- |
| text-color | &lt;color&gt; | - | No | Text color of the selector. |
| font-size | &lt;length&gt; | - | No | Font size of the selector. |
| allow-scale | boolean | true | No | Whether the font size changes with the system's font size settings.<br>If the **config-changes** tag of **fontSize** is configured for abilities in the **config.json** file, the setting takes effect without application restart.|
| letter-spacing | &lt;length&gt; | 0 | No | Letter spacing of the selector. For details, see **letter-spacing** in the **[\<text>](../arkui-js/js-components-basic-text.md#styles)** component.|
| text-decoration | string | - | No | Text decoration of the selector. For details, see **text-decoration** in the **[\<text>](../arkui-js/js-components-basic-text.md#styles)** component.|
| font-style | string | normal | No | Font style of the selector. For details, see **font-style** in the **[\<text>](../arkui-js/js-components-basic-text.md#styles)** component.|
| font-weight | number \| string | normal | No | Font weight of the selector. For details, see **font-weight** in the **[\<text>](../arkui-js/js-components-basic-text.md#styles)** component.|
| font-family | string | sans-serif | No | Font family, in which fonts are separated by commas (,). Each font is set using a font name or font family name. The first font in the family or the specified [custom font](../arkui-js/js-components-common-customizing-font.md) is used for the text.|
| line-height | &lt;length&gt; | 0px | No | Text line height of the selector. |
| column-height<sup>5+</sup> | &lt;length&gt; | - | No | Height of the selector option list. |
## Events
In addition to the events in [Universal Events](js-components-common-events.md), the following events are supported.
### Common Selector
In addition to the [universal events](../arkui-js/js-components-common-events.md), the following events are supported.
### Common Selector
| Name | Parameter | Description |
| ------ | ------------------------------------------------ | ------------------------------------------------------------ |
| change | { newValue: newValue, newSelected: newSelected } | Triggered when a value is selected and the OK button is clicked in the displayed pop-up window. **newSelected** is the index. |
| ------ | ---------------------------------------- | ---------------------------------------- |
| change | { newValue: newValue, newSelected: newSelected } | Triggered when an item is selected and the OK button is clicked in the displayed pop-up window. **newSelected** is the index.|
| cancel | - | Triggered when the cancel button is clicked. |
### Date Selector
### Date Selector
| Name | Parameter | Description |
| ------ | -------------------------------------- | ------------------------------------------------------------ |
| change | { year: year, month: month, day: day } | Triggered when a value is selected and the OK button is clicked in the displayed pop-up window.NOTE:The value of **month** ranges from 0 (January) to 11 (December). 5+ |
| ------ | ---------------------------------------- | ---------------------------------------- |
| change | { year: year, month: month, day: day } | Triggered when an item is selected and the OK button is clicked in the displayed pop-up window.<br>The value of **month** ranges from **0** (January) to **11** (December) since API version 5.|
| cancel | - | Triggered when the cancel button is clicked. |
### Date and Time Selector
### Date and Time Selector
| Name | Parameter | Description |
| ------ | ------------------------------------------------------------ | ------------------------------------------------------------ |
| change | { year: year, month: month, day: day, hour: hour, minute: minute} | Triggered when a value is selected and the OK button is clicked in the displayed pop-up window. |
| ------ | ---------------------------------------- | ---------------------------- |
| change | { year: year, month: month, day: day, hour: hour, minute: minute} | Triggered when an item is selected and the OK button is clicked in the displayed pop-up window.|
| cancel | - | Triggered when the cancel button is clicked. |
### Time Selector
### Time Selector
| Name | Parameter | Description |
| ------ | ------------------------------------------------ | ------------------------------------------------------------ |
| change | { hour: hour, minute: minute, [second: second] } | Triggered when a value is selected and the OK button is clicked in the displayed pop-up window. If **containsecond** is set to true, value contains seconds. |
| ------ | ---------------------------------------- | ---------------------------------------- |
| change | { hour: hour, minute: minute, [second: second] } | Triggered when an item is selected and the OK button is clicked in the displayed pop-up window. If **containsecond** is set to true, value contains seconds.|
| cancel | - | Triggered when the cancel button is clicked. |
### Multi-Column Text Selector
### Multi-Column Text Selector
| Name | Parameter | Description |
| ------------ | ------------------------------------------------------------ | ------------------------------------------------------------ |
| change | { newValue: [newValue1, newValue2, newValue3, …], newSelected:[newSelected1, newSelected2, newSelected3, …] } | Triggered when an item is selected and the OK button is clicked in the displayed pop-up window.<br/>-**newValue** is an array consisting of the values of the selected items.<br/>-**newSelected** is an array consisting of the indexes of the selected items. The lengths of **newValue** and **newSelected** are the same as the length of **range**. |
| columnchange | { column: column, newValue: newValue, newSelected: newSelected } | Triggered when the value of a column in the multi-column selector changes.<br/>-**column** indicates the column whose value has changed.<br/>-**newValue** indicates the selected value.<br/>-**newSelected** indicates the index of the selected value. |
| ------------ | ---------------------------------------- | ---------------------------------------- |
| change | { newValue: [newValue1, newValue2, newValue3, …], newSelected:[newSelected1, newSelected2, newSelected3, …] } | Triggered when an item is selected and the OK button is clicked in the displayed pop-up window.<br>- **newValue** is an array consisting of the values of the selected items.<br>- **newSelected** is an array consisting of the indexes of the selected items. The lengths of **newValue** and **newSelected** are the same as the length of **range**.|
| columnchange | { column: column, newValue: newValue, newSelected: newSelected } | Triggered when the value of a column in the multi-column selector changes.<br>- **column**: column whose value has changed.<br>- **newValue**: selected value.<br>- **newSelected**: index of the selected value.|
| cancel | - | Triggered when the cancel button is clicked. |
## Methods
In addition to the methods in [Universal Methods](js-components-common-methods.md), the following events are supported.
## Methods
In addition to the [universal methods](../arkui-js/js-components-common-methods.md), the following methods are supported.
| Name | Parameter | Description |
| ---- | --------- | -------------------- |
| show | - | Displays the picker. |
| ---- | ---- | --------------- |
| show | - | Shows the picker.|
## Example Code
```
## Example
```html
<!-- xxx.hml -->
<div class="container">
<select @change="selectChange">
......@@ -177,7 +172,7 @@ In addition to the methods in [Universal Methods](js-components-common-methods.m
</option>
</select>
<picker id="picker0" type="text" value="{{textvalue}}" selected="{{textselect}}" range="{{rangetext}}" onchange="textonchange"
oncancel="textoncancel" class="pickertext" "></picker>
oncancel="textoncancel" class="pickertext"></picker>
<picker id="picker1" type="date" value="{{datevalue}}" start="2002-2-5" end="2030-6-5" selected="{{dateselect}}" lunarswitch="true"
onchange="dateonchange" oncancel="dateoncancel" class="pickerdate" show="false"></picker>
......@@ -191,6 +186,9 @@ In addition to the methods in [Universal Methods](js-components-common-methods.m
<picker id="picker4" type="multi-text" value="{{multitextvalue}}" columns="3" range="{{multitext}}" selected="{{multitextselect}}"
onchange="multitextonchange" oncancel="multitextoncancel" class="pickermuitl" show="false"></picker>
</div>
```
```css
/* xxx.css */
.container {
flex-direction: column;
......@@ -215,6 +213,9 @@ In addition to the methods in [Universal Methods](js-components-common-methods.m
margin-bottom: 50px;
font-size: 22px;
}
```
```js
// xxx.js
import router from '@system.router';
import prompt from '@system.prompt';
......@@ -287,4 +288,4 @@ export default {
}
```
![img](figures/mmmm.gif)
\ No newline at end of file
![mmmm](figures/mmmm.gif)
......@@ -2,91 +2,90 @@
The **\<div>** component is a basic container that is used as the root node of the page structure or is used to group the content.
> **NOTE**
>
> This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
None
## Child Components
Supported
## Attributes
Attributes in [Universal Attributes](js-components-common-attributes.md) are supported.
The [universal attributes](../arkui-js/js-components-common-attributes.md) are supported.
## Styles
In addition to the styles in [Universal Styles](js-components-common-styles.md), the following styles are supported.
| Name | Type | Default Value | Mandatory | Description |
| ------------------------------ | -------- | --------------- | --------- | ------------------------------------------------------------ |
| flex-direction | string | row | No | Main axis direction of the flex container. Available values are as follows:<br>- **column**: Items are placed vertically from top to bottom. <br>- **row**: Items are placed horizontally from left to right. |
| flex-wrap | string | nowrap | No | Whether flex items in the container are displayed in a single line or multiple lines. Currently, dynamic modification is not supported. Available values are as follows:<br>- **nowrap**: Items are displayed on a single axis.<br>- **wrap**: Items are displayed on multiple axes. |
| justify-content | string | flex-start | No | How items are aligned along the main axis of the current line in a flex container. Available values are as follows: <br>- **flex-start**: Items are packed towards the start row. <br>- **flex-end**: Items are packed towards the end row. <br>- **center**: Items are centered along the row. <br>- **space-between**: Items are positioned with space between the rows. <br>- **space-around**: Items are positioned with space before, between, and after the rows. <br>- **space-evenly**<sup>5+</sup>: Items are arranged with even space between each two. |
| align-items | string | stretch | No | How items are aligned along the cross axis of the current line in a flex container. Available values are as follows: <br>- **stretch**: Items are stretched to the same height or width as the container in the cross axis direction. <br>- **flex-start**: Items are aligned to the start of the cross axis. <br>- **flex-end**: Items are aligned to the end of the cross axis. <br>- **center**: Items are aligned in the middle of the cross axis. |
| align-content | string | flex-start | No | Multi-row alignment mode when there is extra space in the cross axis. Available values are as follows: <br>- **flex-start**: All rows are packed towards the start of the cross axis. The start edge of the cross axis of the first row is aligned with the start edge of the cross axis of the container. All subsequent rows are aligned with the previous row. <br>- **flex-end**: All rows are packed towards the end of the cross axis. The end of the cross axis of the last row is aligned with the end of the cross axis of the container. All subsequent rows are aligned with the previous row. <br>- **center**: All rows are packed towards the center of the container. Rows are close to each other and aligned with the center of the container. The spacing between the start of the container's cross axis and the first row is equal to the spacing between the end of the container's cross axis and the last row. <br>- **space-between**: All rows are evenly distributed in the container. The spacing between two adjacent rows is the same. The start and end edges of the container's cross axis are aligned with the edges of the first and last rows, respectively. <br>- **space-around**: All rows are evenly distributed in the container, and the spacing between two adjacent lines is the same. The spacing between the start edge of the container's cross axis and the first row and that between the end edge and the last row are half of the spacing between two adjacent rows. |
| display | string | flex | No | Type of the view box of the element. Currently, dynamic modification is not supported. Available values are as follows: <br>- **flex**: flexible layout <br>- **grid**: grid layout <br>- **none**: not rendered |
| grid-template-[columns\|rows] | string | 1 row, 1 column | No | Number of rows and columns in the current grid layout. If this attribute is not set, one row and one column are displayed by default. This attribute is valid only when **display** is set to **grid**.For example, set **grid-template-columns** to: <br>- **50px 100px 60px**: There are three columns. The first column is 50 px, the second column is 100 px, and the third column is 60 px. <br>- **1fr 1fr 2fr**: There are three columns, and the width allowed by the parent component is divided into four equal shares. The first column occupies one share, the second column occupies one share, and the third column occupies two shares. <br>- **30% 20% 50%**: There are three columns. The first column occupies 30% of the total width allowed by the parent component, the second column occupies 20%, and the third column occupies 50%. <br>- **repeat (2,100px)**: There are two columns. The first column is 100 px, and the second column is 100 px. <br>- **repeat(auto-fill,100px)**<sup>5+</sup>: Each column is 100 px and repeats to fill the cross axis. The number of columns is calculated based on the column size and the cross axis size. <br>- **auto 1fr 1fr**: There are three columns. The first column is adaptive to the width required by its child components. The remaining space is divided into two equal shares, one share occupied by each of the rest two columns. |
| grid-[columns\|rows]-gap | \<length> | 0 | No | Size of the gap between two consecutive rows or columns in a grid layout. You can also use **grid-gap** to set the same size of the gap between rows and columns. This attribute is valid only when **display** is set to **grid**. |
| grid-row-[start\|end] | number | - | No | Start and end row numbers of the current item in the grid layout. This attribute is valid only when **display** of the parent component is **grid**. (The **display** attribute of the parent component can be set to **grid** only for the **\<div>** container.) |
| grid-column-[start\|end] | number | - | No | Start and end column numbers of the current item in the grid layout. This attribute is valid only when **display** of the parent component is **grid**. (The **display** attribute of the parent component can be set to **grid** only for the **\<div>** container.) |
| grid-auto-flow<sup>5+</sup> | string | - | No | Using an algorithm to lay out the grid automatically. Available values are as follows: <br>- **row**: Elements are filled row by row. When there is no horizontal space in a row, a new row is added. <br>- **column**: Elements are filled column by column. When there is no vertical space in a column, a new column is added. |
| overflow<sup>6+</sup> | string | visible | No | Display mode when the content exceeds the container size. Available values are as follows: <br>- **visible**: Displays the extra content outside the container. <br>- **hidden**: Truncates the extra content. <br>- **scroll**: Scrolls the content vertically, with a scrollbar provided.NOTE: <br>- **overflow** works for elements whose size is fixed. |
| align-items<sup>6+</sup> | string | - | No | How items are aligned along the cross axis in a flex container. Available values are as follows: <br>- **stretch**: Items are stretched to the same height or width as the container in the cross axis direction. <br>- **flex-start**: Items are aligned to the start of the cross axis. <br>- **flex-end**: Items are aligned to the end of the cross axis. <br>- **center**: Items are aligned in the middle of the cross axis. <br>- **baseline**: In a vertical layout, items are aligned to the start of the cross axis, which means that this value is equivalent of **flex-start**. In a horizontal layout, items are aligned with the text baseline if there is text involved, and aligned to the bottom otherwise. |
| scrollbar-color<sup>6+</sup> | \<color> | - | No | Color of the scrollbar. |
| scrollbar-width<sup>6+</sup> | \<length> | - | No | Width of the scrollbar. |
| overscroll-effect<sup>6+</sup> | string | - | No | Scrolling edge effect. Available values are as follows: <br>- **spring**: Similar to the physical dynamic effect of a spring. After scrolling to the edge, you can continue to scroll for a distance based on the initial speed or by touching the knob of the scrollbar. After you release your hand, the knob is rebounded. <br>- **fade**: Similar to the physical dynamic effect of fade. When you scroll to the edge, a wave shape fades. The fade changes according to the speed and scrolling distance. <br>- **none**: No effect after the scroll bar is moved to the edge. |
## Styles
## Events
In addition to the [universal styles](../arkui-js/js-components-common-styles.md), the following styles are supported.
| Name | Type | Default Value | Mandatory| Description |
| ------------------------------ | -------------- | ------------ | ---- | ------------------------------------------------------------ |
| flex-direction | string | row | No | Main axis direction of the flex container, which defines how items are placed in the container. Available values are as follows:<br>- **column**: Items are placed vertically from top to bottom.<br>- **row**: Items are placed horizontally from left to right.|
| flex-wrap | string | nowrap | No | Whether items in the flex container are displayed in a single line or multiple lines. The value cannot be dynamically updated. Available values are as follows:<br>- **nowrap**: Flex items are displayed in a single line.<br>- **wrap**: Flex items are displayed in multiple lines.|
| justify-content | string | flex-start | No | How items are aligned along the main axis of the flex container. Available values are as follows:<br>- **flex-start**: Items are packed toward the start edge of the container along the main axis.<br>- **flex-end**: Items are packed toward the end edge of the container along the main axis.<br>- **center**: Items are packed toward the center of the container along the main axis.<br>- **space-between**: Items are positioned with space between the rows.<br>- **space-around**: Items are positioned with space before, between, and after the rows.<br>- **space-evenly**<sup>5+</sup>: Items are distributed within the container along the main axis, with even space between each two.|
| align-items | string | stretch<br>| No | How items are aligned along the cross axis of the flex container. Available values are as follows:<br>- **stretch**: Items are stretched to the same height or width as the container along the cross axis.<br>- **flex-start**: Items are packed toward the start edge of the cross axis.<br>- **flex-end**: Items are packed toward the end edge of the cross axis.<br>- **center**: Items are packed toward the center of the cross axis.<br>- **baseline**: In a vertical layout, items are aligned to the start of the cross axis, which means that this value is equivalent of **flex-start**. In a horizontal layout, items are aligned with the text baseline if there is text involved, and aligned to the bottom otherwise.|
| align-content | string | flex-start | No | Multi-row alignment mode when there is extra space in the cross axis. Available values are as follows:<br>- **flex-start**: All rows are packed toward the start edge of the cross axis. The start edge of the cross axis of the first row is aligned with the start edge of the cross axis of the container. All subsequent rows are aligned with the previous row.<br>- **flex-end**: All rows are packed toward the end edge of the cross axis. The end of the cross axis of the last row is aligned with the end of the cross axis of the container. All subsequent rows are aligned with the previous row.<br>- **center**: All rows are packed toward the center of the cross axis. Rows are close to each other and aligned with the center of the container. The spacing between the start edge of the container's cross axis and the first row is equal to the spacing between the end edge of the container's cross axis and the last row.<br>- **space-between**: All rows are evenly distributed in the container. The spacing between two adjacent rows is the same. The start and end edges of the container's cross axis are aligned with the edges of the first and last rows, respectively.<br>- **space-around**: All rows are evenly distributed in the container. The spacing between two adjacent rows is the same. The spacing between the start edge of the container's cross axis and the first row and that between the end edge and the last row are half of the spacing between two adjacent rows.|
| display | string | flex | No | Type of the view box of the item. The value cannot be dynamically updated. Available values are as follows:<br>- **flex**: flexible layout<br>- **grid**: grid layout<br>- **none**: not rendered<br>- **inline-flex**<sup>9+</sup>: layout with the **flex** and **inline-block** effects.|
| grid-template-[columns\|rows] | string | 1 row, 1 column | No | Number of rows and columns in the current grid layout. If this attribute is not set, one row and one column are displayed by default. This attribute is valid only when **display** is set to **grid**.<br>Below are some example values of **grid-template-columns**:<br>- **50px 100px 60px**: There are three columns. The first column is 50 px, the second column is 100 px, and the third column is 60 px.<br>- **1fr 1fr 2fr**: There are three columns, and the width allowed by the parent component is divided into four equal shares. The first column occupies one share, the second column occupies one share, and the third column occupies two shares.<br>- **30% 20% 50%**: There are three columns. The first column occupies 30% of the total width allowed by the parent component, the second column occupies 20%, and the third column occupies 50%.<br>- **repeat (2,100px)**: There are two columns. The first column is 100 px, and the second column is 100 px.<br>- **repeat(auto-fill,100px)**<sup>5+</sup>: Each column is 100 px and repeats to fill the cross axis. The number of columns is calculated based on the column size and the cross axis size.<br>- **auto 1fr 1fr**: There are three columns. The first column is adaptive to the width required by its child components. The remaining space is divided into two equal shares, one share occupied by each of the rest two columns.|
| grid-[columns\|rows]-gap | &lt;length&gt; | 0 | No | Size of the gap between two consecutive rows or columns in a grid layout. You can also use **grid-gap** to set the same size of the gap between rows and columns. This attribute is valid only when **display** is set to **grid**.|
| grid-row-[start\|end] | number | - | No | Start and end row numbers of the current item in the grid layout. This attribute is valid only when the item's parent component is a **\<div>** container whose **display** style is set to **grid**.|
| grid-column-[start\|end] | number | - | No | Start and end column numbers of the current item in the grid layout. This attribute is valid only when the item's parent component is a **\<div>** container whose **display** style is set to **grid**.|
| grid-auto-flow<sup>5+</sup> | string | - | No | How grid items are laid out automatically. Available values are as follows:<br>- **row**: Elements are filled row by row. When there is no horizontal space in a row, a new row is added.<br>- **column**: Elements are filled column by column. When there is no vertical space in a column, a new column is added.|
| overflow<sup>6+</sup> | string | visible | No | Display mode when the content exceeds the container size. Available values are as follows:<br>- **visible**: Displays the excess content outside the container.<br>- **hidden**: Truncates the excess content.<br>- **scroll**: Scrolls the content vertically, with a scrollbar provided.<br>**scroll** works for elements whose size is fixed. By default, the scrolling direction is the same as the container direction.|
| align-items<sup>6+</sup> | string | - | No | How items are aligned along the cross axis in a flex container. Available values are as follows:<br>- **stretch**: Items are stretched to the same height or width as the flex container along the cross axis.<br>- **flex-start**: Items are aligned to the start of the cross axis.<br>- **flex-end**: Items are aligned to the end of the cross axis.<br>- **center**: Items are aligned in the center of the cross axis.<br>- **baseline**: In a vertical layout, items are aligned to the start of the cross axis, which means that this value is equivalent of **flex-start**. In a horizontal layout, items are aligned with the text baseline if there is text involved, and aligned to the bottom otherwise.|
| scrollbar-color<sup>6+</sup> | &lt;color&gt; | - | No | Color of the scrollbar. |
| scrollbar-width<sup>6+</sup> | &lt;length&gt; | - | No | Width of the scrollbar. |
| overscroll-effect<sup>6+</sup> | string | - | No | How the scrollbar behaves when it reaches the edge of the scrolling area. Available values are as follows:<br>- **spring**: Similar to the physical dynamic effect of a spring. When the scrollbar reaches the edge, it can continue to scroll for a distance based on the initial speed or a touch event. It rebounds after being released.<br>- **fade**: Similar to the physical dynamic effect of fade. When the scrollbar reaches the edge, a wave shape fades. The fade changes according to the speed and scrolling distance.<br>- **none**: No effect when the scrollbar reaches the edge.|
In addition to the events in [Universal Events](js-components-common-events.md), the following events are supported.
## Events
In addition to the [universal events](../arkui-js/js-components-common-events.md), the following events are supported.
| Name | Parameters | Description |
| ------------- | ---------- | ------------------------------------------------------------ |
| reachstart<sup>6+</sup> | - | Triggered when the page scrolls to the beginning. This event is triggered only when **flex-direction** is **row**. |
| reachend<sup>6+</sup> | - | Triggered when the page scrolls to the end. This event is triggered only when **flex-direction** is **row**. |
| reachtop<sup>6+</sup> | - | Triggered when the page scrolls to the top. This event is triggered only when **flex-direction** is **column**. |
| reachbottom<sup>6+</sup> | - | Triggered when the page scrolls to the bottom. This event is triggered only when **flex-direction** is **column**. |
| Name | Parameter | Description |
| ------------------------ | ---- | ---------------------------------------- |
| reachstart<sup>6+</sup> | - | Triggered when the page scrolls to the beginning. This event is triggered only when **flex-direction** is **row**.|
| reachend<sup>6+</sup> | - | Triggered when the page scrolls to the end. This event is triggered only when **flex-direction** is **row**.|
| reachtop<sup>6+</sup> | - | Triggered when the page scrolls to the top. This event is triggered only when **flex-direction** is **column**.|
| reachbottom<sup>6+</sup> | - | Triggered when the page scrolls to the bottom. This event is triggered only when **flex-direction** is **column**.|
## Methods
In addition to the methods in [Universal Methods](js-components-common-methods.md), the following events are supported.
In addition to the [universal methods](js-components-common-methods.md), the following methods are supported.
| Name | Parameters | Return values | Description |
| ----------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ |
| getScrollOffset<sup>6+</sup> | - | [ScrollOffset](js-components-container-div.md#table154011838131719) | Obtains the scrolling offset of the element content.<br>NOTE:To use this method, **overflow** must be set to **scroll**. By default, the scrolling direction is the same as the container layout direction. |
| scrollBy<sup>6+</sup> | [ScrollParam](js-components-container-div.md#table1139175871819) | - | Indicates the scrolling offset of the element content.<br>NOTE:To use this method, **overflow** must be set to **scroll**. |
| Name | Parameter | Return Value | Description |
| ---------------------------- | ----------- | ------------ | --------------------------------------- |
| getScrollOffset<sup>6+</sup> | - | ScrollOffset | Obtains the scrolling offset of the element content.<br>To use this method, **overflow** must be set to **scroll**.|
| scrollBy<sup>6+</sup> | ScrollParam | - | Sets the scrolling offset of the element content.<br>To use this method, **overflow** must be set to **scroll**.|
**Table 1** ScrollOffset<sup>6+</sup>
| Name | Type | Description |
| ---- | ------ | -------------------------------------- |
| x | number | Offset in the x-axis direction, in px. |
| y | number | Offset in the y-axis direction, in px. |
| ---- | ------ | --------------- |
| x | number | Offset in the x-axis direction, in px.|
| y | number | Offset in the y-axis direction, in px.|
**Table 2** ScrollParam<sup>6+</sup>
| Name | Type | Description |
| ------ | ------- | ------------------------------------------------------------ |
| dx | number | Offset for scrolling the list in the horizontal direction, in px. |
| dy | number | Offset for scrolling the list in the vertical direction, in px. |
| ------ | ------- | ---------------- |
| dx | number | Offset for scrolling in the horizontal direction, in px.|
| dy | number | Offset for scrolling in the vertical direction, in px.|
| smooth | boolean | Whether to perform smooth processing. |
## Example
1. Flex style
```
```html
<!-- xxx.hml -->
<div class="container">
<div class="flex-box">
......@@ -97,7 +96,7 @@ In addition to the methods in [Universal Methods](js-components-common-methods.m
</div>
```
```
```css
/* xxx.css */
.container {
flex-direction: column;
......@@ -129,11 +128,10 @@ In addition to the methods in [Universal Methods](js-components-common-methods.m
}
```
![img](figures/en-us_image_0000001127285076.png)
![en-us_image_0000001127285076](figures/en-us_image_0000001127285076.png)
2. Flex wrap style
```
```html
<!-- xxx.hml -->
<div class="container">
<div class="flex-box">
......@@ -144,7 +142,7 @@ In addition to the methods in [Universal Methods](js-components-common-methods.m
</div>
```
```
```css
/* xxx.css */
.container {
flex-direction: column;
......@@ -177,11 +175,11 @@ In addition to the methods in [Universal Methods](js-components-common-methods.m
}
```
![img](figures/22.png)
![22](figures/22.png)
3. Grid style
```
```html
<!-- xxx.hml -->
<div class="common grid-parent">
<div class="grid-child grid-left-top"></div>
......@@ -191,7 +189,7 @@ In addition to the methods in [Universal Methods](js-components-common-methods.m
</div>
```
```
```css
/* xxx.css */
.common {
width: 400px;
......@@ -243,11 +241,10 @@ In addition to the methods in [Universal Methods](js-components-common-methods.m
}
```
![img](figures/11.png)
![11](figures/11.png)
4. Dragging<sup>7+</sup>
```
```html
<!-- xxx.hml -->
<div class="container">
<div class="content" ondragstart="dragstart" ondrag="drag" ondragend="dragend" style="position: absolute;left: {{left}};top:{{top}};">
......@@ -255,7 +252,7 @@ In addition to the methods in [Universal Methods](js-components-common-methods.m
</div>
```
```
```css
/* xxx.css */
.container {
flex-direction: column;
......@@ -267,7 +264,7 @@ In addition to the methods in [Universal Methods](js-components-common-methods.m
}
```
```
```js
// xxx.js
import prompt from '@system.prompt';
export default {
......@@ -292,9 +289,9 @@ In addition to the methods in [Universal Methods](js-components-common-methods.m
}
```
![img](figures/9.gif)
![9](figures/9.gif)
```
```html
<!-- xxx.hml -->
<div class="container">
<div class="content" ondrag="drag" style="position: absolute;left: {{left}};top: {{top}};"></div>
......@@ -304,7 +301,7 @@ In addition to the methods in [Universal Methods](js-components-common-methods.m
</div>
```
```
```css
/* xxx.css */
.container {
flex-direction: column;
......@@ -320,7 +317,7 @@ In addition to the methods in [Universal Methods](js-components-common-methods.m
}
```
```
```js
// xxx.js
import prompt from '@system.prompt';
export default {
......@@ -355,11 +352,10 @@ In addition to the methods in [Universal Methods](js-components-common-methods.m
}
```
![img](figures/6.gif)
![6](figures/6.gif)
5. Pinching<sup>7+</sup>
```
```html
<!-- xxx.hml -->
<div class="container">
<div class="content "onpinchstart="pinchstart" onpinchend="pinchend" onpinchupdate="pinchupdate"
......@@ -368,7 +364,7 @@ In addition to the methods in [Universal Methods](js-components-common-methods.m
</div>
```
```
```css
/* xxx.css */
.container {
flex-direction: column;
......@@ -384,7 +380,7 @@ In addition to the methods in [Universal Methods](js-components-common-methods.m
}
```
```
```js
// xxx.js
import prompt from '@system.prompt';
export default {
......@@ -411,4 +407,4 @@ In addition to the methods in [Universal Methods](js-components-common-methods.m
}
```
![img](figures/5.gif)
\ No newline at end of file
![5](figures/5.gif)
......@@ -2,70 +2,71 @@
The **\<stepper-item>** component displays a step in the step navigator. This component is the child component of **\<stepper>**.
> **NOTE**
> This component is supported since API version 5. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
None
## Child Components
Supported
## Attributes
In addition to the attributes in [Universal Attributes](js-components-common-attributes.md), the following attributes are supported.
## Attributes
| Name | Type | Default Value | Mandatory | Triggered when |
| ----- | ----- | ------------- | --------- | ------------------------------------------------------------ |
| label | Label | - | No | Button text at the bottom of the customized step navigator. Dynamic modification is not supported. If this attribute is not set, **BACK** and **NEXT** will be used by default as button text in case the system language is not Chinese. For the first step, there is no previous button. For the last step, the text on the next button is **START** for non-Chinese languages by default. |
In addition to the [universal attributes](../arkui-js/js-components-common-attributes.md), the following attributes are supported.
**Table 1** Label parameters
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| label | Label | No| Button text at the bottom of the customized step navigator. Dynamic modification is not supported. If this attribute is not set, **BACK** and **NEXT** will be used by default as button text in case the system language is not Chinese. For the first step, there is no previous button. For the last step, the text on the next button is **START** for non-Chinese languages by default.|
**Table 1** label
| Name| Type| Default Value| Description|
| -------- | -------- | -------- | -------- |
| prevLabel | string | - | Text content of the previous button at the bottom of the step navigator.|
| nextLabel | string | - | Text content of the next button at the bottom of the step navigator.|
| status | string | normal | Initial status of the current step in the step navigator. Available values are as follows:<br>- **normal**: The right button is clickable and can navigate users to the next step when it is clicked.<br>- **disabled**: The right button is grayed out and unavailable.<br>- **waiting**: The right button is not displayed, and a progress bar is displayed instead.|
| Name | Type | Default Value | Triggered when |
| --------- | ------ | ------------- | ------------------------------------------------------------ |
| prevLabel | string | - | Text content of the previous button at the bottom of the step navigator. |
| nextLabel | string | - | Text content of the next button at the bottom of the step navigator. |
| status | string | normal | Initial status of the current step in the step navigator. Available values are as follows: <br>- **normal**: The right button is clickable and can navigate users to the next step when it is clicked. <br>- **disabled**: The right button is grayed out and unavailable. <br>- **waiting**: The right button is not displayed, and a progress bar is displayed instead. |
## Styles
In addition to the styles in [Universal Styles](js-components-common-styles.md), the following styles are supported.
In addition to the [universal styles](../arkui-js/js-components-common-styles.md), the following styles are supported.
| Name| Type| Default Value| Mandatory| Description|
| -------- | -------- | -------- | -------- | -------- |
| color | &lt;color&gt; | - | No| Text color.|
| font-size | &lt;length&gt; | - | No| Text size.|
| allow-scale | boolean | true | No| Whether the font size changes with the system's font size settings.|
| font-style | string | normal | No| Text font style. Available values are as follows:<br>- **normal**: standard font style<br>- **italic**: italic font style|
| font-weight | number\|string | normal | No| Text font weight. The number value must be an exact multiple of 100 ranging from 100 to 900. The default value is 400. A larger value indicates a bigger weight. Available values of the string type are **lighter**, **normal**, **bold**, or **bolder**.|
| text-decoration | string | none | No| Text decoration. Available values are as follows:<br>- **underline**: An underline is used.<br>- **line-through**: A strikethrough is used.<br>- **none**: The standard text is used.|
| font-family | string | sans-serif | No| Font family, in which fonts are separated by commas (,). Each font is set using a font name or font family name. The first font in the family or the specified [custom font](../arkui-js/js-components-common-customizing-font.md) is used for the text.|
| Name | Type | Default Value | Mandatory | Triggered when |
| --------------- | -------------- | ------------- | --------- | ------------------------------------------------------------ |
| color | \<color> | - | No | Text color. |
| font-size | \<length> | - | No | Text size. |
| allow-scale | boolean | true | No | Whether the text size changes with the system's font size settings. |
| font-style | string | normal | No | Text font style. Available values are as follows: <br>- **normal**: standard font style <br>- **italic**: italic font style |
| font-weight | number\|string | normal | No | Text font weight. The number value must be an exact multiple of 100 ranging from 100 to 900. The default value is 400. A larger value indicates a bigger weight. Available values of the string type are **lighter**, **normal**, **bold**, or **bolder**. |
| text-decoration | string | none | No | Text decoration. Available values are as follows: <br>- **underline**: An underline is used. <br>- **line-through**: A strikethrough is used. <br>- **none**: The standard text is used. |
| font-family | string | sans-serif | No | Font family, in which fonts are separated by commas (,). Each font is set using a font name or font family name. The first font in the family or the font specified by [Custom Font Styles](js-components-common-customizing-font.md) is used for the text. |
> ![img](https://gitee.com/openharmony/docs/raw/OpenHarmony-3.1-Release/en/application-dev/public_sys-resources/icon-note.gif) **NOTE:**
>
> **NOTE**
> - Height and width styles are not supported. The width of each item is the same as that of its container. The height of each item is the difference between the container height and the bottom button height.
>
> - The **posit** style is not supported.
## Events
In addition to the events in [Universal Events](js-components-common-events.md), the following events are supported.
## Events
In addition to the [universal events](../arkui-js/js-components-common-events.md), the following events are supported.
| Name| Parameter| Description|
| -------- | -------- | -------- |
| appear | - | Triggered when this step is displayed.|
| disappear | - | Triggered when this step disappears.|
| Name | Parameter | Description |
| --------- | --------- | -------------------------------------- |
| appear | - | Triggered when this step is displayed. |
| disappear | - | Triggered when this step disappears. |
## Methods
Methods in [Universal Methods](js-components-common-methods.md) are not supported.
The [universal methods](../arkui-js/js-components-common-methods.md) are supported.
## Example
For details, see the [stepper example code](js-components-container-stepper.md).
\ No newline at end of file
For details, see **Example** in [stepper](../arkui-js/js-components-container-stepper.md).
# tab-content
**\<tab-content>** is a child component of [\<tabs>](js-components-container-tabs.md) and is used to provide the area for displaying the tab content. By default, its height is such that all the remaining space of the **\<tabs>** component is filled. The child components are arranged horizontally. When **\<tab-content>** is used as a child element in a container, the length on the main axis direction must be specified. Otherwise, the child element cannot be displayed.
**<tab-content\>** is a child component of **[<tabs\>](js-components-container-tabs.md)** and is used to provide the area for displaying the tab content. By default, its height is such that all the remaining space of the **<tabs\>** component is filled. The child components are arranged horizontally. When **<tab-content\>** is used as a child element in a container, its length along the main axis must be specified. Otherwise, it cannot be displayed.
> **NOTE**
>
> This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
None
## Child Components
Supported
## Attributes
In addition to the attributes in [Universal Attributes](js-components-common-attributes.md), the following attributes are supported.
## Attributes
In addition to the [universal attributes](../arkui-js/js-components-common-attributes.md), the following attributes are supported.
| Name | Type| Default Value | Mandatory| Description|
| -------- | -------- | -------- | -------- | -------- |
| scrollable | boolean | true | No| Whether the tabs can be switched by swiping left or right. The default value is **true**. If this attribute is set to **false**, tab switching is implemented only through the association with **tab-bar**.|
| Name | Type | Default Value | Mandatory | Description |
| ---------- | ------- | ------------- | --------- | ------------------------------------------------------------ |
| scrollable | boolean | true | No | Whether the tabs can be switched by swiping left or right. The default value is **true**. If this attribute is set to **false**, tab switching is implemented only through the association with **tab-bar**. |
## Styles
Styles in [Universal Styles](js-components-common-styles.md) are supported.
The [universal styles](../arkui-js/js-components-common-styles.md) are supported.
## Events
Events in [Universal Events](js-components-common-events.md) are supported.
The [universal events](../arkui-js/js-components-common-events.md) are supported.
## Example
For details, see the [tabs example code](js-components-container-tabs.md).
\ No newline at end of file
For details, see **Example** in [tabs](../arkui-js/js-components-container-tabs.md#example).
# circle
The **<circle\>** component is used to draw circles.
The **\<circle>** component is used to draw circles.
> **NOTE**
>
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
>![](../../public_sys-resources/icon-note.gif) **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
**animate**, **animateMotion**, and **animateTransform** are supported.
The following are supported: [\<animate>](js-components-svg-animate.md), [\<animateMotion>](js-components-svg-animatemotion.md), and [\<animateTransform>](js-components-svg-animatetransform.md).
## Attributes
The [universal attributes](js-components-svg-common-attributes.md) and the attributes listed below are supported.
The [universal attributes](../arkui-js/js-components-svg-common-attributes.md) and the attributes listed below are supported.
| Name | Type | Default Value | Mandatory | Description |
| ---- | ------------------------ | ------------- | --------- | ------------------------------------------------------------ |
| id | string | - | No | Unique ID of the component. |
| cx | \<length>\|\<percentage> | 0 | No | X-coordinate of the circle center. Attribute animations are supported. |
| cy | \<length>\|\<percentage> | 0 | No | Y-coordinate of the circle center. Attribute animations are supported. |
| r | \<length>\|\<percentage> | 0 | No | Radius of the circle. Attribute animations are supported. |
| Name| Type| Default Value| Mandatory| Description|
| -------- | -------- | -------- | -------- | -------- |
| id | string | - | No| Unique ID of the component.|
| cx | &lt;length&gt;\|&lt;percentage&gt; | 0 | No| X-coordinate of the circle center. Attribute animations are supported.|
| cy | &lt;length&gt;\|&lt;percentage&gt; | 0 | No| Y-coordinate of the circle center. Attribute animations are supported.|
| r | &lt;length&gt;\|&lt;percentage&gt; | 0 | No| Radius of the circle. Attribute animations are supported.|
## Example
```
```html
<!-- xxx.hml -->
<div class="container">
<svg fill="white" width="400" height="400">
......@@ -37,5 +41,5 @@ The [universal attributes](js-components-svg-common-attributes.md) and the att
</div>
```
![](figures/en-us_image_0000001173164853.png)
![en-us_image_0000001173164853](figures/en-us_image_0000001173164853.png)
# Universal Attributes
>![](../../public_sys-resources/icon-note.gif) **NOTE:**
>Universal attributes are supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
| Name | Type | Default Value | Mandatory | Description |
| ----------------- | ------------------------- | ------------- | --------- | ------------------------------------------------------------ |
| fill | \<color> | black | No | Fill color of an element using the shorthand attribute. Attribute animations are supported. |
| fill-opacity | number | 1 | No | Opacity of a fill color. The value ranges from **0** to **1**. The value **1** means opaque, and **0** means completely transparent. Attribute animations are supported. |
| fill-rule | nonzero \| evenodd | nonzero | No | **nonzero**: non-zero rule; <br/>**evenodd**: parity rule. |
| opacity | number | 1 | No | Opacity of an element. The value ranges from **0** to **1**. The value **1** means opaque, and **0** means completely transparent. Attribute animations are supported. |
| stroke | \<color> | - | No | Color of the stroke. Attribute animations are supported. |
| stroke-dasharray | \<string> | - | No | Length of the dashes and notches. The format is [length length length length]. The length values of dashes and notches are separated by a space and appear in pairs. |
| stroke-dashoffset | \<length> | 0 | No | Offset for rendering the associated dash line array. Attribute animations are supported. |
| stroke-linejoin | [bevel \| miter \| round] | miter | No | The shape used at the corner of a path when stroked.<br/>- **bevel**: connects paths with bevel corners.<br/>- **miter**: connects paths with mitered corners.<br/>- **round**: connects paths with rounded corners. |
| stroke-linecap | [butt \| round \| square] | butt | No | The shape used at the end of paths when stroked.<br/>- **butt**: The stroke for each path does not extend beyond its two endpoints.<br/>- **round**: At the end of each path the stroke is extended by a half circle with a diameter equal to the stroke width.<br/>- **square**: At the end of each path the stroke is extended by a half circle, with the width being equal to half of the stroke width, and the height being equal to the stroke width. |
| stroke-miterlimit | number | 4 | No | Limit value when the sharp angle is drawn as a miter. Attribute animations are supported. |
| stroke-opacity | number | 1 | No | Opacity of the stroke. The value ranges from **0** to **1**. The value **1** means opaque, and **0** means completely transparent. Attribute animations are supported. |
| stroke-width | \<length> | 1px | No | Stroke width. Attribute animations are supported. |
| transform | \<string> | - | No | Coordinate transformation parameters of the component and its child components.The following formats are supported:<br/>- **translate(\<x>[\<y>])**: translates along the x[y]-axis.<br/>- **scale(\<x>[\<y>])**: scales along the x[y]-axis.<br/>- **rotate(\<a>[\<x> \<y>])**: rotates at an angle of **a** with (x,y) as the center.<br/>- **skewX(\<a>)**: skews at an angle of **a** along the x-axis.<br/>- **skewY(\<a>)**: skews at an angle of **a** along the y-axis. |
> **NOTE**
>
> Universal attributes are supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
| Name| Type| Default Value| Mandatory| Description|
| -------- | -------- | -------- | -------- | -------- |
| fill | &lt;color&gt; | black | No| Fill color of an element using the shorthand attribute. Attribute animations are supported.|
| fill-opacity | number | 1 | No| Opacity of a fill color. The value ranges from **0** to **1**. The value **1** means opaque, and **0** means completely transparent. Attribute animations are supported.|
| fill-rule | nonzero&nbsp;\|&nbsp;evenodd | nonzero | No| Fill rule.<br>**nonzero**: non-zero rule.<br>**evenodd**: parity rule.|
| opacity | number | 1 | No| Opacity of an element. The value ranges from **0** to **1**. The value **1** means opaque, and **0** means completely transparent. Attribute animations are supported.|
| stroke | &lt;color&gt; | - | No| Color of the stroke. Attribute animations are supported.|
| stroke-dasharray | &lt;string&gt; | - | No| Length of the dashes and notches. The format is [length length length length]. The length values of dashes and notches are separated by a space and appear in pairs.|
| stroke-dashoffset | &lt;length&gt; | 0 | No| Offset for rendering the associated dash line array. Attribute animations are supported.|
| stroke-linejoin | [bevel&nbsp;\|&nbsp;miter&nbsp;\|&nbsp;round] | miter | No| The shape used at the corner of a path when stroked.<br>**bevel**: connects paths with bevel corners.<br>**miter**: connects paths with mitered corners.<br>**round**: connects paths with rounded corners.|
| stroke-linecap | [butt&nbsp;\|&nbsp;round&nbsp;\|&nbsp;square] | butt | No| The shape used at the end of paths when stroked.<br>**butt**: The stroke for each path does not extend beyond its two endpoints.<br>**round**: At the end of each path the stroke is extended by a half circle with a diameter equal to the stroke width.<br>**square**: At the end of each path the stroke is extended by a half circle, with the width being equal to half of the stroke width, and the height being equal to the stroke width.|
| stroke-miterlimit | number | 4 | No| Limit value when the sharp angle is drawn as a miter. Attribute animations are supported.|
| stroke-opacity | number | 1 | No| Opacity of the stroke. The value ranges from **0** to **1**. The value **1** means opaque, and **0** means completely transparent. Attribute animations are supported.|
| stroke-width | &lt;length&gt; | 1px | No| Stroke width. Attribute animations are supported.|
| transform | &lt;string&gt; | - | No| Coordinate transformation parameters of the component and its child components.<br>The following formats are supported:<br>**translate(\<x> [\<y>])**: translates along the x[y]-axis.<br>**scale(\<x> [\<y>])**: scales along the x[y]-axis.<br>**rotate(\<a> [\<x> \<y>])**: rotates at an angle of **a** with point (x,y) as the center.<br>**skewX(\<a>)**: skews at an angle of **a** along the x-axis.<br>**skewY(\<a>)**: skews at an angle of **a** along the y-axis. |
# ellipse
The **<ellipse\>** component is used to draw oval shapes.
The **\<ellipse>** component is used to draw oval shapes.
> **NOTE**
>
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
>![](../../public_sys-resources/icon-note.gif) **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
**animate**, **animateMotion**, and **animateTransform** are supported.
The following are supported: [\<animate>](js-components-svg-animate.md), [\<animateMotion>](js-components-svg-animatemotion.md), and [\<animateTransform>](js-components-svg-animatetransform.md).
## Attributes
The [universal attributes](js-components-svg-common-attributes.md) and the attributes listed below are supported.
The [universal attributes](../arkui-js/js-components-svg-common-attributes.md) and the attributes listed below are supported.
| Name | Type | Default Value | Mandatory | Description |
| ---- | ------------------------ | ------------- | --------- | ------------------------------------------------------------ |
| id | string | - | No | Unique ID of the component. |
| cx | \<length>\|\<percentage> | 0 | No | X-coordinate of the oval shape. Attribute animations are supported. |
| cy | \<length>\|\<percentage> | 0 | No | Y-coordinate of the oval shape. Attribute animations are supported. |
| rx | \<length>\|\<percentage> | 0 | No | Radius of the oval shape on the x-axis. Attribute animations are supported. |
| ry | \<length>\|\<percentage> | 0 | No | Radius of the oval shape on the y-axis. Attribute animations are supported. |
| Name| Type| Default Value| Mandatory| Description|
| -------- | -------- | -------- | -------- | -------- |
| id | string | - | No| Unique ID of the component.|
| cx | &lt;length&gt;\|&lt;percentage&gt; | 0 | No| X-coordinate of the oval shape. Attribute animations are supported.|
| cy | &lt;length&gt;\|&lt;percentage&gt; | 0 | No| Y-coordinate of the oval shape. Attribute animations are supported.|
| rx | &lt;length&gt;\|&lt;percentage&gt; | 0 | No| Radius of the oval shape on the x-axis. Attribute animations are supported.|
| ry | &lt;length&gt;\|&lt;percentage&gt; | 0 | No| Radius of the oval shape on the y-axis. Attribute animations are supported.|
## Example
```
```html
<!-- xxx.hml -->
<div class="container">
<svg fill="white" width="400" height="400">
......@@ -38,5 +42,5 @@ The [universal attributes](js-components-svg-common-attributes.md) and the att
</div>
```
![](figures/en-us_image_0000001173164793.png)
![en-us_image_0000001173164793](figures/en-us_image_0000001173164793.png)
# line
The **<line\>** component is used to draw a line.
The **\<line>** component is used to draw a line.
> **NOTE**
>
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
>![](../../public_sys-resources/icon-note.gif) **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
**animate**, **animateMotion**, and **animateTransform** are supported.
The following are supported: [\<animate>](js-components-svg-animate.md), [\<animateMotion>](js-components-svg-animatemotion.md), and [\<animateTransform>](js-components-svg-animatetransform.md).
## Attributes
The universal attributes as well as the attributes listed below are supported.
The [universal attributes](../arkui-js/js-components-svg-common-attributes.md) and the attributes listed below are supported.
| Name | Type | Default Value | Mandatory | Description |
| ---- | ------------------------ | ------------- | --------- | ------------------------------------------------------------ |
| id | string | - | No | Unique ID of the component. |
| x1 | \<length>\|\<percentage> | - | No | X-coordinate of the start point of the line. Attribute animations are supported. |
| y1 | \<length>\|\<percentage> | - | No | Y-coordinate of the start point of the line. Attribute animations are supported. |
| x2 | \<length>\|\<percentage> | - | No | X-coordinate of the end point of the line. Attribute animations are supported. |
| y2 | \<length>\|\<percentage> | - | No | Y-coordinate of the end point of the line. Attribute animations are supported. |
| Name| Type| Default Value| Mandatory| Description|
| -------- | -------- | -------- | -------- | -------- |
| id | string | - | No| Unique ID of the component.|
| x1 | &lt;length&gt;\|&lt;percentage&gt; | - | No| X-coordinate of the start point of the line. Attribute animations are supported.|
| y1 | &lt;length&gt;\|&lt;percentage&gt; | - | No| Y-coordinate of the start point of the line. Attribute animations are supported.|
| x2 | &lt;length&gt;\|&lt;percentage&gt; | - | No| X-coordinate of the end point of the line. Attribute animations are supported.|
| y2 | &lt;length&gt;\|&lt;percentage&gt; | - | No| Y-coordinate of the end point of the line. Attribute animations are supported.|
## Example
```
```html
<!-- xxx.hml -->
<div class="container">
<svg width="400" height="400">
<line x1="10" x2="300" y1="50" y2="50" stroke-width="4" fill="white" stroke="blue"></line>
<line x1="10" x2="300" y1="100" y2="100" stroke-width="4" fill="white" stroke="blue"></line>
<line x1="10" x2="300" y1="150" y2="150" stroke-width="10" stroke="red" stroke-dasharray="5 3" stroke-dashoffset="3"></line>
// round: At the end of each path the stroke is extended by a half circle with a diameter equal to the stroke width.
<line x1="10" x2="300" y1="200" y2="200" stroke-width="10" stroke="black" stroke-linecap="round"></line>
// butt: The stroke for each path does not extend beyond its two endpoints.
<line x1="10" x2="300" y1="220" y2="220" stroke-width="10" stroke="black" stroke-linecap="butt"></line>
// square: At the end of each path the stroke is extended by a half circle, with the width being equal to half of the stroke width, and the height being equal to the stroke width.
<line x1="10" x2="300" y1="240" y2="240" stroke-width="10" stroke="black" stroke-linecap="square"></line>
</svg>
</div>
```
![](figures/en-us_image_0000001127284954.png)
![en-us_image_0000001127284954](figures/en-us_image_0000001127284954.png)
# path
The **<path\>** component is used to draw a path.
The **\<path>** component is used to draw a path.
> **NOTE**
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
>![](../../public_sys-resources/icon-note.gif) **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
**animate**, **animateMotion**, and **animateTransform** are supported.
The following are supported: [\<animate>](js-components-svg-animate.md), [\<animateMotion>](js-components-svg-animatemotion.md), and [\<animateTransform>](js-components-svg-animatetransform.md).
## Attributes
The [universal attributes](js-components-svg-common-attributes.md) and the attributes listed below are supported. The configured universal attributes are passed to the child components.
| Name | Type | Default Value | Mandatory | Description |
| ---- | ------ | ------------- | --------- | ------------------------------------------------------------ |
| id | string | - | No | Unique ID of the component. |
| d | string | - | No | Shape of the path. The value contains a group of character instructions. Uppercase letters are absolute paths, and lowercase letters are relative paths.<br/>The meanings of the letters are as follows:<br/>- M/m = moveto<br/>- L/l = lineto<br/>- H/h = horizontal lineto<br/>- V/v = vertical lineto<br/>- C/c = curveto<br/>- S/s = smooth curveto<br/>- Q/q = quadratic Belzier curve<br/>- T/t = smooth quadratic Belzier curveto<br/>- A/a = elliptical Arc<br/>- Z/z = closepath |
| Name| Type| Default Value| Mandatory| Description|
| -------- | -------- | -------- | -------- | -------- |
| id | string | - | No| Unique ID of the component.|
| d | string | - | No| Shape of the path. The value contains a group of character instructions. Uppercase letters are absolute paths, and lowercase letters are relative paths.<br>The meanings of the letters are as follows:<br>-&nbsp;M/m&nbsp;=&nbsp;moveto<br>-&nbsp;L/l&nbsp;=&nbsp;lineto<br>-&nbsp;H/h&nbsp;=&nbsp;horizontal&nbsp;lineto<br>-&nbsp;V/v&nbsp;=&nbsp;vertical&nbsp;lineto<br>-&nbsp;C/c&nbsp;=&nbsp;curveto<br>-&nbsp;S/s&nbsp;=&nbsp;smooth&nbsp;curveto<br>-&nbsp;Q/q&nbsp;=&nbsp;quadratic&nbsp;Belzier&nbsp;curve<br>-&nbsp;T/t&nbsp;=&nbsp;smooth&nbsp;quadratic&nbsp;Belzier&nbsp;curveto<br>-&nbsp;A/a&nbsp;=&nbsp;elliptical&nbsp;Arc<br>-&nbsp;Z/z&nbsp;=&nbsp;closepath |
## Example
```
```html
<!-- xxx.hml -->
<div class="container">
<svg width="400" height="400">
......@@ -36,5 +39,5 @@ The [universal attributes](js-components-svg-common-attributes.md) and the att
</div>
```
![](figures/en-us_image_0000001173164891.png)
![en-us_image_0000001173164891](figures/en-us_image_0000001173164891.png)
# polygon
The **<polygon\>** component is used to draw a polygon.
The **\<polygon>** component is used to draw a polygon.
>![](../../public_sys-resources/icon-note.gif) **NOTE:**
>This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
> **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
**animate**, **animateMotion**, and **animateTransform** are supported.
The following are supported: [\<animate>](js-components-svg-animate.md), [\<animateMotion>](js-components-svg-animatemotion.md), and [\<animateTransform>](js-components-svg-animatetransform.md).
## Attributes
The [universal attributes](js-components-svg-common-attributes.md) and the attributes listed below are supported.
The [universal attributes](../arkui-js/js-components-svg-common-attributes.md) and the attributes listed below are supported.
| Name | Type | Default Value | Mandatory | Description |
| ------ | ------ | ------------- | --------- | ------------------------------------------------------------ |
| id | string | - | No | Unique ID of the component. |
| points | string | - | No | Multiple coordinates of the polygon.<br/>The format is [x1,y1 x2,y2 x3,y3].<br/>Attribute animations are supported. If the number of coordinates of the animation change value set in the attribute animation is different from the format of the original points, the attribute animation is invalid. |
| Name| Type| Default Value| Mandatory| Description|
| -------- | -------- | -------- | -------- | -------- |
| id | string | - | No| Unique ID of the component.|
| points | string | - | No| Multiple coordinates of the polygon.<br>The format is [x1,y1 x2,y2 x3,y3].<br>Attribute animations are supported. If the number of coordinates of the animation change value set in the attribute animation is different from the format of the original points, the attribute animation is invalid.|
## Example
```
```html
<!-- xxx.hml -->
<div class="container">
<svg fill="white" stroke="blue" width="400" height="400">
......@@ -35,5 +39,5 @@ The [universal attributes](js-components-svg-common-attributes.md) and the att
</div>
```
![](figures/en-us_image_0000001173324721.png)
![en-us_image_0000001173324721](figures/en-us_image_0000001173324721.png)
# polyline
The **<polyline\>** component is used to draw a polyline.
The **\<polyline>** component is used to draw a polyline.
> **NOTE**
>
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
>![](../../public_sys-resources/icon-note.gif) **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
**animate**, **animateMotion**, and **animateTransform** are supported.
The following are supported: [\<animate>](js-components-svg-animate.md), [\<animateMotion>](js-components-svg-animatemotion.md), and [\<animateTransform>](js-components-svg-animatetransform.md).
## Attributes
The universal attributes as well as the attributes listed below are supported.
The [universal attributes](../arkui-js/js-components-svg-common-attributes.md) and the attributes listed below are supported.
| Name | Type | Default Value | Mandatory | Description |
| ------ | ------ | ------------- | --------- | ------------------------------------------------------------ |
| id | string | - | No | Unique ID of the component. |
| points | string | - | No | Multiple coordinates of the polyline.<br/>The format is [x1,y1 x2,y2 x3,y3].<br/>Attribute animations are supported. If the number of coordinates of the animation change value set in the attribute animation is different from the format of the original points, the attribute animation is invalid. |
| Name| Type| Default Value| Mandatory| Description|
| -------- | -------- | -------- | -------- | -------- |
| id | string | - | No| Unique ID of the component.|
| points | string | - | No| Multiple coordinates of the polyline.<br>The format is [x1,y1 x2,y2 x3,y3].<br>Attribute animations are supported. If the number of coordinates of the animation change value set in the attribute animation is different from the format of the original points, the attribute animation is invalid.|
## Example
```
```html
<!-- xxx.hml -->
<div class="container">
<svg fill="white" stroke="blue" width="400" height="400">
......@@ -35,5 +39,5 @@ The universal attributes as well as the attributes listed below are supported.
</div>
```
![](figures/en-us_image_0000001173164845.png)
![en-us_image_0000001173164845](figures/en-us_image_0000001173164845.png)
# rect
The **<rect\>** component is used to draw rectangles and rounded rectangles.
The **\<rect>** component is used to draw rectangles and rounded rectangles.
> **NOTE**
>
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
>![](../../public_sys-resources/icon-note.gif) **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
**animate**, **animateMotion**, and **animateTransform** are supported.
The following are supported: [\<animate>](js-components-svg-animate.md), [\<animateMotion>](js-components-svg-animatemotion.md), and [\<animateTransform>](js-components-svg-animatetransform.md).
## Attributes
The [universal attributes](js-components-svg-common-attributes.md) and the attributes listed below are supported.
The [universal attributes](../arkui-js/js-components-svg-common-attributes.md) and the attributes listed below are supported.
| Name | Type | Default Value | Mandatory | Description |
| ------ | ------------------------ | ------------- | --------- | ------------------------------------------------------------ |
| id | string | - | No | Unique ID of the component. |
| width | \<length>\|\<percentage> | 0 | No | Width of a rectangle. Attribute animations are supported. |
| height | \<length>\|\<percentage> | 0 | No | Height of a rectangle. Attribute animations are supported. |
| x | \<length>\|\<percentage> | 0 | No | X-coordinate of the upper left corner of the rectangle. Attribute animations are supported. |
| y | \<length>\|\<percentage> | 0 | No | Y-coordinate of the upper left corner of the rectangle. Attribute animations are supported. |
| rx | \<length>\|\<percentage> | 0 | No | Radius of the rectangle rounded corner in the x-axis direction. Attribute animations are supported. |
| ry | \<length>\|\<percentage> | 0 | No | Radius of the rectangle rounded corner in the y-axis direction. Attribute animations are supported. |
| Name| Type| Default Value| Mandatory| Description|
| -------- | -------- | -------- | -------- | -------- |
| id | string | - | No| Unique ID of the component.|
| width | &lt;length&gt;\|&lt;percentage&gt; | 0 | No| Width of the rectangle. Attribute animations are supported.|
| height | &lt;length&gt;\|&lt;percentage&gt; | 0 | No| Height of the rectangle. Attribute animations are supported.|
| x | &lt;length&gt;\|&lt;percentage&gt; | 0 | No| X-coordinate of the upper left corner of the rectangle. Attribute animations are supported.|
| y | &lt;length&gt;\|&lt;percentage&gt; | 0 | No| Y-coordinate of the upper left corner of the rectangle. Attribute animations are supported.|
| rx | &lt;length&gt;\|&lt;percentage&gt; | 0 | No| Radius of the rectangle rounded corner in the x-axis direction. Attribute animations are supported.|
| ry | &lt;length&gt;\|&lt;percentage&gt; | 0 | No| Radius of the rectangle rounded corner in the y-axis direction. Attribute animations are supported.|
## Example
```
```html
<!-- xxx.hml -->
<div class="container">
<svg fill="white" width="400" height="400">
......@@ -43,5 +47,5 @@ The [universal attributes](js-components-svg-common-attributes.md) and the att
</div>
```
![](figures/0.png)
![0](figures/0.png)
# text
The **<text\>** component is used to display a piece of textual information.
The **\<text>** component is used to display a piece of textual information.
> **NOTE**
>
> - This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
>
> - The text content must be written in the content area. The **tspan** sub-element label can be nested to segment the text content. The **textPath** sub-element label can be nested to draw the text content based on the specified path.
> - **<text\>** can be nested only by the parent element label **svg**.
>
> - **\<text>** can be nested only by the parent element label **svg**.
>
> - Only the default font **sans-serif** is supported.
## Required Permissions
None
## Child Components
**\<tspan>**, **\<textpath>**, **\<animate>**, and **\<animateTransform>** are supported.
The following are supported: [\<tspan>](js-components-svg-tspan.md), [\<textpath>](js-components-svg-textpath.md), [\<animate>](js-components-svg-animate.md), and [\<animateTransform>](js-components-svg-animatetransform.md).
## Attributes
The attributes in the following table are supported.
| Name | Type | Default Value | Mandatory | Description |
| -------------- | ------------------------ | ------------- | --------- | ------------------------------------------------------------ |
| -------------- | ---------------------------------- | ----- | ---- | ---------------------------------------- |
| id | string | - | No | Unique ID of the component. |
| x | \<length>\|\<percentage> | 0 | No | X-coordinate of the upper left corner of the component. |
| y | \<length>\|\<percentage> | 0 | No | Y-coordinate of the upper left corner of the component. |
| dx | \<length>\|\<percentage> | 0 | No | Offset of the text on the x-axis. |
| dy | \<length>\|\<percentage> | 0 | No | Offset of the text on the y-axis. |
| rotate | number | 0 | No | Rotates the lower left corner of the font based on the circle center. A positive number indicates clockwise rotation, and a negative number indicates counterclockwise rotation. |
| font-size | \<length> | 30px | No | Font size. |
| fill | \<color> | black | No | Font fill color. |
| fill-opacity | number | 1.0 | No | Font fill opacity. |
| opacity | number | 1 | No | Opacity of an element. The value ranges from **0** to **1**. The value **1** means opaque, and **0** means completely transparent. Attribute animations are supported. |
| stroke | \<color> | black | No | Stroke and stroke color. |
| x | &lt;length&gt; \| &lt;percentage&gt; | 0 | No | X-coordinate of the upper left corner of the component. |
| y | &lt;length&gt; \| &lt;percentage&gt; | 0 | No | Y-coordinate of the upper left corner of the component. |
| dx | &lt;length&gt; \| &lt;percentage&gt; | 0 | No | Offset of the text on the x-axis. |
| dy | &lt;length&gt; \| &lt;percentage&gt; | 0 | No | Offset of the text on the y-axis. |
| rotate | number | 0 | No | Rotation of the text around its lower left corner. A positive number indicates clockwise rotation, and a negative number indicates counterclockwise rotation. |
| font-size | &lt;length&gt; | 30px | No | Font size. |
| fill | &lt;color&gt; | black | No | Fill color of the text. |
| fill-opacity | number | 1.0 | No | Fill opacity of the text. |
| opacity | number | 1 | No | Opacity of an element. The value ranges from **0** to **1**. The value **1** means opaque, and **0** means completely transparent. Attribute animations are supported.|
| stroke | &lt;color&gt; | black | No | Stroke color. |
| stroke-width | number | 1px | No | Stroke width. |
| stroke-opacity | number | 1.0 | No | Stroke opacity. |
......@@ -61,7 +67,7 @@ The attributes in the following table are supported.
<text dx="20" y="30" dy="50" fill="blue" font-size="30">test dx|dy|fill|font-size</text>
<text x="20" y="150" fill="blue" font-size="30" fill-opacity="0.2">test fill-opacity</text>
<text x="20" y="200" fill="red" font-size="40">test 0123456789</text>
<text x="20" y="250" fill="red" font-size="40" fill-opacity="0.2">Test Chinese</text>
<text x="20" y="250" fill="red" font-size="40" fill-opacity="0.2">Test</text>
<text x="20" y="300" rotate="30" fill="red" font-size="40">test rotate</text>
<text x="20" y="350" fill="blue" font-size="40" stroke="red" stroke-width="2">test stroke</text>
<text x="20" y="400" fill="white" font-size="40" stroke="red" stroke-width="2" stroke-opacity="0.5">test stroke-opacity</text>
......@@ -69,7 +75,7 @@ The attributes in the following table are supported.
</div>
```
![](figures/text-part1.png)
![text-part1](figures/text-part1.png)
Attribute animation example
......@@ -93,13 +99,12 @@ Attribute animation example
<animate attributeName="x" from="100" by="400" dur="3s" repeatCount="indefinite"></animate>
<animate attributeName="opacity" from="0.01" to="0.99" dur="3s" repeatCount="indefinite"></animate>
<animate attributeName="rotate" from="0" to="360" dur="3s" repeatCount="indefinite"></animate>
text attribute x|opacity|rotate
</text>
</svg>
</div>
```
![](figures/text-animate-part1.gif)
![text-animate-part1](figures/text-animate-part1.gif)
```html
<!-- xxx.hml -->
......@@ -114,7 +119,7 @@ Attribute animation example
</div>
```
![](figures/text-animate-part2.gif)
![text-animate-part2](figures/text-animate-part2.gif)
```html
<!-- xxx.hml -->
......@@ -133,5 +138,4 @@ Attribute animation example
</div>
```
![](figures/text-animate-part3.gif)
![text-animate-part3](figures/text-animate-part3.gif)
# textPath
The **<textPath\>** component is used to draw text along the path.
The **\<textPath>** component is used to draw text along the path.
>![](../../public_sys-resources/icon-note.gif) **NOTE:**
>- This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
>- Draws text based on the specified path. The **tspan** child component can be nested for segmenting.
>- **<textPath\>** can be nested only by the parent element label **svg**.
> **NOTE**
> - This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
>
> - The **\<tspan>** component can be nested in the **\<textPath>** component for segmenting.
>
> - The **\<textPath>** component can only be nested in the **\<text>** component.
## Required Permissions
None
## Child Components
**tspan** is supported.
The **[\<tspan>](js-components-svg-tspan.md)** child component is supported.
## Attributes
The attributes in the following table are supported.
| Name | Type | Default Value | Mandatory | Description |
| -------------- | ------------------------ | ------------- | --------- | ------------------------------------------------------------ |
| id | string | - | No | Unique ID of the component. |
| path | string | 0 | Yes | Shape of the path.<br/>The meanings of the letters are as follows:<br/>- M = moveto<br/>- L = lineto<br/>- H = horizontal lineto<br/>- V = vertical lineto<br/>- C = curveto<br/>- S = smooth curveto<br/>- Q = quadratic Belzier curve<br/>- T = smooth quadratic Belzier curveto<br/>- A = elliptical Arc<br/>- Z = closepath |
| startOffset | \<length>\|\<percentage> | 0 | No | Start offset of the text drawing along the path. |
| font-size | \<length> | 30px | No | Font size. |
| fill | \<color> | black | No | Font fill color. |
| by | number | - | No | Attribute offset relative to the specified animation. The default value of **from** is the original attribute value. |
| opacity | number | 1 | No | Opacity of an element. The value ranges from **0** to **1**. The value **1** means opaque, and **0** means completely transparent. Attribute animations are supported. |
| fill-opacity | number | 1.0 | No | Font fill opacity. |
| stroke | \<color> | black | No | Stroke and stroke color. |
| stroke-width | number | 1px | No | Stroke width. |
| stroke-opacity | number | 1.0 | No | Stroke opacity. |
| Name | Type | Mandatory | Description |
| -------------- | ---------------------------------- | ------ | ------------------------------------------------------------ |
| id | string | No | Unique ID of the component. |
| path | string | Yes | Shape of the path.<br>The meanings of the letters are as follows:<br>-&nbsp;M&nbsp;=&nbsp;moveto<br>-&nbsp;L&nbsp;=&nbsp;lineto<br>-&nbsp;H&nbsp;=&nbsp;horizontal&nbsp;lineto<br>-&nbsp;V&nbsp;=&nbsp;vertical&nbsp;lineto<br>-&nbsp;C&nbsp;=&nbsp;curveto<br>-&nbsp;S&nbsp;=&nbsp;smooth&nbsp;curveto<br>-&nbsp;Q&nbsp;=&nbsp;quadratic&nbsp;Belzier&nbsp;curve<br>-&nbsp;T&nbsp;=&nbsp;smooth&nbsp;quadratic&nbsp;Belzier&nbsp;curveto<br>-&nbsp;A&nbsp;=&nbsp;elliptical&nbsp;Arc<br>-&nbsp;Z&nbsp;=&nbsp;closepath<br>Default value: **0**|
| startOffset | &lt;length&gt;\|&lt;percentage&gt; | No | Offset of the text start point relative to the path start point.<br>Default value: **0** |
| font-size | &lt;length&gt; | No | Font size.<br>Default value: **30px** |
| fill | &lt;color&gt; | No | Font fill color.<br>Default value: **black** |
| by | number | No | Attribute offset relative to the specified animation. By default, **from** is the original attribute value. |
| opacity | number | No | Opacity of an element. The value ranges from **0** to **1**. The value **1** means opaque, and **0** means completely transparent. Attribute animations are supported.<br>Default value: **0**|
| fill-opacity | number | No | Font fill opacity.<br>Default value: **1.0** |
| stroke | &lt;color&gt; | No | Stroke color.<br>Default value: **black** |
| stroke-width | number | No | Stroke width.<br>Default value: **1px** |
| stroke-opacity | number | No | Stroke opacity.<br>Default value: **1.0** |
## Example
The following is an example of the **textspan** attribute. The **textpath** text is drawn along the path specified by the **path** attribute, and the start point is offset by 20% of the **path** length. \(The drawn element **<path\>** curve is for reference only.\)
The following is an example of the **\<textspan>** attributes, where text is drawn along the path specified by **path**, and the start point is offset by 20% of the **path** length. (The drawn **\<path>** curve is for reference only.)
```
/* xxx.css */
.container {
flex-direction: row;
justify-content: flex-start;
align-items: flex-start;
height: 1200px;
width: 600px;
}
```
```
```html
<!-- xxx.hml -->
<div class="container">
<svg fill="#00FF00" x="50">
......@@ -63,11 +59,23 @@ The following is an example of the **textspan** attribute. The **textpath**
</div>
```
![](figures/textpath-part1.png)
```css
/* xxx.css */
.container {
flex-direction: row;
justify-content: flex-start;
align-items: flex-start;
height: 1200px;
width: 600px;
}
```
Combination of **textpath** and **tspan**
```
![textpath-part1](figures/textpath-part1.png)
Combination of **\<textpath>** and **\<tspan>**
```html
<!-- xxx.hml -->
<div class="container">
<svg fill="#00FF00" x="50">
......@@ -83,9 +91,9 @@ Combination of **textpath** and **tspan**
</div>
```
![](figures/textpath-part2.png)
![textpath-part2](figures/textpath-part2.png)
```
```html
<!-- xxx.hml -->
<div class="container">
<svg fill="#00FF00" x="50">
......@@ -103,9 +111,9 @@ Combination of **textpath** and **tspan**
</div>
```
![](figures/textpath-part3.png)
![textpath-part3](figures/textpath-part3.png)
```
```html
<!-- xxx.hml -->
<div class="container">
<svg fill="#00FF00" x="50">
......@@ -124,11 +132,11 @@ Combination of **textpath** and **tspan**
</div>
```
![](figures/textpath-part4.png)
![textpath-part4](figures/textpath-part4.png)
The following is an example of the **startOffset** animation. When the text is drawn, the start offset is moved from 10% to 40%, and the text whose length exceeds the path length range is not drawn.
The following is an example of the **startOffset** animation, where the value of **startOffset** changes from 10% to 40%, and the text is not drawn when its length exceeds the path length range.
```
```css
/* xxx.css */
.container {
flex-direction: row;
......@@ -139,7 +147,7 @@ The following is an example of the **startOffset** animation. When the text is
}
```
```
```html
<!-- xxx.hml -->
<div class="container">
<svg fill="#00FF00">
......@@ -156,11 +164,11 @@ The following is an example of the **startOffset** animation. When the text is
</div>
```
![](figures/textpath-animate1.gif)
![textpath-animate1](figures/textpath-animate1.gif)
Animation and effect of the combination of **textpath** and **tspan**
Attribute animation of the **\<textPath>** and **\<tspan>** in combination
```
```html
<!-- xxx.hml -->
<div class="container">
<svg fill="#00FF00">
......@@ -187,17 +195,17 @@ Animation and effect of the combination of **textpath** and **tspan**
</div>
```
![](figures/textpath-animate2.gif)
![textpath-animate2](figures/textpath-animate2.gif)
\(1\) "tspan attribute x|rotate" indicates that the text drawing start point moves from 50 px to 100 px and rotates clockwise by 0 degrees to 360 degrees.
(1) **"tspan attribute x|rotate"**: The beginning of the text is offset from 50 px to 100 px, and the text rotates clockwise by 0 degrees to 360 degrees.
\(2\) "tspan attribute dx|opacity" is drawn after the "tspan static." drawing is complete. The offset moves from 0% to 30%, and the opacity changes from shallow to deep.
(2) **"tspan attribute dx|opacity"**: The text is drawn after the "tspan static." drawing is complete. The horizontal offset moves from 0% to 30%, and the opacity changes from shallow to deep.
\(3\) **tspan move**: After the previous **tspan** is drawn, the next tspan is drawn with an offset of 5% to show the effect of following the previous **tspan**.
(3) **tspan move**: After the previous **\<tspan>** is drawn, the next **\<tspan>** is drawn with an offset of 5%, creating the effect of following the previous **\<tspan>**.
Animation and effect of the combination of **textpath** and **tspan**
Attribute animation of the **\<textPath>** and **\<tspan>** in combination
```
```html
<!-- xxx.hml -->
<div class="container">
<svg fill="#00FF00">
......@@ -223,19 +231,19 @@ Animation and effect of the combination of **textpath** and **tspan**
</div>
```
![](figures/textpath-animate3.gif)
![textpath-animate3](figures/textpath-animate3.gif)
\(1\) **This is TextPath**.: Draw the first paragraph of text on the path without offset. The size is 30px, and the color is "\#D2691E".
(1) **"This is TextPath."**: The first segment of text, in the size of 30px and color of \#D2691E is drawn on the path without offset.
\(2\) The value of **tspan attribute fill|fill-opacity** is 20px offset from the end of the previous text segment. The color is from blue to red, and the opacity is from light to deep.
(2) **"tspan attribute fill|fill-opacity"**: The new segment of text is 20px offset from the end of the previous text segment. The text color changes from blue to red, and the opacity changes from light to deep.
\(3\) **tspan attribute font-size**: The drawing start point is 20px offset from the end of the previous segment. The start point is static, and the font size ranges from 10px to 50px. The overall length is continuously prolonged.
(3) **"tspan attribute font-size"**: The new segment of text is 20px offset from the end of the previous text segment. While the start point of the text is static, the font size shifts from 10px to 50px and the overall length is continuously prolonged.
\(4\) **Single tspan**: Draw a horizontal line at the end of the previous segment to follow the previous segment.
(4) **"Single tspan"**: A horizontal line is drawn at the end of the previous segment, creating the effect of following the previous segment.
Animation and effect of the combination of **textpath** and **tspan**
Attribute animation of the **\<textPath>** and **\<tspan>** in combination
```
```html
<!-- xxx.hml -->
<div class="container">
<svg fill="#00FF00">
......@@ -260,9 +268,8 @@ Animation and effect of the combination of **textpath** and **tspan**
</div>
```
![](figures/textpath-animate4.gif)
\(1\) **tspan attribute stroke**: The stroke color gradually changes from red to green.
![textpath-animate4](figures/textpath-animate4.gif)
\(2\) **tspan attribute stroke-width-opacity**: The contour width is changed from 1px to 5px, and the opacity is changed from shallow to deep.
(1) **"tspan attribute stroke"**: The stroke color gradually changes from red to green.
(2) **"tspan attribute stroke-width-opacity"**: The stroke width changes from 1px to 5px, and the opacity changes from shallow to deep.
# tspan
>![](../../public_sys-resources/icon-note.gif) **NOTE:**
>- This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
>- The text content must be written in the content area. The **<tspan\>** child component can be nested.
>- **<tspan\>** can be nested only by the parent element label **svg**.
The **\<tspan>** component is used to add a text style.
> **NOTE**
> - This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
>
> - This component can have **\<tspan>** child components nested.
>
> - This component can only be nested by the parent element label **svg**.
## Required Permissions
None
## Child Components
Tspan is supported.
The **[\<tspan>](js-components-svg-tspan.md)** child component is supported.
## Attributes
The attributes in the following table are supported.
| Name | Type | Default Value | Mandatory | Description |
| -------------- | ------------------------ | ------------- | --------- | ------------------------------------------------------------ |
| -------------- | ---------------------------------- | ----- | ---- | ---------------------------------------- |
| id | string | - | No | Unique ID of the component. |
| x | \<length>\|\<percentage> | 0 | No | X-coordinate of the upper left corner of the component. |
| y | \<length>\|\<percentage> | 0 | No | Y-coordinate of the upper left corner of the component. This parameter is invalid for the **textpath** child component. |
| dx | \<length>\|\<percentage> | 0 | No | Offset of the text on the x-axis. |
| dy | \<length>\|\<percentage> | 0 | No | Offset of the text on the y-axis. This parameter is invalid for the **textpath** child component. |
| rotate | number | 0 | No | Rotates the lower left corner of the font based on the circle center. A positive number indicates clockwise rotation, and a negative number indicates counterclockwise rotation. |
| font-size | \<length> | 30px | No | Font size. |
| fill | \<color> | black | No | Font fill color. |
| opacity | number | 1 | No | Opacity of an element. The value ranges from **0** to **1**. The value **1** means opaque, and **0** means completely transparent. Attribute animations are supported. |
| fill-opacity | number | 1.0 | No | Font fill opacity. |
| stroke | \<color> | black | No | Stroke and stroke color. |
| x | &lt;length&gt;\|&lt;percentage&gt; | 0 | No | X-coordinate of the upper left corner of the component. |
| y | &lt;length&gt;\|&lt;percentage&gt; | 0 | No | Y-coordinate of the upper left corner of the component. This attribute is invalid when the component is a child component of the **\<textpath>**. |
| dx | &lt;length&gt;\|&lt;percentage&gt; | 0 | No | Offset of the text on the x-axis. |
| dy | &lt;length&gt;\|&lt;percentage&gt; | 0 | No | Offset of the text on the y-axis. This attribute is invalid when the component is a child component of the **\<textpath>**. |
| rotate | number | 0 | No | Rotation of the text around its lower left corner. A positive number indicates clockwise rotation, and a negative number indicates counterclockwise rotation. |
| font-size | &lt;length&gt; | 30px | No | Font size. |
| fill | &lt;color&gt; | black | No | Fill color of the text. |
| opacity | number | 1 | No | Opacity of an element. The value ranges from **0** to **1**. The value **1** means opaque, and **0** means completely transparent. Attribute animations are supported.|
| fill-opacity | number | 1.0 | No | Fill opacity of the text. |
| stroke | &lt;color&gt; | black | No | Stroke color. |
| stroke-width | number | 1px | No | Stroke width. |
| stroke-opacity | number | 1.0 | No | Stroke opacity. |
## Example
```
/* xxx.css */
.container {
flex-direction: row;
justify-content: flex-start;
align-items: flex-start;
height: 1000px;
width: 1080px;
}
```
```
```html
<!-- xxx.hml -->
<div class="container">
<svg >
......@@ -65,22 +63,22 @@ The attributes in the following table are supported.
</div>
```
![](figures/tspan-part1.png)
Attribute animation example
```
```css
/* xxx.css */
.container {
flex-direction: row;
justify-content: flex-start;
align-items: flex-start;
height: 3000px;
height: 1000px;
width: 1080px;
}
```
```
![tspan-part1](figures/tspan-part1.png)
Attribute animation example
```html
<!-- xxx.hml -->
<div class="container">
<svg>
......@@ -103,9 +101,20 @@ Attribute animation example
</div>
```
![](figures/tspan-animate-part1.gif)
```css
/* xxx.css */
.container {
flex-direction: row;
justify-content: flex-start;
align-items: flex-start;
height: 3000px;
width: 1080px;
}
```
![tspan-animate-part1](figures/tspan-animate-part1.gif)
```html
<!-- xxx.hml -->
<div class="container">
<svg>
......@@ -120,9 +129,9 @@ Attribute animation example
</div>
```
![](figures/tspan-animate-part2.gif)
![tspan-animate-part2](figures/tspan-animate-part2.gif)
```
```html
<!-- xxx.hml -->
<div class="container">
<svg>
......@@ -136,9 +145,9 @@ Attribute animation example
</div>
```
![](figures/tspan-animate-part3.gif)
![tspan-animate-part3](figures/tspan-animate-part3.gif)
```
```html
<!-- xxx.hml -->
<div class="container">
<svg>
......@@ -159,5 +168,4 @@ Attribute animation example
</div>
```
![](figures/tspan-animate-part4.gif)
![tspan-animate-part4](figures/tspan-animate-part4.gif)
# svg
The **<svg\>** component is a basic container. It can be used as the root node of an SVG document or be used to nest an SVG fragment into an SVG document.
The **\<svg>** component is a basic container. It can be used as the root node of an SVG document or be used to nest an SVG fragment into an SVG document.
>![](../../public_sys-resources/icon-note.gif) **NOTE:**
>- This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
>- The width and height must be defined for the **<svg\>** parent component or **<svg\>** component. Otherwise, the component is not drawn.
> **NOTE**
> - This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
>
> - The width and height must be defined for the **<svg>** parent component or **<svg>** component. Otherwise, the component is not drawn.
## Required Permissions
None
## Child Components
**svg**, **rect**, **circle**, **ellipse**, **path**, **line**, **polygon**, **polyline**, **text**, **animate**, and **animateTransform** are supported.
The following are supported: [\<svg>](js-components-svg.md), [\<rect>](js-components-svg-rect.md), [\<circle>](js-components-svg-circle.md), [\<ellipse>](../arkui-js/js-components-svg-ellipse.md), [\<path>](js-components-svg-path.md), [\<line](../arkui-js/js-components-svg-line.md), [\<polygon>](../arkui-js/js-components-svg-polygon.md), [\<polyline>](js-components-svg-polyline.md), [\<text>](js-components-svg-text.md), [\<animate>](js-components-svg-animate.md), and [\<animateTransform>](js-components-svg-animateTransform.md).
## Attributes
The [universal attributes](js-components-svg-common-attributes.md) and the attributes listed below are supported. The configured universal attributes are passed to the child components.
The [universal attributes](../arkui-js/js-components-svg-common-attributes.md) and the attributes listed below are supported. The configured universal attributes are passed to the child components.
| Name | Type | Default Value | Mandatory | Description |
| ------- | ------------------------ | ------------- | --------- | ------------------------------------------------------------ |
| id | string | - | No | Unique ID of the component. |
| width | \<length>\|\<percentage> | - | No | Component width. |
| height | \<length>\|\<percentage> | - | No | Component height. |
| x | \<length>\|\<percentage> | - | No | X-coordinate of the current **\<svg>** component. The settings do not work for the root **\<svg>** node. |
| y | \<length>\|\<percentage> | | No | Y-coordinate of the current **\<svg>** component. The settings do not work for the root **\<svg>** node. |
| viewBox | string | - | No | View box of the current **\<svg>** component. The supported format is **\<number number number number>**. The four parameters indicate the **min-x**, **min-y**, **width**, and **height**. The width and height of the view box are different from those of the **\<svg>** component. The view box is scaled in center-aligned mode. |
| Name| Type| Default Value| Mandatory| Description|
| -------- | -------- | -------- | -------- | -------- |
| id | string | - | No| Unique ID of the component.|
| width | &lt;length&gt;\|&lt;percentage&gt; | - | No| Component width.|
| height | &lt;length&gt;\|&lt;percentage&gt; | - | No| Component height.|
| x | &lt;length&gt;\|&lt;percentage&gt; | - | No| X-coordinate of the current **\<svg>** component. The settings do not work for the root **\<svg>** node. |
| y | &lt;length&gt;\|&lt;percentage&gt; | | No| Y-coordinate of the current **\<svg>** component. The settings do not work for the root **\<svg>** node. |
| viewBox | string | - | No| View box of the current **\<svg>** component. The supported format is \<number number number number>. The four parameters indicate **min-x**, **min-y**, **width**, and **height**, respectively. The width and height of the view box are different from those of the **\<svg>** component. The view box is scaled in center-aligned mode. |
## Example
```
```html
<!-- xxx.hml -->
<div class="container">
<svg width="400" height="400">
......@@ -48,5 +52,5 @@ The [universal attributes](js-components-svg-common-attributes.md) and the att
</div>
```
![](figures/en-us_image_0000001173164789.png)
![en-us_image_0000001173164789](figures/en-us_image_0000001173164789.png)
# TypeScript-based Declarative Development Paradigm
# eTS-based Declarative Development Paradigm
- Universal Component Information
- Universal Events
......@@ -120,12 +120,13 @@
- Canvas Components
- [Canvas](ts-components-canvas-canvas.md)
- [CanvasRenderingContext2D](ts-canvasrenderingcontext2d.md)
- [OffscreenCanvasRenderingConxt2D](ts-offscreencanvasrenderingcontext2d.md)
- [Lottie](ts-components-canvas-lottie.md)
- [Path2D](ts-components-canvas-path2d.md)
- [CanvasGradient](ts-components-canvas-canvasgradient.md)
- [ImageBitmap](ts-components-canvas-imagebitmap.md)
- [ImageData](ts-components-canvas-imagedata.md)
- [OffscreenCanvasRenderingContext2D](ts-offscreencanvasrenderingcontext2d.md)
- [Path2D](ts-components-canvas-path2d.md)
- [Lottie](ts-components-canvas-lottie.md)
- Animation
- [AnimatorProperty](ts-animatorproperty.md)
- [Explicit Animation](ts-explicit-animation.md)
......@@ -136,8 +137,9 @@
- [Motion Path Animation](ts-motion-path-animation.md)
- [Matrix Transformation](ts-matrix-transformation.md)
- [Interpolation Calculation](ts-interpolation-calculation.md)
- Global UI Methods
- Pop-up Window
- Dialog Box
- [Alert Dialog Box](ts-methods-alert-dialog-box.md)
- [Action Sheet](ts-methods-action-sheet.md)
- [Custom Dialog Box](ts-methods-custom-dialog-box.md)
......
# 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**
>
> The APIs of this module are supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
animation(value: {duration?: number, tempo?: number, curve?: string | Curve, delay?:number, iterations: number, playMode?: PlayMode, onFinish?: () => void})
Applies a property animator to the component to animate its attributes over time.
| Name | Type | Default Value | Description |
| ---------- | ---------------------------------------- | --------------- | ----------------------- |
| duration | number | 1000 | Animation duration, in ms. The default duration is 1000 ms. |
| curve | [Curve](ts-appendix-enums.md#curve) | Curve.Linear | Animation curve. The default curve is linear. |
| delay | number | 0 | Delay of animation playback, in ms. By default, the playback is not delayed. |
| 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. |
| 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.|
**Parameters**
| Name | Type | Mandatory | Description |
| ---------- | ------------------------------------------| ---- | ------------------------------------------------------------ |
| duration | number | No | Animation duration, in ms.<br>Default value: **1000**|
| 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**|
| curve | string&nbsp;\|&nbsp;[Curve](ts-appendix-enums.md#curve) | No | Animation curve.<br>Default value: **Curve.Linear** |
| delay | number | No | Delay of animation playback, in ms. The value **0** indicates that the playback is not delayed.<br>Default value: **0** |
| 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
......
......@@ -55,12 +55,12 @@
## MouseButton
| Name | Description |
| ------- | ---------------- |
| ------- | ---------------------------------------- |
| Left | Left button on the mouse. |
| Right | Right button on the mouse. |
| Middle | Middle button on the mouse. |
| Back | Back button on the left of the mouse.|
| Forward | Forward button on the left of the mouse.|
| Back | Back button on the left of the mouse. |
| Forward | Forward button on the left of the mouse. |
| None | No button. |
## MouseAction
......
# CheckboxGroup
> **NOTE**<br>
> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
The **\<CheckboxGroup>** component is used to select or deselect all check boxes in a group.
## 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
None
Not supported
## 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.
- Parameters
| Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- |
| group | string | No| - | Group name.|
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| group | string | No| Group name.|
## Attributes
| Name| Type| Default Value| Description|
| Name| Type| Default Value | Description|
| -------- | -------- | -------- | -------- |
| selectAll | bool | false | Whether to select all.|
| selectedColor | Color | - | Color of the selected check box.|
| selectAll | boolean | false | Whether to select all. |
| selectedColor | [ResourceColor](ts-types.md#resourcecolor8) | - | Color of the selected check box.|
## Events
| 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
- SelectStatus enums
| Name | Description|
| ----- | -------------------- |
| All | All check boxes in the group are selected.|
| Part | Some check boxes in the group are selected.|
| None | None of the check boxes in the group are selected.|
onChange (callback: (event: CheckboxGroupResult ) => void )
Triggered when the selection status of the check box group or any check box wherein changes.
| Name | Type | Mandatory | Description |
| ----- | ------------------- | --------- | ----------------------------------- |
| event | CheckboxGroupResult | Yes | Callback used to return the result. |
## CheckboxGroupResult
| Name | Type | Description |
| ------ | ------ | ------- |
| name | Array&lt;string&gt; | Names of all the selected check boxes in the group.|
| status | SelectStatus | Selected status.|
## SelectStatus
| Name | Description|
| ----- | -------------------- |
| All | All check boxes in the group are selected.|
| Part | Some check boxes in the group are selected.|
| None | None of the check boxes in the group are selected.|
## Example
```
```ts
// xxx.ets
@Entry
@Component
struct CheckboxExample {
......
# Gauge
The **\<Gauge>** component is used to display data in a ring chart.
> ![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.
Data gauge chart widget, which is used to display data in a ring chart.
## 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
None
Not supported
## APIs
Gauge(value:{value: number, min?: number, max?: number})
Gauge(options:{value: number, min?: number, max?: number})
- Parameter
| 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. |
**Parameters**
| 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
| Name | Type | Default Value | Description |
| -------- | -------- | -------- | -------- |
| value | number | 0 | Sets the value of the current data chart. |
| startAngle | Angle | -150 | Set the start angle. Clock 0 indicates 0 degree, and the clockwise direction indicates the positive angle. |
| endAngle | Angle | 150 | Sets the end angle position. The clock 0 point is 0 degree, and the clockwise direction is the positive angle. |
| colors | Color \| Array&lt;ColorStop&gt; | - | Set the color of the chart. You can set the pure color or segmental gradient color. |
| strokeWidth | Length | - | Sets the ring thickness of a ring chart. |
| Name| Type| Description|
| -------- | -------- | -------- |
| value | number | Value of the chart.<br>Default value: **0**|
| 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**|
| 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](ts-types.md#length) | Stroke width of the chart.|
## ColorStop
Describes a gradient stop.
| Name | Type | Description |
| --------- | -------------------- | ------------------------------------------------------------ |
| ColorStop | [[ResourceColor](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.|
## Example
```
```ts
// xxx.ets
@Entry
@Component
struct GaugeExample {
......
# Image
The **\<Image>** component is used to render and display local and online images.
The **\<image>** component is used to render and display images.
> **NOTE**
>
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## 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).
```
"abilities": [
{
...
"permissions": ["ohos.permission.INTERNET"],
...
}
]
```
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).
## Child Components
......@@ -31,37 +19,38 @@ Not supported
Image(src: string | PixelMap | Resource)
Obtains an image from the specified source for subsequent rendering and display.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ---- | ---------------------------------------- | ---- | ---- | ---------------------------------------- |
| 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 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.|
| Name| Type | Mandatory| Default Value| Description |
| ------ | ------------------------------------------------------------ | ---- | ------ | ------------------------------------------------------------ |
| 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 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.<br>\- Strings with the `file:///data/storage` prefix are supported, which are used to read image resources in the` files` folder in the installation directory of the application. Using such strings requires read permission on the files in the installation directory. |
## Attributes
| Name | Type | Default Value | Description |
| --------------------- | ------------------------------------------------------- | ------------------------ | ------------------------------------------------------------ |
| alt | string \| [Resource](ts-types.md#resource) | - | Placeholder image displayed during loading. Both local and Internet URIs are supported. |
| objectFit | [ImageFit](ts-appendix-enums.md#imagefit) | Cover | Image scale type. |
| objectRepeat | [ImageRepeat](ts-appendix-enums.md#imagerepeat) | NoRepeat | Whether the image is repeated.<br>**NOTE**<br>This attribute is not applicable to SVG images. |
| interpolation | 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. |
| renderMode | ImageRenderMode | Original | Rendering mode of the image.<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. |
| matchTextDirection | boolean | false | 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.|
| fitOriginalSize | boolean | true | Whether to fit the component to the original size of the image source when the component size is not set.|
| fillColor | [ResourceColor](ts-types.md#resourcecolor8) | - | Fill color. This parameter is valid only for SVG images. Once set, the fill color will replace that of the SVG image.|
| --------------------- | ---------------------------------------- | -------- | ---------------------------------------- |
| alt | string \| [Resource](ts-types.md#resource) | - | Placeholder image displayed during loading. Only local images are supported. |
| objectFit | [ImageFit](ts-appendix-enums.md#imagefit) | Cover | Image scale mode. |
| objectRepeat | [ImageRepeat](ts-appendix-enums.md#imagerepeat) | NoRepeat | Whether the image is repeated.<br>> **NOTE**<br>> This attribute is not applicable to SVG images.|
| interpolation | 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 or **PixelMap** objects. |
| renderMode | ImageRenderMode | Original | Rendering mode of the image.<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. If the value is of the number type, the unit px is used.<br>> **NOTE**<br>> This attribute is not applicable to **PixelMap** objects.|
| matchTextDirection | boolean | false | 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. |
| fitOriginalSize | boolean | true | Whether to fit the component to the original size of the image source when the component size is not set. |
| fillColor | [ResourceColor](ts-types.md#resourcecolor8) | - | 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 | true | 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.|
| 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. |
| syncLoad<sup>8+</sup> | boolean | false | 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. |
> **NOTE**
>
> For SVG images, only the following tags are included in the supported list: **svg**, **rect**, **circle**, **ellipse**, **path**, **line**, **polyline**, **polygon**, **animate**, **animateMotion**, and **animateTransform**.
## ImageInterpolation
| Name | Description |
| ------ | ------------------------- |
| ------ | ------------------------ |
| None | Interpolation image data is not used. |
| High | The interpolation image data is used at the high level, which may affect the image rendering speed.|
| High | The interpolation image data is used at the high level. The use of the interpolation image data may affect the image rendering speed.|
| Medium | The interpolation image data is used at the medium level. |
| Low | The interpolation image data is used at the low level. |
......@@ -74,12 +63,11 @@ Obtains an image from the specified source for subsequent rendering and display.
## Events
| 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. |
| 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. |
| onFinish(event:&nbsp;()&nbsp;=&gt;&nbsp;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. |
| ---------------------------------------- | ---------------------------------------- |
| onComplete(callback: (event?: { width: number, height: number, componentWidth: number,<br> componentHeight: number, loadingStatus: number }) =&gt; void) | Triggered when an image is successfully loaded. The loaded image is returned. |
| onError(callback: (event?: { componentWidth: number, componentHeight: number }) =&gt; void) | Triggered when an exception occurs during image loading. |
| 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
......@@ -281,3 +269,53 @@ struct ImageExample3 {
```
![en-us_image_0000001256858397](figures/en-us_image_0000001256858397.gif)
### Rendering Sandbox Images
```
import fileio from '@ohos.fileio';
import image from '@ohos.multimedia.image';
const EMPTY_PATH = 'file://';
@Entry
@Component
struct LoadImageExample {
@State fileContent: string = '';
@State path: string = EMPTY_PATH;
@State accountInfoHeadPic: any = '';
build() {
Column() {
Button ('Read Sandbox Image')
.margin({ bottom: 10 })
.onClick(() => {
try {
this.path = EMPTY_PATH;
let context = getContext(this);
let path = context.getApplicationContext().filesDir + '/icon.png';
console.log(`Read the sandbox image=========>${path}`);
let fd = fileio.openSync(path, 0o100, 0o666);
console.log(`create file========>${fd}`);
let srcPath = context.bundleCodeDir + '/entry/resource/base/media/icon.png';
fileio.copyFileSync(srcPath, path);
console.log(`error:=============>${e.message}`);
}
})
Button ('Read Image')
.margin({ bottom: 10 })
.onClick(() => {
this.path = EMPTY_PATH;
this.path += getContext(this.bundleCodeDir + '/entry/resource/base/media/icon.png');
})
Text(`Image path: ${this.path}`)
.fontSize(20)
.margin({ bottom: 10 })
Image(this.path)
.width(100)
.height(100)
}
.width('100%').height('100%')
}
}
```
# ImageAnimator
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
Not supported
......@@ -25,17 +22,16 @@ ImageAnimator()
## Attributes
| Name| Type| Default Value| Mandatory| Description|
| -------- | -------- | -------- | -------- | -------- |
| images | Array&lt;{<br/>src: string,<br/>width?: number \| string,<br/>height?: number \| string,<br/>top?: number \| string,<br/>left?: number \| string,<br/>duration?: number<br/>}&gt; | [] | Yes| Image frame information. The information of each frame includes the image path, image size, image position, and image playback duration. The detailed description is as follows:<br/>**src**: image path. The image format can be SVG, PNG, or JPG.<br/>**width**: image width.<br/>**height**: image height.<br/>**top**: vertical coordinate of the image relative to the upper left corner of the component.<br/>**left**: horizontal coordinate of the image relative to the upper left corner of the component.<br/>**duration**: playback duration of the image, in ms. |
| state | [AnimationStatus](ts-appendix-enums.md#animationstatus) | Initial | No| Playback status of the animation. The default status is **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.|
| 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.|
| 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.|
| 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.|
| fillMode | [FillMode](ts-appendix-enums.md#fillmode) | Forwards | No| Status before and after the animation starts. For details about the options, see **FillMode**.|
| 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.|
| Name | Type | Default Value | Mandatory | Description |
| ---------- | ----------------------- | -------- | -------- | -------- |
| images | Array&lt;{<br/>src: string,<br/>width?: number \| string,<br/>height?: number \| string,<br/>top?: number \| string,<br/>left?: number \| string,<br/>duration?: number<br/>}&gt; | [] | No | Image frame information. The information of each frame includes the image path, image size, image position, and image playback duration. The detailed description is as follows:<br/>**src**: image path. The image format can be SVG, PNG, or JPG.<br/>**width**: image width.<br/>**height**: image height.<br/>**top**: vertical coordinate of the image relative to the upper left corner of the component.<br/>**left**: horizontal coordinate of the image relative to the upper left corner of the component.<br/>**duration**: playback duration of the image, in ms. |
| state | [AnimationStatus](ts-appendix-enums.md#animationstatus) | Initial | No | Playback status of the animation. |
| 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. |
| 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. |
| 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. |
| 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. |
| fillMode | [FillMode](ts-appendix-enums.md#fillmode) | Forwards | No | Status before and after the animation starts. For details about the options, see **FillMode**. |
| 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. |
## Events
......
# LoadingProgress
> ![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 **\<LoadingProgress>** component is used to display the loading progress.
The **\<LoadingProgress>** component is used to create a loading animation.
## Required Permissions
> **NOTE**
> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
None
## Child Components
None
Not supported
## APIs
LoadingProgress()
Creates a **LoadingProgress** instance.
Creates a **\<LoadingProgress>** component.
## Attributes
| Name | Type | Default Value | Description |
| ----- | ----- | ------------- | ---------------------------------------- |
| color | Color | - | Foreground color of the loading progress bar. |
| Name| Type| Description|
| -------- | -------- | -------- |
| color | [ResourceColor](ts-types.md#resourcecolor8) | Foreground color of the **\<LoadingProgress>** component.|
## Example
```
```ts
// xxx.ets
@Entry
@Component
struct LoadingProgressExample {
......@@ -41,4 +40,4 @@ struct LoadingProgressExample {
}
```
![zh-cn_image_0000001198839004](figures/loadingProgress.png)
\ No newline at end of file
![en-us_image_000000111864201](figures/en-us_image_000000111864201.gif)
# 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**
>
> 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
......@@ -23,23 +22,28 @@ Not supported
Marquee(value: { start: boolean, step?: number, loop?: number, fromStart?: boolean, src: string })
- Parameters
| Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- |
| start | boolean | Yes| - | Whether to start scrolling.|
| step | number | No| 6 | Scrolling step.|
| 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.|
| fromStart | boolean | No| true | Whether the text scrolls from the start.|
| src | string | Yes| - | Text to scroll.|
**Parameters**
| Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- |
| start | boolean | Yes| - | Whether to start scrolling.|
| step | number | No| 6 | Scrolling step.|
| 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.|
| fromStart | boolean | No| true | Whether the text scrolls from the start.|
| src | string | Yes| - | Text to scroll.|
## Attributes
| Name | Type| Default Value | Description |
| ---------- | -------- | ------------------------------------ | ------------------------------------ |
| allowScale | boolean | false | Whether to allow text to scale. |
## Events
| Name| Description|
| -------- | -------- |
| onStart(callback:&nbsp;()&nbsp;=&gt;&nbsp;void) | Triggered when the marquee starts scrolling.|
| onBounce(callback:&nbsp;()&nbsp;=&gt;&nbsp;void) | Triggered when the marquee has reached the end.|
| onFinish(callback:&nbsp;()&nbsp;=&gt;&nbsp;void) | Triggered when the marquee has finished scrolling.|
| onStart(event:&nbsp;()&nbsp;=&gt;&nbsp;void) | Triggered when the marquee starts scrolling.|
| onBounce(event:&nbsp;()&nbsp;=&gt;&nbsp;void) | Triggered when the marquee has reached the end.|
| onFinish(event:&nbsp;()&nbsp;=&gt;&nbsp;void) | Triggered when the marquee has finished scrolling.|
## Example
......
# Navigation
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**<br>
> **NOTE**
>
> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
The **&lt;Navigation&gt;** component typically functions as the root container of a page and displays the page title, toolbar, and menu based on the attribute settings.
## Required Permissions
None
## Child Components
Supported
......@@ -24,56 +18,58 @@ Navigation()
Creates a component that can automatically display the navigation bar, title, and toolbar based on the attribute settings.
## Attributes
| Name | Type | Default Value | Description |
| -------- | -------- | -------- | -------- |
| title | string \| [CustomBuilder](../../ui/ts-types.md) | - | Page title. |
| 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. |
| titleMode | NavigationTitleMode | NavigationTitleMode.Free | Display mode of the page title bar. |
| toolBar | {<br/>items:[<br/>Object<br/>] }<br/>\| [CustomBuilder](../../ui/ts-types.md) | - | Content of the toolbar.<br/>**items**: all items on the toolbar. |
| hideToolBar | boolean | false | Whether to hide the toolbar.<br/>**true**: Hide the toolbar.<br/>**false**: Show the toolbar. |
| hideTitleBar | boolean | false | Whether to hide the title bar. |
| hideBackButton | boolean | false | Whether to hide the back button. |
- NavigationMenuItem attributes
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| value | string | Yes | - | Text of an option on the menu bar. |
| icon | string | No | - | Icon path of an option on the menu bar. |
| action | () =&gt; void | No | - | Callback invoked when an option is selected. |
- Object attributes
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| value | string | Yes | - | Text of an option on the toolbar. |
| icon | string | No | - | Icon path of an option on the toolbar. |
| action | () =&gt; void | No | - | Callback invoked when an option is selected. |
- NavigationTitleMode enums
| Name | Description |
| -------- | -------- |
| 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). |
| Full | The mode is fixed at full mode (main title and subtitle). |
> **NOTE**
> Currently, only the scrollable component **&lt;List&gt;** is supported.
| Name | Type | Description |
| -------------- | ---------------------------------------- | ---------------------------------------- |
| title | string \| [CustomBuilder](ts-types.md#custombuilder8)<sup>8+</sup> | Page title. |
| subtitle | string | Subtitle of the page. |
| menus | Array<NavigationMenuItem&gt; \| [CustomBuilder](ts-types.md#custombuilder8)<sup>8+</sup> | Menu in the upper right corner of the page. |
| titleMode | NavigationTitleMode | Display mode of the page title bar.<br>Default value: **NavigationTitleMode.Free**|
| toolBar | object \| [CustomBuilder](ts-types.md#custombuilder8)<sup>8+</sup> | Content of the toolbar.<br>**items**: all items on the toolbar. |
| 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** |
| hideBackButton | boolean | Whether to hide the back button.<br>Default value: **false** |
## NavigationMenuItem
| Name | Type | Mandatory| Description |
| ------ | ----------------------- | ---- | ------------------------------ |
| value | string | Yes | Text of a menu item. |
| icon | string | No | Icon path of a menu item.|
| action | () =&gt; void | No | Callback invoked when a menu item is selected. |
## object
| Name | Type | Mandatory| Description |
| ------ | ----------------------- | ---- | ------------------------------ |
| value | string | Yes | Text of an option on the toolbar. |
| icon | string | No | Icon path of an option on the toolbar.|
| action | () =&gt; void | No | Callback invoked when an option is selected. |
## NavigationTitleMode
| Name | Description |
| ---- | ---------------------------------------- |
| 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.|
| 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
| 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
```
```ts
// Example 01
@Entry
@Component
......@@ -161,8 +157,7 @@ struct NavigationExample {
![en-us_image_0000001256978359](figures/en-us_image_0000001256978359.gif)
```
```ts
// Example 02
@Entry
@Component
......
# Progress
The **\<Progress>** component is used to provide a progress indicator that displays the progress of content loading or an operation.
> **NOTE**
>
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
The **\<Progress>** component is used to provide a progress bar that displays the progress of content loading or an operation.
## Required Permissions
None
## Child Components
Not supported
......@@ -21,40 +14,50 @@ Not supported
## APIs
Progress(value: {value: number, total?: number, type?: ProgressType})
Progress(options: {value: number, total?: number, style?: ProgressStyle, type?: ProgressType})
Creates a progress bar.
Creates a progress indicator.
- Parameters
| 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. |
- ProgressType enums
| Name | Description |
| -------- | -------- |
| Linear | Linear type. |
| Ring<sup>8+</sup> | Ring type without scale. 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<sup>8+</sup> | Ring type with scale, which is similar to the clock scale style. |
| 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. |
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| value | number | Yes| Current progress.|
| total | number | No| Total progress.<br>Default value: **100**|
| type<sup>8+</sup> | ProgressType | No| Type of the progress indicator.<br>Default value: **ProgressType.Linear**|
| 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**|
## ProgressType
| Name| Description|
| -------- | -------- |
| Linear | Linear type.|
| Ring<sup>8+</sup> | 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<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
| Name | Type | Default Value | Description |
| -------- | -------- | -------- | -------- |
| value | number | - | Current progress. |
| color | Color | - | Background color of the progress bar. |
| 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 thickness is greater than the progress bar width, the default scale thickness is used. |
| Name| Type| Description|
| -------- | -------- | -------- |
| value | number | Current progress.|
| color | [ResourceColor](ts-types.md#resourcecolor8) | Background color of the progress indicator.|
| 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
```ts
// xxx.ets
@Entry
......
# Radio
> ![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 **\<Radio>** component allows users to select from a set of mutually exclusive options.
## 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
None
Not supported
## APIs
Radio(options: {value: string, group: string})
- 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.|
**Parameters**
| 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
| Name| Type| Default Value| Description|
| -------- | -------- | -------- | -------- |
| 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
| 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
```
```ts
// xxx.ets
@Entry
@Component
struct RadioExample {
......@@ -55,8 +50,8 @@ struct RadioExample {
Radio({ value: 'Radio1', group: 'radioGroup' }).checked(true)
.height(50)
.width(50)
.onChange((value: boolean) => {
console.log('Radio1 status is ' + value)
.onChange((isChecked: boolean) => {
console.log('Radio1 status is ' + isChecked)
})
}
Column() {
......@@ -64,8 +59,8 @@ struct RadioExample {
Radio({ value: 'Radio2', group: 'radioGroup' }).checked(false)
.height(50)
.width(50)
.onChange((value: boolean) => {
console.log('Radio2 status is ' + value)
.onChange((isChecked: boolean) => {
console.log('Radio2 status is ' + isChecked)
})
}
Column() {
......@@ -73,8 +68,8 @@ struct RadioExample {
Radio({ value: 'Radio3', group: 'radioGroup' }).checked(false)
.height(50)
.width(50)
.onChange((value: boolean) => {
console.log('Radio3 status is ' + value)
.onChange((isChecked: boolean) => {
console.log('Radio3 status is ' + isChecked)
})
}
}.padding({ top: 30 })
......
......@@ -6,10 +6,6 @@ The **\<RichText>** component parses and displays HTML text.
>
> 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
Not supported
......@@ -20,64 +16,67 @@ RichText(content:string)
**Parameters**
| Name| Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| content | string | Yes| - | Text string in HTML format. |
| Name| Type| Mandatory | Description|
| ------- | -------- | ------------- | -------- |
| content | string | Yes | String in HTML format.|
## Events
| Name | Description|
| Name| Description|
| -------- | -------- |
| onStart(callback: () => void) => void | Triggered when web page loading starts. |
| onComplete(callback: () => void) => void | Triggered when web page loading is completed. |
| onStart(callback: () => void) | Triggered when web page loading starts. |
| onComplete(callback: () => void) | Triggered when web page loading is completed.|
## 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> |
| \<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>|
| \<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> |
| \<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> |
| \<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> |
| \<script>\</script> | Used to embed or reference a client-side script, such as JavaScript. | \<script>document.write("Hello World!")\</script> |
| \<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>|
| \<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> |
| \<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>|
| \<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 | 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> |
## Example
You can preview how this component looks on a real device. The preview is not yet available in the DevEco Studio Previewer.
```ts
// xxx.ets
@Entry
@Component
struct RichTextExample {
@State data: string = "<h1 style='text-align: center;'>h1 heading</h1>" +
"<h1 style='text-align: center;'><i>h1 italic</i></h1>" +
"<h1 style='text-align: center;'><u>h1 underlined</u></h1>" +
"<h2 style='text-align: center;'>h2 heading</h2>" +
"<h3 style='text-align: center;'>h3 heading</h3>" +
"<p style='text-align: center;'>Regular paragraph</p><hr/>" +
"<div style='width: 500px;height: 500px;border: 1px solid;margin: 0auto;'>" +
"<p style='font-size: 35px;text-align: center;font-weight: bold; color: rgb(24,78,228)'>Font size: 35px; line height: 45px</p>" +
"<p style='background-color: #e5e5e5;line-height: 45px;font-size: 35px;text-indent: 2em;'>" +
"<p>This is a paragraph. This is a paragraph. This is a paragraph. This is a paragraph. This is a paragraph. This is a paragraph. This is a paragraph. This is a paragraph. This is a paragraph.</p>"
@State data: string = '<h1 style="text-align: center;">h1 heading</h1>' +
'<h1 style="text-align: center;"><i>h1 italic</i></h1>' +
'<h1 style="text-align: center;"><u>h1 underlined</u></h1>' +
'<h2 style="text-align: center;">h2 heading</h2>' +
'<h3 style="text-align: center;">h3 heading</h3>' +
'<p style="text-align: center;">Regular paragraph</p><hr/>' +
'<div style="width: 500px;height: 500px;border: 1px solid;margin: 0auto;">' +
'<p style="font-size: 35px;text-align: center;font-weight: bold; color: rgb(24,78,228)">Font size: 35px; line height: 45px</p>' +
'<p style="background-color: #e5e5e5;line-height: 45px;font-size: 35px;text-indent: 2em;">' +
'<p>This is a paragraph. This is a paragraph. This is a paragraph. This is a paragraph. This is a paragraph. This is a paragraph. This is a paragraph. This is a paragraph. This is a paragraph.</p>';
build() {
Flex({direction: FlexDirection.Column,alignItems: ItemAlign.Center,
justifyContent: FlexAlign.Center }){
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center,
justifyContent: FlexAlign.Center }) {
RichText(this.data)
.onStart(()=>{
console.info("RichText onStart")
.onStart(() => {
console.info('RichText onStart');
})
.onComplete(()=>{
console.info("RichText onComplete")
.onComplete(() => {
console.info('RichText onComplete');
})
}
}
}
```
![richText](figures/richText.png)
......@@ -6,10 +6,6 @@ The **\<ScrollBar>** is used together with scrollable components, such as **\<Li
>
> 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
......@@ -22,20 +18,20 @@ ScrollBar(value: { scroller: Scroller, direction?: ScrollBarDirection, state?: B
**Parameters**
| Name| Type| Mandatory| Default Value| Description|
| Name| Type| Mandatory| Default Value | 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.|
| state | [BarState](ts-appendix-enums.md#barstate) | No| BarState.Auto | Scrollbar state.|
| direction | ScrollBarDirection | No| ScrollBarDirection.Vertical | Scrollbar direction in which scrollable components scroll. |
| state | [BarState](ts-appendix-enums.md#barstate) | No| BarState.Auto | Scrollbar state. |
> **NOTE**
>
> The **<\ScrollBar>** component defines the behavior style of the scrollable area, and its subnodes define the behavior style of the scrollbar.
> The **\<ScrollBar>** component defines the behavior style of the scrollable area, and its subnodes define the behavior style of the scrollbar.
>
> 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.
## ScrollBarDirection
| Name| Description|
| -------- | -------- |
| Vertical | Vertical scrollbar.|
......
......@@ -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.
## Required Permissions
None
## Child Components
Not supported
......@@ -20,19 +16,18 @@ Search(options?: { value?: string; placeholder?: string; icon?: string; controll
**Parameters**
| Name | Type | Mandatory | Description |
| ----------- | ---------------- | ---- | ---------------------------------------- |
| 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
| Name | Type | Description |
| ----------------------- | ---------------------------------------- | --------------------- |
| searchButton | string | Text on the search button located next to the search text box. By default, there is no search button.|
| ----------------------- | ------------------------------------------------ | ---------------------------------------------- |
| searchButton | string | Text on the search button located next to the search text box. By default, there is no search button. |
| placeholderColor | [ResourceColor](ts-types.md#resourcecolor8) | Placeholder text color. |
| placeholderFont | [Font](ts-types.md#font) | Placeholder text style. |
| textFont | [Font](ts-types.md#font) | Text font for the search text box. |
......@@ -40,12 +35,12 @@ Search(options?: { value?: string; placeholder?: string; icon?: string; controll
## Events
| Name | Description |
| ------------------------------------------- | ------------------------------------------------------------ |
| onSubmit(callback: (value: string) => void) | Triggered when users click the search icon or the search button, or touch the search button on a soft keyboard.<br>- **value**: current text input. |
| onChange(callback: (value: string) => void) | Triggered when the input in the text box changes.<br>- **value**: current text input. |
| onCopy(callback: (value: string) => void) | Triggered when data is copied to the pasteboard.<br>- **value**: text copied. |
| onCut(callback: (value: string) => void) | Triggered when data is cut from the pasteboard.<br>- **value**: text cut. |
| onPaste(callback: (value: string) => void) | Triggered when data is pasted from the pasteboard.<br>- **value**: text pasted. |
| ---------------------------------------- | ---------------------------------------- |
| onSubmit(callback: (value: string) => void) | Triggered when users click the search icon or the search button, or touch the search button on a soft keyboard.<br> -**value**: current text input.|
| onChange(callback: (value: string) => void) | Triggered when the input in the text box changes.<br> -**value**: current text input. |
| onCopy(callback: (value: string) => void) | Triggered when data is copied to the pasteboard.<br> -**value**: text copied. |
| onCut(callback: (value: string) => void) | Triggered when data is cut from the pasteboard.<br> -**value**: text cut. |
| onPaste(callback: (value: string) => void) | Triggered when data is pasted from the pasteboard.<br> -**value**: text pasted. |
## SearchController
......@@ -63,12 +58,10 @@ Sets the position of the caret.
**Parameters**
| Name | Type | Mandatory | Description |
| ----- | ------ | ---- | ----------------- |
| Name| Type| Mandatory| Description |
| ------ | -------- | ---- | ---------------------------------- |
| value | number | Yes | Length from the start of the character string to the position where the caret is located.|
## Example
```ts
......
# Select
> ![](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 **<Select\>** component provides a drop-down list box that allows users to select among multiple options.
## 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
None
Not supported
## APIs
Select(options: Array\<SelectOption>\)
Select(options: Array\<SelectOption\>)
- SelectOption parameters
**SelectOption**
| Name| Type| Mandatory| Default Value| Description|
| ------ | ----------------------------------------------- | ---- | ------ | -------------- |
| value | [ResourceStr](../../ui/ts-types.md) | 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.|
| Name| Type | Mandatory| Description |
| ------ | ----------------------------------- | ---- | -------------- |
| value | [ResourceStr](ts-types.md#resourcestr8) | Yes | Value of an option in the drop-down list box.|
| icon | [ResourceStr](ts-types.md#resourcestr8) | No | Icon of an option in the drop-down list box.|
## Attributes
| Name| Type| Default Value| Description|
| ----------------------- | --------------------------------------------------- | ------ | ----------------------------------------------- |
| 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.|
| font | [Font](../../ui/ts-types.md) | - | Text font of the drop-down button.|
| fontColor | [ResourceColor](../../ui/ts-types.md) | - | 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.|
| selectedOptionFont | [Font](../../ui/ts-types.md) | - | 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.|
| optionBgColor | [ResourceColor](../../ui/ts-types.md) | - | 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.|
| optionFontColor | [ResourceColor](../../ui/ts-types.md) | - | Text color of an option in the drop-down list box.|
| 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**.|
| value | string | Text of the drop-down button. |
| font | [Font](ts-types.md#font) | Text font of the drop-down button. |
| fontColor | [ResourceColor](ts-types.md#resourcecolor8) | Text color of the drop-down button. |
| selectedOptionBgColor | [ResourceColor](ts-types.md#resourcecolor8) | Background color 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](ts-types.md#resourcecolor8) | Text color of the selected option in the drop-down list box. |
| optionBgColor | [ResourceColor](ts-types.md#resourcecolor8) | Background color 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](ts-types.md#resourcecolor8) | Text color of an option in the drop-down list box. |
## Events
| 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.|
| Name | Description |
| ---------------------------------------------------------- | ------------------------------------------------------------ |
| 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
```
```ts
// xxx.ets
@Entry
@Component
struct SelectExample {
......@@ -61,7 +60,7 @@ struct SelectExample {
.font({size: 30, weight:400, family: 'serif', style: FontStyle.Normal })
.selectedOptionFont({size: 40, weight: 500, family: 'serif', style: FontStyle.Normal })
.optionFont({size: 30, weight: 400, family: 'serif', style: FontStyle.Normal })
.onSelecte((index:number)=>{
.onSelect((index:number)=>{
console.info("Select:" + index)
})
}
......
# Slider
The **\<Slider>** component is used to quickly adjust settings, such as the volume and brightness.
> **NOTE**
>
> 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
Not supported
......@@ -21,59 +14,64 @@ Not supported
## 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
| 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. |
**Parameters**
- SliderStyle enums
| Name | Description |
| ------ | --------------------------------- |
| OutSet | The slider is on the slider rail. |
| InSet | The slider is in the slider rail. |
| Name | Type | Mandatory| Description |
| ---------------------- | --------------------------------- | ---- | ------------------------------------------------------------ |
| value | number | No | Current progress.<br>Default value: **0** |
| min | number | No | Minimum value.<br>Default value: **0** |
| max | number | No | Maximum value.<br>Default value: **100** |
| step | number | No | Step of the slider.<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>**NOTE**<br>The value **false** indicates that the values increase from left to right for a horizontal slider and from top to bottom for a vertical slider. The value **true** indicates that the values increase from right to left for a horizontal slider and from bottom to top for a vertical slider.<br>Default value: **false**|
## SliderStyle
| Name | Description |
| ------ | ------- |
| OutSet | The slider is on the slider rail.|
| InSet | The slider is in the slider rail.|
## Attributes
Touch target configuration is not supported.
| Name | Type | Default Value | Description |
| ------------- | ------- | ------------- | ---------------------------------------- |
| blockColor | Color | - | Color of the slider. |
| trackColor | Color | - | Background color of the slider. |
| selectedColor | Color | - | Color of the slider rail that has been slid. |
| showSteps | boolean | false | Whether to display the current step. |
| showTips | boolean | false | Whether to display a bubble to indicate the percentage when sliding. |
| Name | Type | Description |
| ------------- | ------- | ----------------- |
| blockColor | [ResourceColor](ts-types.md#resourcecolor8) | Color of the slider. |
| trackColor | [ResourceColor](ts-types.md#resourcecolor8) | Background color of the slider. |
| selectedColor | [ResourceColor](ts-types.md#resourcecolor8) | Color of the slider rail that has been slid. |
| showSteps | boolean | Whether to display the current step.<br>Default value: **false**|
| 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.|
| maxLabel | string | Maximum label.|
| minLabel | string | Minimum label.|
## 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 |
| ---------------------------------------- | ---------------------------------------- |
| 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. If the return value contains decimals, you can use **Math.toFixed()** to process the data to the required precision.<br>**mode**: dragging state.|
- SliderChangeMode enums
| 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. |
## 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.|
| Click | 3 | The user moves the slider by touching the slider rail.|
## Example
```
```ts
// xxx.ets
@Entry
@Component
struct SliderExample {
......
# Span
The **\<Span>** component is used to display inline text in the **\<Text>** component.
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> **NOTE**
>
> 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
None
Not supported
## 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
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 |
| -------- | -------- | -------- | -------- |
| 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. |
| textCase | [TextCase](ts-appendix-enums.md#textcase-enums) | Normal | Text case. |
| Name| Type| Description|
| -------- | -------- | -------- |
| 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>} |
| letterSpacing | number \| string | Letter spacing. |
| textCase | [TextCase](ts-appendix-enums.md#textcase) | Text case.<br>Default value: **Normal** |
## 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.
> ![icon-note.gif](public_sys-resources/icon-note.gif) **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.
> **NOTE**
>
> As the **\<Span>** component does not include size information, the **target** attribute of the **ClickEvent** object returned by the click event is invalid.
## Example
```
```ts
// xxx.ets
@Entry
@Component
struct SpanExample {
......
# TextArea
The **\<TextArea>** component provides multi-line text input and responds to certain input events.
The **\<TextArea>** component provides multi-line text input.
> **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
Not supported
......@@ -23,34 +18,33 @@ TextArea(value?:{placeholder?: ResourceStr, text?: ResourceStr, controller?: Tex
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ----------------------- | ---------------------------------------- | ---- | ---- | -------------- |
| placeholder | [ResourceStr](ts-types.md#resourcestr8) | No | - | Text displayed when there is no input. |
| text | [ResourceStr](ts-types.md#resourcestr8) | No | - | Current text input. |
| controller<sup>8+</sup> | [TextAreaController](#textareacontroller8) | No | - | Text area controller.|
| Name | Type | Mandatory | Description |
| ----------------------- | ---------------------------------------- | ---- | -------------- |
| placeholder | [ResourceStr](ts-types.md#resourcestr8) | No | Text displayed when there is no input. |
| text | [ResourceStr](ts-types.md#resourcestr8) | 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.
| Name | Type | Default Value | Description |
| ------------------------ | ---------------------------------------- | ----- | ---------------------------------------- |
| placeholderColor | [ResourceColor](ts-types.md#resourcecolor8) | - | Placeholder text color. |
| placeholderFont | [Font](ts-types.md#font) | - | 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.<br/>Default value: **TextAlign.Start** |
| caretColor | [ResourceColor](ts-types.md#resourcecolor8) | - | Color of the caret in the text box. |
| inputFilter<sup>8+</sup> | {<br/>value:&nbsp;[ResourceStr](ts-types.md#resourcestr8)<sup>8+</sup>,<br/>error?:&nbsp;(value:&nbsp;string)&nbsp;=&gt;&nbsp;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.|
In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported.
| Name | Type | Description |
| ------------------------ | ---------------------------------------- | ---------------------------------------- |
| placeholderColor | [ResourceColor](ts-types.md#resourcecolor8) | 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#resourcecolor8) | Color of the caret in the text box. |
| inputFilter<sup>8+</sup> | {<br>value: [ResourceStr](ts-types.md#resourcestr8)<sup>8+</sup>,<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.|
## Events
| Name | Description |
| ---------------------------------------- | ---------------------------------------- |
| ------------------------------------------------------------ | ------------------------------------------------------------ |
| onChange(callback: (value: string) =&gt; void) | Triggered when the input 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.|
| 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>
......@@ -60,7 +54,6 @@ Defines the controller for controlling the **\<TextArea>** component.
```
controller: TextAreaController = new TextAreaController()
```
### caretPosition<sup>8+</sup>
......@@ -71,9 +64,9 @@ Sets the position of the caret.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ----- | ------ | ---- | ---- | ------------------- |
| value | number | Yes | - | Length from the start of the 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
......
......@@ -18,8 +18,8 @@ TextClock(options?: { timeZoneOffset?: number, controller?: TextClockController
| Name | Type | Mandatory | Description |
| -------------- | -------- | ------ | --------------------------------------------------------------------------- |
| 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 |
| controller | [TextClockController](#textclockcontroller) | No | Controller to control the status of the **<TextClock\>** component. |
| 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|
| controller | [TextClockController](#textclockcontroller) | No | Controller to control the status of the **<TextClock\>** component.|
## Attributes
......@@ -27,24 +27,24 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| Name | Type | Description |
| ------ | --------------- | ------------------------------------------------------------ |
| 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'**|
| 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>If the specified format does not match the supported formats, the default value is used.<br>Default value: **'hms'**|
## 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 |
| -------------------------------------------- | ------------------------------------------------------------ |
| 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
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.
Implements the controller of the **\<TextClock>** component. You can bind the controller to the component to control its start and stop. A **\<TextClock>** component can be bound to only one controller.
### Objects to Import
```ts
controller: TextClockController = new TextClockController()
controller: TextClockController = new TextClockController();
```
### start
......@@ -59,35 +59,37 @@ stop()
Stops the **<TextClock\>** component.
## Example
```ts
@Entry
@Component
struct Second {
@State accumulateTime: number = 0
controller: TextClockController = new TextClockController()
@State accumulateTime: number = 0;
// Objects to import
controller: TextClockController = new TextClockController();
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Text('Current milliseconds is ' + this.accumulateTime)
.fontSize(20)
// Display the system time in 12-hour format for the UTC+8 time zone, accurate to seconds.
TextClock({ timeZoneOffset: -8, controller: this.controller })
.format('hms')
.onDateChange((value: number) => {
this.accumulateTime = value
this.accumulateTime = value;
})
.margin(20)
.fontSize(30)
Button("start TextClock")
.margin({ bottom: 10 })
.onClick(() => {
this.controller.start()
// Start the text clock.
this.controller.start();
})
Button("stop TextClock")
.onClick(() => {
this.controller.stop()
// Stop the text clock.
this.controller.stop();
})
}
.width('100%')
......@@ -95,4 +97,4 @@ struct Second {
}
}
```
![](figures/text_clock.png)
# TextInput
The **\<TextInput>** component provides single-line text input.
> **NOTE**
>
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
The **\<TextInput>** component provides single-line text input.
## Required Permissions
None
## Child Components
Not supported
......@@ -20,83 +14,81 @@ Not supported
## APIs
TextInput(value?:{placeholder?: string controller?: TextInputController})
TextInput(value?:{placeholder?: [ResourceStr](ts-types.md#resourcestr8), text?: [ResourceStr](ts-types.md#resourcestr8), controller?: TextInputController})
- Parameters
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| placeholder | string | No | - | Text displayed when there is no input. |
| controller<sup>8+</sup> | [TextInputController](#textinputcontroller8) | No | - | Text input controller. |
**Parameters**
| Name | Type | Mandatory | Description |
| ----------------------- | ---------------------------------------- | ---- | --------------- |
| placeholder | [ResourceStr](ts-types.md#resourcestr8) | No | Text displayed when there is no input. |
| text | [ResourceStr](ts-types.md#resourcestr8) | No | Current text input. |
| controller<sup>8+</sup> | [TextInputController](#textinputcontroller8) | No | Text input controller.|
## Attributes
In addition to universal attributes, the following attributes are supported.
| Name | Type | Default Value | Description |
| -------- | -------- | -------- | -------- |
| type | InputType | InputType.Normal | Input box type. |
| placeholderColor | Color | - | Placeholder 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. |
| enterKeyType | EnterKeyType | EnterKeyType.Done | How the Enter key is labeled. |
| caretColor | Color | - | Color of the caret (also known as the text insertion cursor). |
| 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. |
- EnterKeyType enums
| Name | Description |
| -------- | -------- |
| EnterKeyType.Go | The Enter key is labeled **Go**. |
| EnterKeyType.Search | The Enter key is labeled **Search**. |
| EnterKeyType.Send | The Enter key is labeled **Send**. |
| EnterKeyType.Next | The Enter key is labeled **Next**. |
| EnterKeyType.Done | The Enter key is labeled **Done**. |
- InputType enums
| Name | Description |
| -------- | -------- |
| InputType.Normal | Normal input mode. |
| InputType.Password | Password input mode. |
| InputType.Email | Email address input mode. |
| InputType.Number | Digit input mode. |
## Events
In addition to the universal attributes, the following attributes are supported.
| Name | Type | Description |
| ------------------------ | ---------------------------------------- | ---------------------------------------- |
| type | InputType | Input box type.<br>Default value: **InputType.Normal** |
| placeholderColor | [ResourceColor](ts-types.md#resourcecolor8) | Placeholder text color.|
| placeholderFont | [Font](ts-types.md#font) | Placeholder text style.|
| enterKeyType | EnterKeyType | How the Enter key is labeled.<br>Default value: **EnterKeyType.Done** |
| caretColor | [ResourceColor](ts-types.md#resourcecolor8) | Color of the caret in the text box. |
| maxLength | number | Maximum number of characters in the text input. |
| inputFilter<sup>8+</sup> | {<br>value: value:&nbsp;[ResourceStr](ts-types.md#resourcestr8)<sup>8+</sup>,<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.|
## EnterKeyType
| Name | Description |
| -------- | -------- |
| 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. |
| 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. |
| 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. |
| ------------------- | --------- |
| Go | The Enter key is labeled "Go." |
| Search | The Enter key is labeled "Search." |
| Send | The Enter key is labeled "Send." |
| Next | The Enter key is labeled "Next."|
| Done | The Enter key is labeled "Done." |
### TextInputController<sup>8+</sup>
## InputType enums
Implements the controller of the **\<TextInput>** component.
| Name | Description |
| ------------------ | ------------- |
| Normal | Normal input mode. |
| Password | Password input mode. |
| Email | Email address input mode.|
| Number | Digit input mode. |
## Event
| Name | Description |
| ---------------------------------------- | ---------------------------------------- |
| onChange(callback: (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. |
| onEditChanged(callback: (isEditing: boolean) =&gt; void)<sup>(deprecated) </sup> | Triggered when the input status changes. |
| 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.|
#### Objects to Import
## TextInputController<sup>8+</sup>
Implements the controller of the **\<TextInput>** component.
### Objects to Import
```
controller: TextInputController = new TextInputController()
```
#### caretPosition
### caretPosition
caretPosition(value: number): void
Sets the position of the caret.
- 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. |
**Parameters**
| Name| Type| Mandatory| Description |
| ------ | -------- | ---- | -------------------------------------- |
| value | number | Yes | Length from the start of the string to the position where the caret is located.|
## Example
......
# TextPicker
The **TextPicker** component allows users to scroll to select text.
> ![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 **&lt;TextPicker&gt;** component allows users to select text from a list of options.
## Required Permissions
None
## Child Components
None
Not supported
## APIs
TextPicker(value: {range: string[], selected?: number})
TextPicker(options?: {range: string[] | [Resource](ts-types.md#resource), selected?: number, value?: string})
Creates a text picker based on the selection range specified by **range**.
- Parameter
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| range | string[] | Yes | - | Data selection range of the picker. |
| selected | number | No | First element | Index value of the selected item in the array. |
**Parameters**
| 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
| Name | Type | Default Value | Description |
| -------- | -------- | -------- | -------- |
| defaultPickerItemHeight | Length | - | Default height of a Picker content item element. |
| Name| Type| Description|
| -------- | -------- | -------- |
| defaultPickerItemHeight | number \| string | Default height of an item in the picker.|
## Events
| Name | Description |
| Name| Description|
| -------- | -------- |
| onChange(callback: (value: string, index: number) =&gt; void) | Triggered when an item in the picker is selected.<br/>- **value**: text 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.|
## Example
```
```ts
// xxx.ets
@Entry
@Component
struct TextPickerExample {
......
# TextTimer
The **\<TextTimer>** component displays timing information and is controlled in text format.
> ![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 **&lt;TextTimer&gt;** component supports custom time formats.
## Required Permissions
None
## Child Components
None
Not supported
## APIs
TextTimer(options: { isCountDown?: boolean, count?: number, controller?: TextTimerController })
TextTimer(options?: { isCountDown?: boolean, count?: number, controller?: TextTimerController })
- Parameters
| Name | Type | Mandatory | Default Value | 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 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. |
| controller | [TextTimerController](#texttimercontroller) | No | null | **&lt;TextTimer&gt;** controller. |
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| isCountDown | boolean | No| Whether to count down.<br/>Default value: **false** |
| 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
| Name | Type | Default Value | 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**. |
| Name| Type| Description|
| -------- | -------- | -------- |
| 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
| 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
Defines the controller for controlling the **&lt;TextTimer&gt;** component.
Implements the controller for controlling the **\<TextTimer>** component. A **\<TextTimer>** component can be bound to only one controller.
### Objects to Import
......@@ -75,8 +70,8 @@ Resets the timer.
## Example
```
```ts
// xxx.ets
@Entry
@Component
struct TextTimerExample {
......@@ -88,9 +83,9 @@ struct TextTimerExample {
TextTimer({controller: this.textTimerController})
.format(this.format)
.fontColor(Color.Black)
.fontSize(this.textSize)
.fontSize(50)
.onTimer((utc: number, elapsedTime: number) => {
console.info('textTimer notCountDown utc is:' + utc + ', elapsedTime: ' + elapsedTime)
console.info('textTimer notCountDown utc is: ' + utc + ', elapsedTime: ' + elapsedTime)
})
Row() {
Button("start").onClick(() => {
......
# TimePicker
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.
## Required Permissions
No
## Child Components
Not supported
......@@ -20,34 +14,35 @@ Not supported
## APIs
TimePicker(options?: TimePickerOptions)
TimePicker(options?: {selected?: Date})
Creates a time picker whose default time range is from 00:00 to 23:59.
- options parameters
| Name | Type | Mandatory | Default Value | Description |
| -------- | ---- | --------- | ------------------- | -------------------------- |
| selected | Date | No | Current system time | Time of the selected item. |
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| selected | Date | No| Time of the selected item.<br>Default value: current system time|
## Attributes
| Name | Type | Default Value | Description |
| --------------- | ------- | ------------- | ---------------------------------------- |
| useMilitaryTime | boolean | false | Whether to display time in 24-hour format. The value cannot be modified dynamically. |
| Name| Type| Description|
| -------- | -------- | -------- |
| useMilitaryTime | boolean | Whether to display time in 24-hour format. The value cannot be modified dynamically.<br>Default value: **false**|
## Events
| 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
| Name | Type | Description |
| ------ | ------ | ------------------------------------ |
| hour | number | Hour portion of the selected time. |
| minute | number | Minute portion of the selected time. |
| ------ | ------ | ------- |
| hour | number | Hour portion of the selected time.|
| minute | number | Minute portion of the selected time.|
## Example
......
# LongPressGesture
**LongPressGesture** is used to trigger a long press gesture, which requires one or more fingers with a minimum 500 ms hold-down time.
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> **NOTE**
>
> 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
LongPressGesture(options?: { fingers?: number, repeat?: boolean, duration?: number })
LongPressGesture(value?: { fingers?: number, repeat?: boolean, duration?: number })
- Parameters
| Name | Type | Mandatory | Default Value | 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. |
| duration | number | No | 500 | Minimum hold-down time, in ms. |
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| fingers | number | No| Minimum number of fingers to trigger a long press gesture. The value ranges from 1 to 10.<br>Default value: **1**|
| 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
| Name | Description |
| Name| Description|
| -------- | -------- |
| onAction((event?: GestureEvent) =&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. |
| 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. |
| onAction(event:(event?: [GestureEvent](ts-gesture-settings.md)) =&gt; void) | Callback invoked when a long press gesture is recognized.|
| 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.|
## Example
```
```ts
// xxx.ets
@Entry
@Component
struct LongPressGestureExample {
@State count: number = 0
@State count: number = 0;
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.SpaceBetween }) {
Text('LongPress onAction:' + this.count)
}
.height(200).width(300).padding(60).border({ width:1 }).margin(30)
Column() {
Text('LongPress onAction:' + this.count).fontSize(28)
// Touch and hold the text with one finger to trigger the gesture event.
.gesture(
LongPressGesture({ repeat: true })
// Repeatedly triggered when the long press gesture exists.
// When repeat is set to true, the event callback is triggered continuously when the gesture is detected. The triggering interval is specified by duration (500 ms by default).
.onAction((event: GestureEvent) => {
if (event.repeat) { this.count++ }
if (event.repeat) {
this.count++;
}
})
// Triggered when the long press gesture ends.
.onActionEnd(() => {
this.count = 0
this.count = 0;
})
)
}
.height(200)
.width(300)
.padding(20)
.border({ width: 3 })
.margin(30)
}
}
```
......
# PanGesture
**PanGesture** is used to trigger a pan gesture, which requires a minimum 5 vp movement distance of a finger on the screen.
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> **NOTE**
>
> 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
PanGesture(value?: { fingers?: number, direction?: PanDirection, distance?: number } | [PanGestureOptions](#pangestureoptions))
## APIs
**Parameters**
PanGesture(options?: { fingers?: number, direction?: PanDirection, distance?: number } | [PanGestureOption](#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**<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
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| fingers | number | No | 1 | Minimum number of fingers to trigger a long press gesture. The value ranges from 1 to 10. |
| direction | PanDirection | No | All | Slide direction. The enumerated value supports the AND (&amp;) and OR (\|) operations. |
| distance | number | No | 5.0 | Minimum slide recognition distance, in vp. |
## PanDirection enums
- PanDirection enums
| Name | Description |
| -------- | -------- |
| All | All directions. |
| Horizontal | Horizontal slide. |
| Vertical | Vertical slide. |
| Left | Slide to the left. |
| Right | Slide to the right. |
| Up | Slide up. |
| Down | Slide down. |
| None | Slide disabled. |
| Name| Description|
| -------- | -------- |
| All | All directions.|
| Horizontal | Horizontal panning.|
| Vertical | Vertical panning.|
| Left | Panning to the left.|
| Right | Panning to the right.|
| Up | Panning up.|
| Down | Panning down.|
| None | Panning disabled.|
### PanGestureOptions
## PanGestureOptions
The attributes of the slide gesture recognizer can be dynamically modified using the **PanGestureOptions** AP. This avoids modifying attributes through status 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 })
- Parameters
For details, see **PanGesture**.
**Parameters**
See the **PanGesture** parameters.
- APIs
| Name | Description |
| -------- | -------- |
| setDirection(value: PanDirection) | Sets the direction. |
| setDistance(value: number) | Sets the distance. |
| setFingers(value: number) | Sets the number of fingers. |
**APIs**
| Name| Description|
| -------- | -------- |
| setDirection(value: PanDirection) | Sets the direction.|
| setDistance(value: number) | Sets the distance.|
| setFingers(value: number) | Sets the number of fingers.|
## Events
| Name | Description |
| Name| Description|
| -------- | -------- |
| onActionStart(callback: (event?: GestureEvent) =&gt; void) | Callback for the pan gestures reorganization event. |
| onActionUpdate(callback: (event?: GestureEvent) =&gt; void) | Callback invoked when a pan gesture is recognized. |
| onActionEnd(callback: (event?: GestureEvent) =&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. |
- 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. |
| onActionStart(event: (event?: [GestureEvent](ts-gesture-settings.md)) =&gt; void) | Callback invoked when a pan gesture is recognized.|
| onActionUpdate(event: (event?: [GestureEvent](ts-gesture-settings.md)) =&gt; void) | Callback invoked when the pan gesture status is updated.|
| onActionEnd(event: (event?: [GestureEvent](ts-gesture-settings.md)) =&gt; void) | Callback invoked when the finger used for a pan gesture is lift.|
| onActionCancel(event: () =&gt; void) | Callback invoked when a tap cancellation event is received after a pan gesture is recognized.|
## Example
```
```ts
// xxx.ets
@Entry
@Component
struct PanGestureExample {
@State offsetX: number = 0
@State offsetY: number = 0
@State offsetX: number = 0;
@State offsetY: number = 0;
@State positionX: number = 0;
@State positionY: number = 0;
private panOption: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Left | PanDirection.Right });
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.SpaceBetween }) {
Column() {
Column() {
Text('PanGesture offset:\nX: ' + this.offsetX + '\n' + 'Y: ' + this.offsetY)
}
.height(100).width(200).padding(20).border({ width: 1 }).margin(80)
.translate({ x: this.offsetX, y: this.offsetY, z: 5 })
.height(200)
.width(300)
.padding(20)
.border({ width: 3 })
.margin(50)
.translate({ x: this.offsetX, y: this.offsetY, z: 0 })
// Pan left or right to trigger the gesture event.
.gesture(
PanGesture({})
PanGesture(this.panOption)
.onActionStart((event: GestureEvent) => {
console.info('Pan start')
console.info('Pan start');
})
.onActionUpdate((event: GestureEvent) => {
this.offsetX = event.offsetX
this.offsetY = event.offsetY
this.offsetX = this.positionX + event.offsetX;
this.offsetY = this.positionY + event.offsetY;
})
.onActionEnd(() => {
console.info('Pan end')
this.positionX = this.offsetX;
this.positionY = this.offsetY;
console.info('Pan end');
})
)
Button ('Set PanGesture Trigger Condition')
.onClick(() => {
// Set the pan gesture to be triggered by two fingers moving in any direction.
this.panOption.setDirection(PanDirection.All);
this.panOption.setFingers(2);
})
}
}
}
```
![en-us_image_0000001256978371](figures/en-us_image_0000001256978371.gif)
**Diagrams**
Pannig to the left:
![en-us_image_0000001174264374](figures/en-us_image_0000001174264374.png)
Click Set PanGesture Trigger Condition to two fingers moving toward the lower left corner.
![en-us_image1_0000001174264374](figures/en-us_image1_0000001174264374.png)
# PinchGesture
**PinchGesture** is used to trigger a pinch gesture, which requires two to five fingers with a minimum 3 vp distance between the fingers.
> **NOTE**
>
> 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
PinchGesture(options?: { fingers?: number, distance?: number })
PinchGesture(value?: { fingers?: number, distance?: number })
**Parameters**
| Name | Type | Mandatory | Default Value | 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. |
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| 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**|
## Events
| Name | Description |
| Name| Description|
| -------- | -------- |
| onActionStart((event?: GestureEvent) =&gt; void) | Callback invoked when a pinch gesture is recognized. |
| onActionUpdate((event?: GestureEvent) =&gt; void) | Callback invoked during the movement of a pinch gesture. |
| onActionEnd((event?: GestureEvent) =&gt; void) | Callback invoked 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. |
## 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. |
| onActionStart(event:(event?: [GestureEvent](ts-gesture-settings.md)) =&gt; void) | Triggered when a pinch gesture is recognized.|
| 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:(event?: [GestureEvent](ts-gesture-settings.md)) =&gt; void) | Triggered when the finger used for a pinch gesture is lift.|
| onActionCancel(event: () =&gt; void) | Triggered when a tap cancellation event is received after a pinch gesture is recognized.|
## Example
......@@ -47,28 +36,42 @@ PinchGesture(options?: { fingers?: number, distance?: number })
@Entry
@Component
struct PinchGestureExample {
@State scaleValue: number = 1
@State scaleValue: number = 1;
@State pinchValue: number = 1;
@State pinchX: number = 0;
@State pinchY: number = 0;
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.SpaceBetween }) {
Text('PinchGesture scale:' + this.scale)
Column() {
Column() {
Text('PinchGesture scale:\n' + this.scaleValue)
Text('PinchGesture center:\n(' + this.pinchX + ',' + this.pinchY + ')')
}
.height(100).width(200).padding(20).border({ width: 1 }).margin(80)
.scale({ x: this.scaleValue, y: this.scaleValue, z: this.scaleValue })
.height(200)
.width(300)
.padding(20)
.border({ width: 3 })
.margin({ top: 100 })
.scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
// The gesture event is triggered by pinching three fingers together.
.gesture(
PinchGesture()
PinchGesture({ fingers: 3 })
.onActionStart((event: GestureEvent) => {
console.info('Pinch start')
console.info('Pinch start');
})
.onActionUpdate((event: GestureEvent) => {
this.scaleValue = event.scale
this.scaleValue = this.pinchValue * event.scale;
this.pinchX = event.pinchCenterX;
this.pinchY = event.pinchCenterY;
})
.onActionEnd(() => {
console.info('Pinch end')
this.pinchValue = this.scaleValue;
console.info('Pinch end');
})
)
}.width('100%')
}
}
```
![en-us_image_0000001257058419](figures/en-us_image_0000001257058419.gif)
![en-us_image_0000001174582848](figures/en-us_image_0000001174582848.png)
# RotationGesture
**RotationGesture** is used to trigger a rotation gesture, which requires two to five fingers with a minimum 1-degree rotation angle.
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> **NOTE**
>
> 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
RotationGesture(options?: { fingers?: number, angle?: number })
RotationGesture(value?: { fingers?: number, angle?: number })
**Parameters**
- Parameters
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| fingers | number | No | 2 | Minimum number of fingers to trigger a rotation. The value ranges from 2 to 5. |
| angle | number | No | 1.0 | Minimum degree that can trigger the rotation gesture. |
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| fingers | number | No| Minimum number of fingers to trigger a rotation. The value ranges from 2 to 5.<br>Default value: **2**|
| angle | number | No| Minimum degree that can trigger the rotation gesture.<br>Default value: **1**|
## Events
| Name | Description |
| Parameter| Description|
| -------- | -------- |
| onActionStart((event?: GestureEvent) =&gt; void) | Callback invoked when a rotation gesture is recognized. |
| onActionUpdate((event?: GestureEvent) =&gt; void) | Callback invoked during the movement of the rotation gesture. |
| onActionEnd((event?: GestureEvent) =&gt; void) | Callback invoked 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. |
- GestureEvent attributes related to the rotation gesture
| Name | Type | Description |
| -------- | -------- | -------- |
| angle | number | Rotation angle. |
| onActionStart(event:(event?:&nbsp;[GestureEvent](ts-gesture-settings.md))&nbsp;=&gt;&nbsp;void) | Triggered when a rotation gesture is recognized.|
| onActionUpdate(event:(event?:&nbsp;[GestureEvent](ts-gesture-settings.md))&nbsp;=&gt;&nbsp;void) | Triggered when the user moves the finger in a rotation gesture on the screen.|
| onActionEnd(event:(event?:&nbsp;[GestureEvent](ts-gesture-settings.md))&nbsp;=&gt;&nbsp;void) | Triggered when the finger used for the rotation gesture is lift.|
| onActionCancel(event:&nbsp;()&nbsp;=&gt;&nbsp;void) | Triggered when a tap cancellation event is received after the rotation gesture is recognized.|
## Example
```
```ts
// xxx.ets
@Entry
@Component
struct RotationGestureExample {
@State angle: number = 0
@State angle: number = 0;
@State rotateValue: number = 0;
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.SpaceBetween }) {
Column() {
Column() {
Text('RotationGesture angle:' + this.angle)
}
.height(100).width(200).padding(20).border({ width:1 })
.margin(80).rotate({ x:1, y:2, z:3, angle: this.angle })
.height(200)
.width(300)
.padding(20)
.border({ width: 3 })
.margin(80)
.rotate({ angle: this.angle })
// The gesture event is triggered by rotating with two fingers.
.gesture(
RotationGesture()
.onActionStart((event: GestureEvent) => {
console.log('Rotation start')
console.info('Rotation start');
})
.onActionUpdate((event: GestureEvent) => {
this.angle = event.angle
this.angle = this.rotateValue + event.angle;
})
.onActionEnd(() => {
console.log('Rotation end')
this.rotateValue = this.angle;
console.info('Rotation end');
})
)
}.width('100%')
}
}
```
![en-us_image_0000001256858403](figures/en-us_image_0000001256858403.gif)
![en-us_image_0000001174264372](figures/en-us_image_0000001174264372.png)
# SwipeGesture
**\<SwipeGesture>** is used to implement a swipe gesture, which can be recognized when the swipe speed is 100 vp/s or higher.
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> **NOTE**
>
> 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
SwipeGesture(value?: { fingers?: number; direction?: SwipeDirection; speed?: number })
- 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). |
**Parameters**
- SwipeDirection enums
| Name | Description |
| -------- | -------- |
| All | All directions. |
| Horizontal | Horizontal direction. |
| Vertical | Vertical direction. |
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| fingers | number | No| Minimum number of fingers to trigger a swipe gesture. The value ranges from 1 to 10.<br>Default value: **1**|
| direction | SwipeDirection | No| Swipe direction.<br>Default value: **SwipeDirection.All**|
| speed | number | No| Minimum speed of the swipe gesture, in vp/s.<br>Default value: **100**|
## SwipeDirection
## Events
| Name | Description |
| Name| Description|
| -------- | -------- |
| onAction(callback:(event?: GestureEvent) =&gt; void) | Callback 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
| Name | Type | Description |
| -------- | -------- | -------- |
| angle | number | Angle of the swipe gesture.<br/>>&nbsp;![icon-note.gif](public_sys-resources/icon-note.gif)&nbsp;**NOTE**<br/>>&nbsp;Angle calculation method: After the swipe gesture is identified, 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. |
## Events
![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.|
## Example
```
```ts
// xxx.ets
@Entry
@Component
struct SwipeGestureExample {
@State rotateAngle : number = 0
@State speed : number = 1
@State rotateAngle: number = 0;
@State speed: number = 1;
build() {
Column() {
Text("SwipGesture speed : " + this.speed)
Text("SwipGesture angle : " + this.rotateAngle)
Column() {
Text("SwipeGesture speed\n" + this.speed)
Text("SwipeGesture angle\n" + this.rotateAngle)
}
.position({x: 80, y: 200})
.border({width:2})
.width(260).height(260)
.rotate({x: 0, y: 0, z: 1, angle: this.rotateAngle})
.border({ width: 3 })
.width(300)
.height(200)
.margin(100)
.rotate({ angle: this.rotateAngle })
// The gesture event is triggered by swiping vertically with one finger.
.gesture(
SwipeGesture({fingers: 1, direction:SwipeDirection.Vertical})
SwipeGesture({ direction: SwipeDirection.Vertical })
.onAction((event: GestureEvent) => {
this.speed = event.speed
this.rotateAngle = event.angle
this.speed = event.speed;
this.rotateAngle = event.angle;
})
)
}.width('100%')
}
}
```
![en-us_image_0000001231374559](figures/en-us_image_0000001231374559.gif)
![en-us_image_0000001231374559.png](figures/en-us_image_0000001231374559.png)
# TapGesture
**TapGesture** is used to trigger a tap gesture with one or more taps.
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> **NOTE**
>
> 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
TapGesture(options?: { count?: number, fingers?: number })
TapGesture(value?: { count?: number, fingers?: number })
- Parameters
| Name | Type | Mandatory | Default Value | 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/>> ![icon-note.gif](public_sys-resources/icon-note.gif) **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/>> ![icon-note.gif](public_sys-resources/icon-note.gif) **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/>> <br/>> 2. Gesture recognition fails if the number of fingers used for tap exceeds the configured number. |
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| 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| Number of fingers required 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 of tapping by the first finger.<br>> 2. The gesture will fail to be recognized if the number of fingers used for tapping exceeds the configured number.|
## Events
| Name | Description |
| Name| Description|
| -------- | -------- |
| onAction((event?: GestureEvent) =&gt; 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
```
```ts
// xxx.ets
@Entry
@Component
struct TapGestureExample {
@State value: string = ''
@State value: string = '';
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.SpaceBetween }) {
Text('Click twice')
Text(this.value)
}
.height(200).width(300).padding(60).border({ width: 1 }).margin(30)
Column() {
// The gesture event is triggered by double-tapping.
Text('Click twice').fontSize(28)
.gesture(
TapGesture({ count: 2 })
.onAction(() => {
this.value = 'TapGesture onAction'
.onAction((event: GestureEvent) => {
this.value = JSON.stringify(event.fingerList[0]);
})
)
Text(this.value)
}
.height(200)
.width(300)
.padding(20)
.border({ width: 3 })
.margin(30)
}
}
```
......
# CanvasRenderingContext2D
The **\<RenderingContext>** component is used to draw rectangles, text, images, and other objects on a canvas.
Use **RenderingContext** to draw rectangles, text, images, and other objects on a canvas.
> **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
CanvasRenderingContext2D(setting: RenderingContextSetting)
- Parameters
| Name | Type | Mandatory | Default Value | Description |
| ------- | ---------------------------------------- | --------- | ------------- | ----------------------------- |
| setting | [RenderingContextSettings](#renderingcontextsettings) | Yes | - | See [RenderingContextSettings](#renderingcontextsettings). |
**Parameters**
| Name | Type | Mandatory | Description |
| ------- | ---------------------------------------- | ---- | ---------------------------------------- |
| setting | [RenderingContextSettings](#renderingcontextsettings) | Yes | See [RenderingContextSettings](#renderingcontextsettings).|
### RenderingContextSettings
RenderingContextSettings(antialias?: bool)
RenderingContextSettings(antialias?: boolean)
Configures the settings of a **CanvasRenderingContext2D** object, including whether to enable antialiasing.
- Parameters
| Name | Type | Mandatory | Default Value | Description |
| --------- | ---- | --------- | ------------- | -------------------------------- |
| antialias | bool | No | false | Whether antialiasing is enabled. |
**Parameters**
| Name | Type | Mandatory | Description |
| --------- | ------- | ---- | ----------------------------- |
| antialias | boolean | No | Whether antialiasing is enabled.<br>Default value: **false**|
## Attributes
| Name | Type | Default Value | 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. |
| [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. |
| [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. |
| [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**. |
| [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. |
| [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'**. |
| [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'**. |
| [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. |
| [globalAlpha](#globalalpha) | number | - | Opacity. **0.0**: completely transparent; **1.0**: completely opaque. |
| [lineDashOffset](#linedashoffset) | number | 0.0 | Offset of the dashed line. The precision is float. |
| [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'**. |
| [shadowBlur](#shadowblur) | number | 0.0 | Blur level during shadow drawing. A larger value indicates a more blurred effect. The precision is float. |
| [shadowColor](#shadowcolor) | &lt;color&gt; | - | Shadow color. |
| [shadowOffsetX](#shadowoffsetx) | number | - | X-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. |
| imageSmoothingQuality | string | 'low' | Image smoothness. The value can be **'low'**, **'medium'**, or **'high'**. |
> **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.
| Name | Type | Description |
| ---------------------------------------- | ---------------------------------------- | ---------------------------------------- |
| [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. |
| [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) | 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) | 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 | 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 | 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) | 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) | 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.<br>**0.0**: completely transparent.<br>**1.0**: completely opaque. |
| [lineDashOffset](#linedashoffset) | number | Offset of the dashed line. The precision is float.<br>Default value: **0.0** |
| [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 | Blur level during shadow drawing. A larger value indicates a more blurred effect. The precision is float.<br>Default value: **0.0**|
| [shadowColor](#shadowcolor) | string | Shadow color. |
| [shadowOffsetX](#shadowoffsetx) | number | X-axis shadow offset relative to the original object. |
| [shadowOffsetY](#shadowoffsety) | number | Y-axis shadow offset relative to the original object. |
| [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**|
> **NOTE**
>
> 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
......@@ -62,8 +66,8 @@ Configures the settings of a **CanvasRenderingContext2D** object, including whet
@Entry
@Component
struct FillStyleExample {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
......@@ -92,8 +96,8 @@ struct FillStyleExample {
@Entry
@Component
struct LineWidthExample {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
......@@ -122,8 +126,8 @@ struct LineWidthExample {
@Entry
@Component
struct StrokeStyleExample {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
......@@ -154,8 +158,8 @@ struct StrokeStyleExample {
@Entry
@Component
struct LineCapExample {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
......@@ -188,8 +192,8 @@ struct LineCapExample {
@Entry
@Component
struct LineJoinExample {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
......@@ -223,8 +227,8 @@ struct LineJoinExample {
@Entry
@Component
struct MiterLimit {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
......@@ -257,9 +261,9 @@ struct MiterLimit {
// xxx.ets
@Entry
@Component
struct Font {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
struct Fonts {
private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
......@@ -288,8 +292,8 @@ struct Font {
@Entry
@Component
struct CanvasExample {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
......@@ -333,8 +337,8 @@ struct CanvasExample {
@Entry
@Component
struct TextBaseline {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
......@@ -378,8 +382,8 @@ struct TextBaseline {
@Entry
@Component
struct GlobalAlpha {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
......@@ -401,7 +405,7 @@ struct GlobalAlpha {
}
```
![en-us_image_0000001212218444](figures/en-us_image_0000001212218444.png)
![en-us_image_0000001194192434](figures/en-us_image_0000001194192434.png)
### lineDashOffset
......@@ -411,8 +415,8 @@ struct GlobalAlpha {
@Entry
@Component
struct LineDashOffset {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
......@@ -423,6 +427,7 @@ struct LineDashOffset {
.onReady(() =>{
this.context.arc(100, 75, 50, 0, 6.28)
this.context.setLineDash([10,20])
this.context.lineDashOffset = 10.0;
this.context.stroke();
})
}
......@@ -432,32 +437,32 @@ struct LineDashOffset {
}
```
![en-us_image_0000001212058480](figures/en-us_image_0000001212058480.png)
![en-us_image_0000001194352434](figures/en-us_image_0000001194352434.png)
### globalCompositeOperation
| Name | Description |
| ---------------- | ---------------------------------------- |
| ---------------- | ------------------------ |
| 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-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-atop | Displays the existing drawing on the top of 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. |
| lighter | Displays both the new drawing and the existing drawing. |
| destination-out | Displays the existing drawing outside the new drawing. |
| lighter | Displays both the new and 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
// xxx.ets
@Entry
@Component
struct GlobalCompositeOperation {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
......@@ -526,8 +531,8 @@ struct ShadowBlur {
@Entry
@Component
struct ShadowColor {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
......@@ -558,8 +563,8 @@ struct ShadowColor {
@Entry
@Component
struct ShadowOffsetX {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
......@@ -591,8 +596,8 @@ struct ShadowOffsetX {
@Entry
@Component
struct ShadowOffsetY {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
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)
......@@ -623,9 +628,9 @@ struct ShadowOffsetY {
@Entry
@Component
struct ImageSmoothingEnabled {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private img:ImageBitmap = new ImageBitmap("common/images/icon.jpg")
private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
private img:ImageBitmap = new ImageBitmap("common/images/icon.jpg");
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
......@@ -656,23 +661,24 @@ fillRect(x: number, y: number, w: number, h: number): void
Fills a rectangle on the canvas.
- 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. |
**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
**Example**
```ts
// xxx.ets
@Entry
@Component
struct FillRect {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
......@@ -699,23 +705,25 @@ strokeRect(x: number, y: number, w: number, h: number): void
Draws an outlined rectangle on the canvas.
- 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. |
**Parameters**
- 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
@Component
struct StrokeRect {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
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)
......@@ -741,33 +749,35 @@ clearRect(x: number, y: number, w: number, h: number): void
Clears the content in a rectangle on the canvas.
- 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. |
**Parameters**
- 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
@Component
struct ClearRect {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
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')
.backgroundColor('#ffffff')
.onReady(() =>{
this.context.fillStyle = 'rgb(0,0,255)'
this.context.fillRect(0,0,500,500)
this.context.clearRect(20,20,150,100)
this.context.fillRect(20,20,200,200)
this.context.clearRect(30,30,150,100)
})
}
.width('100%')
......@@ -781,26 +791,29 @@ Clears the content in a rectangle on the canvas.
### 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.
- 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. |
**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.|
| maxWidth | number | No | - | Maximum width allowed for the text. |
- Example
**Example**
```ts
// xxx.ets
@Entry
@Component
struct FillText {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
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)
......@@ -823,26 +836,29 @@ Draws filled text on the canvas.
### 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.
- 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. |
**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.|
| maxWidth | number | No | - | Maximum width of the text to be drawn. |
- Example
**Example**
```ts
// xxx.ets
@Entry
@Component
struct StrokeText {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
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)
......@@ -867,32 +883,51 @@ Draws a text stroke on the canvas.
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 |
| ---- | ------ | --------- | ------------- | -------------------- |
| text | string | Yes | "" | Text to be measured. |
| Name | Type | Mandatory | Default Value | Description |
| ---- | ------ | ---- | ---- | ---------- |
| text | string | Yes | "" | Text to be measured.|
- Return value
| Type | Description |
| ----------- | ----------------------- |
| TextMetrics | **TextMetrics** object. |
**Return value**
- **TextMetrics** attributes
| Name | Type | Description |
| ----- | ------ | ------------------ |
| width | number | Width of the text. |
| Type | Description |
| ----------- | ------- |
| TextMetrics | **TextMetrics** object.|
- 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
// xxx.ets
@Entry
@Component
struct MeasureText {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
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)
......@@ -920,20 +955,21 @@ stroke(path?: Path2D): void
Strokes a path.
- Parameters
| Name | Type | Mandatory | Default Value | Description |
| ---- | ---------------------------------------- | --------- | ------------- | -------------------------- |
| path | [Path2D](ts-components-canvas-path2d.md) | No | null | A **Path2D** path to draw. |
**Parameters**
- Example
| Name | Type | Mandatory | Default Value | Description |
| ---- | ---------------------------------------- | ---- | ---- | ------------ |
| path | [Path2D](ts-components-canvas-path2d.md) | No | null | A **Path2D** path to draw.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct Stroke {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
......@@ -944,6 +980,8 @@ Strokes a path.
.onReady(() =>{
this.context.moveTo(25, 25)
this.context.lineTo(25, 105)
this.context.lineTo(75, 105)
this.context.lineTo(75, 25)
this.context.strokeStyle = 'rgb(0,0,255)'
this.context.stroke()
})
......@@ -963,15 +1001,15 @@ beginPath(): void
Creates a drawing path.
- Example
**Example**
```ts
// xxx.ets
@Entry
@Component
struct BeginPath {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
......@@ -1003,21 +1041,22 @@ moveTo(x: number, y: number): void
Moves a drawing path to a target position on the canvas.
- 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. |
**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
**Example**
```ts
// xxx.ets
@Entry
@Component
struct MoveTo {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
......@@ -1047,21 +1086,22 @@ lineTo(x: number, y: number): void
Connects the current point to a target position using a straight line.
- 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. |
**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
**Example**
```ts
// xxx.ets
@Entry
@Component
struct LineTo {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
......@@ -1091,15 +1131,15 @@ closePath(): void
Draws a closed path.
- Example
**Example**
```ts
// xxx.ets
@Entry
@Component
struct ClosePath {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
......@@ -1127,26 +1167,33 @@ Draws a closed path.
### 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.
- 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'**. |
**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"**.|
**Return value**
- Example
| Type | Description |
| ------------------------------- | ----------------------- |
| [CanvasPattern](#canvaspattern) | Created pattern for image filling based on a specified source image and repetition mode.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct CreatePattern {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private img:ImageBitmap = new ImageBitmap("common/images/icon.jpg")
private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
private img:ImageBitmap = new ImageBitmap("common/images/icon.jpg");
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
......@@ -1175,25 +1222,26 @@ bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number,
Draws a cubic bezier curve on the canvas.
- Parameters
| 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. |
| cp2x | number | Yes | 0 | X-coordinate of the second parameter of the bezier curve. |
| cp2y | number | Yes | 0 | Y-coordinate of the second parameter of 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. |
**Parameters**
- Example
| 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.|
| cp2x | number | Yes | 0 | X-coordinate of the second parameter of the bezier curve.|
| cp2y | number | Yes | 0 | Y-coordinate of the second parameter of 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**
```ts
// xxx.ets
@Entry
@Component
struct BezierCurveTo {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
......@@ -1223,15 +1271,16 @@ quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void
Draws a quadratic curve on the canvas.
- 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. |
**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
**Example**
```ts
// xxx.ets
......@@ -1240,6 +1289,7 @@ Draws a quadratic curve on the canvas.
struct QuadraticCurveTo {
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)
......@@ -1264,28 +1314,30 @@ Draws a quadratic curve on the canvas.
### 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.
- Parameters
| 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. |
| radius | number | Yes | 0 | Radius of the arc. |
| startAngle | number | Yes | 0 | Start radian of the arc. |
| endAngle | number | Yes | 0 | End radian of the arc. |
| anticlockwise | boolean | No | false | Whether to draw the arc counterclockwise. |
**Parameters**
- Example
| 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.|
| radius | number | Yes | 0 | Radius of the arc. |
| startAngle | number | Yes | 0 | Start radian of the arc. |
| endAngle | number | Yes | 0 | End radian of the arc. |
| counterclockwise | boolean | No | false | Whether to draw the arc counterclockwise.|
```
**Example**
```ts
// xxx.ets
@Entry
@Component
struct Arc {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
......@@ -1314,24 +1366,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.
- 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. |
**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
**Example**
```ts
// xxx.ets
@Entry
@Component
struct ArcTo {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
......@@ -1356,32 +1409,32 @@ Draws an arc based on the radius and points on the arc.
### 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
| 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. |
**Parameters**
- 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
// xxx.ets
@Entry
@Component
struct CanvasExample {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
......@@ -1391,7 +1444,7 @@ Draws an ellipse in the specified rectangular region.
.backgroundColor('#ffff00')
.onReady(() =>{
this.context.beginPath()
this.context.ellipse(200, 200, 50, 100, Math.PI * 0.25, Math.PI * 0.5, Math.PI)
this.context.ellipse(200, 200, 50, 100, Math.PI * 0.25, Math.PI * 0.5, Math.PI * 2)
this.context.stroke()
})
}
......@@ -1406,27 +1459,28 @@ Draws an ellipse in the specified rectangular region.
### 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
| 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. |
**Parameters**
- 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
@Component
struct CanvasExample {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
......@@ -1450,19 +1504,26 @@ Creates a rectangle.
### fill
fill(): void
fill(fillRule?: CanvasFillRule): void
Fills the area inside a closed path on the canvas.
Fills the area inside a closed 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 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)
private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
......@@ -1484,21 +1545,78 @@ Fills the area inside a closed path.
![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(): void
clip(fillRule?: CanvasFillRule): void
Sets the current path to a clipping path.
Sets the current path to a clipping area.
**Parameters**
| 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
**Example**
```ts
// xxx.ets
@Entry
@Component
struct Clip {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
......@@ -1507,11 +1625,11 @@ Sets the current path to a clipping path.
.height('100%')
.backgroundColor('#ffff00')
.onReady(() =>{
this.context.rect(0, 0, 200, 200)
this.context.rect(0, 0, 100, 200)
this.context.stroke()
this.context.clip()
this.context.fillStyle = "rgb(255,0,0)"
this.context.fillRect(0, 0, 150, 150)
this.context.fillRect(0, 0, 200, 200)
})
}
.width('100%')
......@@ -1523,26 +1641,106 @@ Sets the current path to a clipping path.
![en-us_image_0000001211898488](figures/en-us_image_0000001211898488.png)
clip(path: Path2D, fillRule?: CanvasFillRule): void
Sets the current path to a clipping path.
**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"**.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct Clip {
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.rect(80,10,20,130);
region.rect(40,50,100,50);
this.context.clip(region,"evenodd")
this.context.fillStyle = "rgb(255,0,0)"
this.context.fillRect(0, 0, this.context.width, this.context.height)
})
}
.width('100%')
.height('100%')
}
}
```
![en-us_image_000000127777779](figures/en-us_image_000000127777779.png)
### filter
filter(filter: string): void
Provides filter effects. This API is a void 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 void API.
### resetTransform
resetTransform(): void
Resets the current transform to the identity matrix. This API is a void API.
### direction
direction(direction: CanvasDirection): void
Sets the current text direction used to draw text. This API is a void API.
### rotate
rotate(rotate: number): void
rotate(angle: number): void
Rotates a canvas clockwise around its coordinate axes.
- 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. |
**Parameters**
- 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
// xxx.ets
@Entry
@Component
struct Rotate {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
......@@ -1568,23 +1766,24 @@ Rotates a canvas clockwise around its coordinate axes.
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. |
| Name | Type | Mandatory | Default Value | Description |
| ---- | ------ | ---- | ---- | ----------- |
| x | number | Yes | 0 | Horizontal scale factor.|
| y | number | Yes | 0 | Vertical scale factor.|
- Example
**Example**
```ts
// xxx.ets
@Entry
@Component
struct Scale {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
......@@ -1593,9 +1792,10 @@ Scales a canvas based on scale factors.
.height('100%')
.backgroundColor('#ffff00')
.onReady(() =>{
this.context.strokeRect(10, 10, 25, 25)
this.context.lineWidth = 3
this.context.strokeRect(30, 30, 50, 50)
this.context.scale(2, 2) // Scale to 200%
this.context.strokeRect(10, 10, 25, 25)
this.context.strokeRect(30, 30, 50, 50)
})
}
.width('100%')
......@@ -1609,36 +1809,38 @@ Scales a canvas based on scale factors.
### 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.
> **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.
>
> - x' = scaleX \* x + skewY \* y + translateX
>
> - y' = skewX \* x + scaleY \* y + translateY
- 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. |
**Parameters**
- 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
// xxx.ets
@Entry
@Component
struct Transform {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
......@@ -1668,29 +1870,30 @@ Defines a transformation matrix. To transform a graph, you only need to set para
### 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()** API.
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 |
| ---------- | ------ | --------- | ------------- | ------------------- |
| 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. |
| 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
**Example**
```ts
// xxx.ets
@Entry
@Component
struct SetTransform {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
......@@ -1715,27 +1918,33 @@ Resets the existing transformation matrix and creates a new transformation matri
![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 void API.
### translate
translate(x: number, y: number): void
Moves the origin of the coordinate system.
- Parameters
| Name | Type | Mandatory | Default Value | Description |
| ---- | ------ | --------- | ------------- | ------------------- |
| x | number | Yes | 0 | X-axis translation. |
| y | number | Yes | 0 | Y-axis translation. |
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ---- | ------ | ---- | ---- | -------- |
| x | number | Yes | 0 | X-axis translation.|
| y | number | Yes | 0 | Y-axis translation.|
- Example
**Example**
```ts
// xxx.ets
@Entry
@Component
struct Translate {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
......@@ -1762,27 +1971,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, 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
| 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. |
| 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. 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. |
| 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. |
**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** 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. 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.|
- Example
**Example**
```ts
// xxx.ets
......@@ -1792,6 +2002,7 @@ Draws an image.
private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
private img:ImageBitmap = new ImageBitmap("common/images/example.jpg");
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context)
......@@ -1813,81 +2024,139 @@ Draws an image.
### 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](ts-components-canvas-imagedata.md)** object with the specified dimensions.
- Parameters
| Name | Type | Mandatory | Default Value | Description |
| ------ | ------ | --------- | ------------- | ----------------------------------- |
| width | number | Yes | 0 | Width of the **ImageData** object. |
| height | number | Yes | 0 | Height of the **ImageData** object. |
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ---- | ------ | ---- | ---- | ------------- |
| sw | number | Yes | 0 | Width of the **ImageData** object.|
| sh | number | Yes | 0 | Height of the **ImageData** object.|
### createImageData
createImageData(imageData: Object): Object
createImageData(imageData: ImageData): ImageData
Creates an **[ImageData](ts-components-canvas-imagedata.md)** object.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| --------- | ---------------------------------------- | ---- | ---- | ----------------- |
| imagedata | [ImageData](ts-components-canvas-imagedata.md) | Yes | null | **ImageData** object with the same width and height copied from the original **ImageData** object.|
Creates an **ImageData** object. For details, see [ImageData](ts-components-canvas-imagebitmap.md).
**Return value**
| Type | Description |
| ---------------------------------------- | -------------- |
| [ImageData](ts-components-canvas-imagedata.md) | New **ImageData** object.|
- Parameters
| Name | Type | Mandatory | Default Value | Description |
| --------- | ------ | --------- | ------------- | ---------------------------------------- |
| imagedata | Object | Yes | null | **ImageData** object with the same width and height copied from the original **ImageData** object. |
### getPixelMap
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.
- Parameters
| Name | 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.|
| sw | number | Yes | 0 | Width of the output area. |
| sh | number | Yes | 0 | Height of the output area. |
**Parameters**
| Name | 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.|
| 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(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-imagedata.md)** object created with the pixels within the specified area on the canvas.
**Parameters**
| Name | 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.|
| 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-imagedata.md) | New **ImageData** object.|
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 |
| ---- | ------ | --------- | ------------- | ---------------------------------------- |
| 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. |
| sw | number | Yes | 0 | Width of the output area. |
| sh | number | Yes | 0 | Height of the output area. |
**Example**
```ts
// xxx.ets
@Entry
@Component
struct GetImageData {
private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
private img:ImageBitmap = new ImageBitmap("/common/images/1234.png")
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context)
.width('100%')
.height('100%')
.backgroundColor('#ffff00')
.onReady(() =>{
this.context.drawImage(this.img,0,0,130,130);
var imagedata = this.context.getImageData(50,50,130,130);
this.context.putImageData(imagedata,150,150);
})
}
.width('100%')
.height('100%')
}
}
```
![en-us_image_000000127777780](figures/en-us_image_000000127777780.png)
### 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 the **[ImageData](ts-components-canvas-imagebitmap.md)** onto a rectangular area on the canvas.
Puts an **[ImageData](ts-components-canvas-imagedata.md)** object onto a rectangular area on the canvas.
- Parameters
| Name | 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. |
| 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. |
| 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. |
| dirtyHeight | number | No | Height of the **ImageData** object | Height of the rectangular area to crop the source image. |
**Parameters**
- Example
| Name | Type | Mandatory | Default Value | Description |
| ----------- | ---------------------------------------- | ---- | ------------ | ----------------------------- |
| imagedata | [ImageData](ts-components-canvas-imagedata.md) | 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. |
| 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.|
| 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. |
| dirtyHeight | number | No | Height of the **ImageData** object| Height of the rectangular area to crop the source image. |
**Example**
```ts
// xxx.ets
@Entry
@Component
struct PutImageData {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
......@@ -1915,21 +2184,231 @@ Puts the **[ImageData](ts-components-canvas-imagebitmap.md)** onto a rectangular
![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])
this.context.stroke()
})
}
.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 CanvasGetLineDash {
@State message: string = 'Hello World'
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() {
Row() {
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
.onClick(()=>{
console.error('before getlinedash clicked')
let res = this.context.getLineDash()
console.error(JSON.stringify(res))
})
Canvas(this.context)
.width('100%')
.height('100%')
.backgroundColor('#ffff00')
.onReady(() => {
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%')
}
}
```
![en-us_image_000000127777778](figures/en-us_image_000000127777778.png)
### imageSmoothingQuality
imageSmoothingQuality(quality: imageSmoothingQuality)
Sets the quality of image smoothing. This API is a void 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 | [ImageBitmap](ts-components-canvas-imagebitmap.md) | **ImageBitmap** object to display.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct TransferFromImageBitmap {
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(): void
Restores the saved drawing context.
- Example
**Example**
```ts
// xxx.ets
@Entry
@Component
struct CanvasExample {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
private img:ImageBitmap = new ImageBitmap("common/images/icon.jpg")
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
......@@ -1938,7 +2417,11 @@ Restores the saved drawing context.
.height('100%')
.backgroundColor('#ffff00')
.onReady(() =>{
this.context.restore()
this.context.save(); // save the default state
this.context.fillStyle = "green";
this.context.fillRect(20, 20, 100, 100);
this.context.restore(); // restore to the default state
this.context.fillRect(150, 75, 100, 100);
})
}
.width('100%')
......@@ -1946,23 +2429,24 @@ Restores the saved drawing context.
}
}
```
![en-us_image_000000127777781](figures/en-us_image_000000127777781.png)
### save
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
// xxx.ets
@Entry
@Component
struct CanvasExample {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
......@@ -1971,7 +2455,11 @@ Saves the current drawing context.
.height('100%')
.backgroundColor('#ffff00')
.onReady(() =>{
this.context.save()
this.context.save(); // save the default state
this.context.fillStyle = "green";
this.context.fillRect(20, 20, 100, 100);
this.context.restore(); // restore to the default state
this.context.fillRect(150, 75, 100, 100);
})
}
.width('100%')
......@@ -1979,6 +2467,7 @@ Saves the current drawing context.
}
}
```
![en-us_image_000000127777781](figures/en-us_image_000000127777781.png)
### createLinearGradient
......@@ -1987,23 +2476,24 @@ createLinearGradient(x0: number, y0: number, x1: number, y1: number): void
Creates a linear gradient.
- Parameters
| 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. |
| x1 | number | Yes | 0 | X-coordinate of the end point. |
| y1 | number | Yes | 0 | Y-coordinate of the end point. |
**Parameters**
| 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.|
| x1 | number | Yes | 0 | X-coordinate of the end point.|
| y1 | number | Yes | 0 | Y-coordinate of the end point.|
- Example
**Example**
```ts
// xxx.ets
@Entry
@Component
struct CreateLinearGradient {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
......@@ -2035,25 +2525,26 @@ createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number,
Creates a linear gradient.
- Parameters
| 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. |
| r0 | number | Yes | 0 | Radius of the start circle, which must be a non-negative finite number. |
| x1 | number | Yes | 0 | X-coordinate of the center of the end circle. |
| 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. |
**Parameters**
- Example
| 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. |
| r0 | number | Yes | 0 | Radius of the start circle, which must be a non-negative finite number.|
| x1 | number | Yes | 0 | X-coordinate of the center of the end circle. |
| 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**
```ts
// xxx.ets
@Entry
@Component
struct CreateRadialGradient {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
......@@ -2081,4 +2572,4 @@ Creates a linear gradient.
## CanvasPattern
Defines an object created by using the [createPattern](#createpattern) method.
Defines an object created using the **[createPattern](#createpattern)** API.
# Canvas
The **\<Canvas>** component can be used to customize drawings.
> **NOTE**
>
> 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
None
## Child Components
Not supported
## APIs
Canvas(context: CanvasRenderingContext2D)
Canvas(context?: CanvasRenderingContext2D)
- Parameters
| Name | Type | Mandatory | Default Value | Description |
| ------- | ---------------------------------------- | --------- | ------------- | ---------------------------------------- |
| context | [CanvasRenderingContext2D](ts-canvasrenderingcontext2d.md) | Yes | - | For details, see CanvasRenderingContext2D. |
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ------- | ---------------------------------------- | ---- | ---- | ---------------------------- |
| context | [CanvasRenderingContext2D](ts-canvasrenderingcontext2d.md) | No | - | For details, see **CanvasRenderingContext2D**.|
## Attributes
Universal attributes are supported.
The [universal attributes](ts-universal-attributes-size.md) are supported.
## 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 the canvas is ready for drawing. |
| ----------------------------- | ---- | -------------------- |
| onReady(event: () => void) | - | Triggered when a canvas is ready. |
## Example
**Example**
```
```ts
// xxx.ets
@Entry
@Component
struct CanvasExample {
......@@ -58,8 +55,8 @@ struct CanvasExample {
.width('100%')
.height('100%')
.backgroundColor('#ffff00')
.onReady(() =>{
this.context.fillRect(0,30,100,100)
.onReady(() => {
this.context.fillRect(0, 30, 100, 100)
})
}
.width('100%')
......@@ -67,3 +64,4 @@ struct CanvasExample {
}
}
```
![en-us_image_0000001194032666](figures/en-us_image_0000001194032666.png)
# CanvasGradient
**CanvasGradient** provides a canvas gradient object.
> ![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.
> **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.
**CanvasGradient** provides a gradient object.
## addColorStop
......@@ -14,15 +14,19 @@ addColorStop(offset: number, color: string): void
Adds a color stop for the **CanvasGradient** object based on the specified offset and gradient color.
- Parameters
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ------ | ------ | --------- | ------------- | ---------------------------------------- |
| offset | number | Yes | 0 | Proportion of the distance between the color stop and the start point to the total length. The value ranges from 0 to 1. |
| color | string | Yes | 'ffffff' | Gradient color to set. |
| ------ | ------ | ---- | --------- | ---------------------------- |
| 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. |
- Example
```
**Example**
```ts
// xxx.ets
@Entry
@Component
struct Page45 {
......@@ -37,17 +41,17 @@ Adds a color stop for the **CanvasGradient** object based on the specified offse
.backgroundColor('#ffff00')
.onReady(() =>{
var grad = this.context.createLinearGradient(50,0, 300,100)
this.grad.addColorStop(0.0, 'red')
this.grad.addColorStop(0.5, 'white')
this.grad.addColorStop(1.0, 'green')
grad.addColorStop(0.0, 'red')
grad.addColorStop(0.5, 'white')
grad.addColorStop(1.0, 'green')
this.context.fillStyle = grad
this.context.fillRect(0, 0, 500, 500)
})
}
.width('100%')
.height('100%')
}
}
}}
```
![en-us_image_0000001256858381](figures/en-us_image_0000001256858381.png)
# ImageBitmap
An **ImageBitmap** object stores pixel data rendered on a canvas.
> ![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.
> **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.
**CanvasImageData** stores pixel data rendered on a canvas.
## Attributes
| Name | Type | Description |
| Name| Type| Description|
| -------- | -------- | -------- |
| width | number | Actual width 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. |
| width | number | Pixel width of the **ImageBitmap** object.|
| height | number | Pixel height of the **ImageBitmap** object.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct ImageExample {
private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
private img:ImageBitmap = new ImageBitmap("common/images/example.jpg");
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context)
.width('100%')
.height('100%')
.backgroundColor('#ffff00')
.onReady(() =>{
this.context.drawImage( this.img,0,0,500,500,0,0,400,200);
})
}
.width('100%')
.height('100%')
}
}
```
![en-us_image_0000001194352442](figures/en-us_image_0000001194352442.png)
## Methods
### close
close()
Releases all graphics resources associated with this **ImageBitmap** object. This API is a void API.
# ImageData
An **ImageData** object stores pixel data rendered on a canvas.
> ![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.
> **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.
**ImageData** stores pixel data rendered on a canvas.
## Attributes
| Name | Type | Description |
| Name| Type| Description|
| -------- | -------- | -------- |
| width | number | Actual width 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. |
| width | number | Actual width of the rectangle on the canvas, in pixels.|
| height | number | Actual height of the rectangle on the canvas, in pixels.|
| data | Uint8ClampedArray | A one-dimensional array of color values. The values range from 0 to 255.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct Translate {
private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
private img:ImageBitmap = new ImageBitmap("/common/images/1234.png")
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context)
.width('100%')
.height('100%')
.backgroundColor('#ffff00')
.onReady(() =>{
this.context.drawImage(this.img,0,0,130,130);
var imagedata = this.context.getImageData(50,50,130,130);
this.context.putImageData(imagedata,150,150);
})
}
.width('100%')
.height('100%')
}
}
```
![en-us_image_000000127777780](figures/en-us_image_000000127777780.png)
......@@ -7,10 +7,6 @@
> 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
## Modules to Import
......@@ -33,10 +29,11 @@ path: string, container: object, render: string, loop: boolean, autoplay: boolea
Loads an animation. Before calling this method, declare the **Animator('\__lottie\_ets')** object and check that the canvas layout is complete. This method can be used together with a lifecycle callback of the **Canvas** component, for example, **onAppear()** and **onPageShow()**.
- Parameters
**Parameters**
| 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.|
| 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.|
......@@ -51,12 +48,13 @@ 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()**.
- Parameters
**Parameters**
| 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.|
- Example
**Example**
```ts
// xxx.ets
import lottie from '@ohos/lottieETS'
......@@ -91,7 +89,7 @@ Destroys the animation. This method must be called when a page exits. This metho
path: this.animatePath,
})
})
// @ts-ignore
Animator('__lottie_ets') // declare Animator('__lottie_ets') when use lottie
Button('load animation')
.onClick(() => {
......@@ -131,12 +129,14 @@ play(name: string): void
Plays a specified animation.
- Parameters
**Parameters**
| 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.|
- Example
**Example**
```ts
lottie.play(this.animateName)
```
......@@ -148,12 +148,14 @@ pause(name: string): void
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 | 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.|
- Example
**Example**
```ts
lottie.pause(this.animateName)
```
......@@ -165,12 +167,14 @@ togglePause(name: string): void
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 | string | Yes | Name of the target animation, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are paused.|
- Example
**Example**
```ts
lottie.togglePause(this.animateName)
```
......@@ -182,12 +186,14 @@ stop(name: string): void
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 | string | Yes | Name of the target animation, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are paused.|
- Example
**Example**
```ts
lottie.stop(this.animateName)
```
......@@ -199,13 +205,15 @@ setSpeed(speed: number, name: string): void
Sets the playback speed of the specified animation.
- Parameters
**Parameters**
| 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.|
- Example
**Example**
```ts
lottie.setSpeed(5, this.animateName)
```
......@@ -217,13 +225,15 @@ setDirection(direction: AnimationDirection, name: string): void
Sets the direction in which the specified animation plays.
- Parameters
**Parameters**
| 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 |
| 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.|
- Example
**Example**
```ts
lottie.setDirection(-1, this.animateName)
```
......@@ -263,12 +273,14 @@ play(name?: string): void
Plays an animation.
- Parameters
**Parameters**
| Name | Type | Mandatory | Description |
| ---- | ------ | ---- | --------------- |
| name | string | No | Name of the target animation. By default, the value is null.|
- Example
**Example**
```ts
this.animateItem.play()
```
......@@ -280,12 +292,14 @@ destroy(name?: string): void
Destroys an animation.
- Parameters
**Parameters**
| Name | Type | Mandatory | Description |
| ---- | ------ | ---- | --------------- |
| name | string | No | Name of the target animation. By default, the value is null.|
- Example
**Example**
```ts
this.animateItem.destroy()
```
......@@ -297,12 +311,14 @@ pause(name?: string): void
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 | string | No | Name of the target animation. By default, the value is null.|
- Example
**Example**
```ts
this.animateItem.pause()
```
......@@ -314,12 +330,14 @@ togglePause(name?: string): void
Pauses or plays an animation. This method is equivalent to the switching between **play** and **pause**.
- Parameters
**Parameters**
| Name | Type | Mandatory | Description |
| ---- | ------ | ---- | --------------- |
| name | string | No | Name of the target animation. By default, the value is null.|
- Example
**Example**
```ts
this.animateItem.togglePause()
```
......@@ -331,12 +349,14 @@ stop(name?: string): void
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 | string | No | Name of the target animation. By default, the value is null.|
- Example
**Example**
```ts
this.animateItem.stop()
```
......@@ -348,12 +368,14 @@ setSpeed(speed: number): void
Sets the playback speed of an animation.
- Parameters
**Parameters**
| 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
this.animateItem.setSpeed(5);
```
......@@ -365,12 +387,14 @@ setDirection(direction: AnimationDirection): void
Sets the playback direction of an animation.
- Parameters
**Parameters**
| 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.|
- Example
**Example**
```ts
this.animateItem.setDirection(-1)
```
......@@ -382,14 +406,16 @@ goToAndStop(value: number, isFrame?: boolean): void
Sets the animation to stop at the specified frame or time.
- Parameters
**Parameters**
| Name | Type | Mandatory | Description |
| ------- | ------- | ---- | ---------------------------------------- |
| value | number | Yes | Frame ID (greater than or equal to 0) or time progress (ms) at which the animation will stop. |
| isFrame | boolean | No | Whether to set the animation to stop at the specified frame. The value **true** means to set the animation to stop at the specified frame, and **false** means to set the animation to stop at the specified time progress. The default value is **false**.|
| name | string | No | Name of the target animation. By default, the value is null. |
- Example
**Example**
```ts
// Set the animation to stop at the specified frame.
this.animateItem.goToAndStop(25, true)
......@@ -404,14 +430,16 @@ goToAndPlay(value: number, isFrame: boolean, name?: string): void
Sets the animation to start from the specified frame or time progress.
- Parameters
**Parameters**
| 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. |
| 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**.|
| name | string | No | Name of the target animation. By default, the value is null. |
- Example
**Example**
```ts
// Set the animation to stop at the specified frame.
this.animateItem.goToAndPlay(25, true)
......@@ -426,13 +454,15 @@ playSegments(segments: AnimationSegment | AnimationSegment[], forceFlag: boolean
Sets the animation to play only the specified segment.
- Parameters
**Parameters**
| 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.|
| 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. |
- Example
**Example**
```ts
// Set the animation to play the specified segment.
this.animateItem.playSegments([10, 20], false)
......@@ -447,12 +477,14 @@ resetSegments(forceFlag: boolean): void
Resets the settings configured by the **playSegments** method to play all the frames.
- Parameters
**Parameters**
| Name | Type | Mandatory | Description |
| --------- | ------- | ---- | ------------------------------ |
| 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.|
- Example
**Example**
```ts
this.animateItem.resetSegments(true)
```
......@@ -464,7 +496,8 @@ resize(): void
Resizes the animation layout.
- Example
**Example**
```ts
this.animateItem.resize()
```
......@@ -476,12 +509,14 @@ setSubframe(useSubFrame: boolean): void
Sets the precision of the **currentFrame** attribute to display floating-point numbers.
- Parameters
**Parameters**
| 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.|
- Example
**Example**
```ts
this.animateItem.setSubframe(false)
```
......@@ -493,12 +528,14 @@ 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.
- Parameters
**Parameters**
| 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.<br>Default value: **false**|
**Example**
- Example
```ts
this.animateItem.getDuration(true)
```
......@@ -510,13 +547,15 @@ 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.
- Parameters
**Parameters**
| 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'|
| callback | AnimationEventCallback&lt;T&gt; | Yes | Custom callback. |
- Example
**Example**
```ts
private callbackItem: any = function() {
console.log("grunt loopComplete")
......@@ -534,13 +573,15 @@ removeEventListener&lt;T = any&gt;(name: AnimationEventName, callback?: Animatio
Removes an event listener.
- Parameters
**Parameters**
| 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'|
| callback | AnimationEventCallback&lt;T&gt; | No | Custom callback. By default, the value is null, meaning that all callbacks of the event will be removed. |
- Example
**Example**
```ts
this.animateItem.removeEventListener('loopComplete', this.animateName)
```
......@@ -552,13 +593,15 @@ triggerEvent&lt;T = any&gt;(name: AnimationEventName, args: T): void
Directly triggers all configured callbacks of a specified event.
- Parameters
**Parameters**
| Name | Type | Mandatory | Description |
| ---- | ------------------ | ---- | --------- |
| name | AnimationEventName | Yes | Animation event type. |
| args | any | Yes | Custom callback parameters.|
- Example
**Example**
```ts
private triggerCallBack: any = function(item) {
console.log("trigger loopComplete, name:" + item.name)
......
# Path2D
**Path2D** allows you to describe a path through an existing path. This path can be drawn through the **stroke** API of **Canvas**.
> ![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.
> **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.
**Path2D** allows you to describe a path through an existing path. This path can be drawn through the **stroke** API of **Canvas**.
## addPath
addPath(path: Object): void
addPath(path: path2D, transform?:Matrix2D): void
Adds a path to this path.
- Parameters
| Name | Type | Mandatory | Default Value | Description |
**Parameters**
| Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- |
| path | Object | Yes | null | Path to be added to this path. |
| path | path2D | Yes| - | Path to be added to this path.|
| transform | Matrix2D | No| null | Transformation matrix of the new path.|
- Example
```
**Example**
```ts
// xxx.ets
@Entry
@Component
struct AddPath {
......@@ -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.
- Example
**Example**
```
```ts
// xxx.ets
@Entry
@Component
struct ClosePath {
......@@ -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.
- Parameters
| Name | Type | Mandatory | Default Value | Description |
**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. |
| x | number | Yes| 0 | X-coordinate of the target point.|
| y | number | Yes| 0 | Y-coordinate of the target point.|
- Example
**Example**
```
```ts
// xxx.ets
@Entry
@Component
struct MoveTo {
......@@ -141,15 +148,17 @@ lineTo(x: number, y: number): void
Draws a straight line from the current point to the target point.
- Parameters
| Name | Type | Mandatory | Default Value | Description |
**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. |
| x | number | Yes| 0 | X-coordinate of the target point.|
| y | number | Yes| 0 | Y-coordinate of the target point.|
- Example
**Example**
```
```ts
// xxx.ets
@Entry
@Component
struct LineTo {
......@@ -187,19 +196,21 @@ bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number,
Draws a cubic bezier curve on the canvas.
- Parameters
| Name | Type | Mandatory | Default Value | Description |
**Parameters**
| 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. |
| cp2x | number | Yes | 0 | X-coordinate of the second parameter of the bezier curve. |
| cp2y | number | Yes | 0 | Y-coordinate of the second parameter of 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. |
| 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.|
| cp2x | number | Yes| 0 | X-coordinate of the second parameter of the bezier curve.|
| cp2y | number | Yes| 0 | Y-coordinate of the second parameter of 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
@Component
struct BezierCurveTo {
......@@ -215,7 +226,8 @@ Draws a cubic bezier curve on the canvas.
.backgroundColor('#ffff00')
.onReady(() =>{
this.path2Db.moveTo(10, 10)
this.path2Db.bezierCurveTo(20, 100, 200, 100, 200, 20);this.context.stroke(this.path2Db)
this.path2Db.bezierCurveTo(20, 100, 200, 100, 200, 20)
this.context.stroke(this.path2Db)
})
}
.width('100%')
......@@ -233,17 +245,19 @@ quadraticCurveTo(cpx: number, cpy: number, x: number ,y: number): void
Draws a quadratic curve on the canvas.
- Parameters
| Name | Type | Mandatory | Default Value | Description |
**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. |
| 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
**Example**
```
```ts
// xxx.ets
@Entry
@Component
struct QuadraticCurveTo {
......@@ -274,23 +288,25 @@ Draws a quadratic curve on the canvas.
## 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.
- Parameters
| Name | Type | Mandatory | Default Value | Description |
**Parameters**
| 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. |
| radius | number | Yes | 0 | Radius of the arc. |
| startAngle | number | Yes | 0 | Start radian of the arc. |
| endAngle | number | Yes | 0 | End radian of the arc. |
| anticlockwise | boolean | No | false | Whether to draw the arc counterclockwise. |
| 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.|
| radius | number | Yes| 0 | Radius of the arc.|
| startAngle | number | Yes| 0 | Start radian of the arc.|
| 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
@Component
struct Arc {
......@@ -305,7 +321,8 @@ Draws an arc on the canvas.
.height('100%')
.backgroundColor('#ffff00')
.onReady(() =>{
this.path2Db.arc(100, 75, 50, 0, 6.28);this.context.stroke(this.path2Db)
this.path2Db.arc(100, 75, 50, 0, 6.28)
this.context.stroke(this.path2Db)
})
}
.width('100%')
......@@ -323,18 +340,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.
- Parameters
| Name | Type | Mandatory | Default Value | Description |
**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. |
| 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
**Example**
```
```ts
// xxx.ets
@Entry
@Component
struct ArcTo {
......@@ -364,25 +383,27 @@ Draws an arc based on the radius and points on the arc.
## 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
| 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
**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. 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
@Component
struct CanvasExample {
......@@ -397,7 +418,7 @@ Draws an ellipse in the specified rectangular region.
.height('100%')
.backgroundColor('#ffff00')
.onReady(() =>{
this.path2Db.ellipse(200, 200, 50, 100, Math.PI * 0.25, Math.PI * 0.5, Math.PI)
this.path2Db.ellipse(200, 200, 50, 100, 0, Math.PI * 1, Math.PI*2)
this.context.stroke(this.path2Db)
})
}
......@@ -412,21 +433,23 @@ Draws an ellipse in the specified rectangular region.
## 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
| Name | Type | Mandatory | Default Value | Description |
**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. |
| 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
**Example**
```
```ts
// xxx.ets
@Entry
@Component
struct CanvasExample {
......@@ -441,7 +464,8 @@ Creates a rectangle.
.height('100%')
.backgroundColor('#ffff00')
.onReady(() =>{
this.path2Db.rect(20, 20, 100, 100);this.context.stroke(this.path2Db)
this.path2Db.rect(20, 20, 100, 100);
this.context.stroke(this.path2Db)
})
}
.width('100%')
......
# AlphabetIndexer
The **\<Indexer>** component provides an alphabetic index bar.
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> **NOTE**
>
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
The **&lt;AlphabetIndexer&gt;** component provides an alphabetic index bar.
## Required Permissions
None
## Child Components
None
Not supported
## APIs
AlphabetIndexer(value: {arrayValue : Array&lt;string&gt;, selected : number})
AlphabetIndexer(value: {arrayValue: Array&lt;string&gt;, selected: number})
- 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. |
**Parameters**
| 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
| Name | Type | Description |
| -------- | -------- | -------- |
| selectedColor | Color | Font color of the selected text. |
| popupColor | Color | Font color of the pop-up text. |
| selectedBackgroundColor | Color | Background color of the selected text. |
| popupBackground | Color | Background color of the pop-up text. |
| ----------------------- | --------------- | ----------------------------------------------------------- |
| color | [ResourceColor](ts-types.md#resourcecolor8) | Font color. |
| selectedColor | [ResourceColor](ts-types.md#resourcecolor8) | Font color of the selected text. |
| popupColor | [ResourceColor](ts-types.md#resourcecolor8) | Font color of the pop-up text. |
| selectedBackgroundColor | [ResourceColor](ts-types.md#resourcecolor8) | Background color of the selected item. |
| popupBackground | [ResourceColor](ts-types.md#resourcecolor8) | Background color of the pop-up text. |
| usingPopup | boolean | Whether to use pop-up text. |
| selectedFont | {<br/>size?: number,<br/>weight?: FontWeight,<br/>family?: string,<br/>style?: FontStyle<br/>} | Font style of the selected text. |
| popupFont | {<br/>size?: number,<br/>weight?: FontWeight,<br/>family?: string,<br/>style?: FontStyle<br/>} | Font style 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. |
| itemSize | Length | Size of an item in the alphabetic index bar. The item is a square, and the side length needs to be set. |
| 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. |
| selectedFont | [Font](ts-types.md#font) | Font style of the selected text. |
| 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. |
| 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. |
| 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.|
| popupPosition | [Position](ts-types.md#position8) | Position of the pop-up window relative to the center of the indexer bar's top border.|
- 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. |
## 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
| Name | Description |
| Name| Description|
| -------- | -------- |
| onSelected(index:&nbsp;number)&nbsp;=&gt;&nbsp;void<sup>(deprecated) </sup> | Invoked when an item in the alphabetic indexer bar is selected. |
| onSelect(index:&nbsp;number)&nbsp;=&gt;&nbsp;void<sup>8+</sup> | Invoked when an item in the alphabetic indexer bar is selected. |
| 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. |
| 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(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 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. |
## Example
```
```ts
// xxx.ets
@Entry
@Component
struct AlphabetIndexerSample {
......
# Badge
The **\<Badge>** component is a container that can be attached to another component for tagging.
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> **NOTE**
>
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
The **&lt;Badge&gt;** component presents event information on a component.
## Required Permissions
None
## Child Components
This component supports only one child component.
......@@ -20,88 +14,139 @@ This component supports only one child component.
## APIs
Badge(value: {count: number, position?: BadgePosition, maxCount?: number, style?: BadgeStyle})
**Method 1**: Badge(value: {count: number, position?: BadgePosition, maxCount?: number, style: BadgeStyle})
- Parameters
| 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 **&lt;Badge&gt;** component, including the text color, text size, badge color, and badge size. |
Create a badge.
Badge(value: {value: string, position?: BadgePosition, style?: BadgeStyle})
**Parameters**
| Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- |
| count | number | Yes| - | Number of notifications.|
| position | [BadgePosition](#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](#badgestyle) | Yes| - | Style of the badge, including the font color, font size, badge color, and badge size. |
Creates a **&lt;Badge&gt;** component based on the string.
**Method 2**: Badge(value: {value: string, position?: BadgePosition, style: BadgeStyle})
- Parameters
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| value | string | Yes | - | String of the content to prompt. |
| position | BadgePosition | No | BadgePosition.RightTop | Display position of the badge. |
| style | BadgeStyle | No | - | Style of the **&lt;Badge&gt;** component, including the text color, text size, badge color, and badge size. |
Creates a badge based on the given string.
- BadgeStyle object
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| color | Color | No | Color.White | Text color. |
| fontSize | number \| string | No | 10 | Text size. |
| badgeSize | number \| string | Yes | - | Size of the badge. |
| badgeColor | Color | No | Color.Red | Color of the badge. |
**Parameters**
- BadgePosition enums
| 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. |
| Left | The badge is vertically centered on the left of the parent component. |
| Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- |
| value | string | Yes| - | Prompt content.|
| position | [BadgePosition](#badgeposition) | No| BadgePosition.RightTop | Position to display the badge relative to the parent component.|
| style | [BadgeStyle](#badgestyle) | Yes| - | Style of the badge, including the font color, font size, badge color, and badge size. |
## BadgePosition
## Example
| Name| Description|
| -------- | -------- |
| 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.|
## BadgeStyle
| Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- |
| color | [ResourceColor](ts-types.md#resourcecolor) | No| Color.White | Font color. |
| fontSize | number&nbsp;\|&nbsp;string | No| 10 | Font size. |
| badgeSize | number&nbsp;\|&nbsp;string | Yes| - | Badge size.|
| badgeColor | [ResourceColor](ts-types.md#resourcecolor) | No| Color.Red | Badge color.|
```
## Example
```ts
// xxx.ets
@Entry
@Component
struct BadgeExample {
@State counts: number = 1
@State message: string = 'new'
@State counts: number = 1;
@State message: string = 'new';
build() {
Flex({ justifyContent: FlexAlign.SpaceAround }) {
Column() {
Text('numberBadge').width('80%')
Row({ space: 10 }) {
// Number badge. The default value of maxCount is 99. If the number of notifications exceeds 99, 99+ is displayed.
Badge({
count: this.counts,
maxCount: 99,
position: BadgePosition.RightTop,
style: { color: 0xFFFFFF, fontSize: 16, badgeSize: 20, badgeColor: Color.Red }
}) {
Button('message')
.onClick(() => {
this.counts++
this.counts++;
})
.width(100).height(50).backgroundColor(0x317aff)
}.width(100).height(50)
// Number badge
Badge({
count: this.counts,
maxCount: 99,
position: BadgePosition.Left,
style: { color: 0xFFFFFF, fontSize: 16, badgeSize: 20, badgeColor: Color.Red }
}) {
Button('message')
.onClick(() => {
this.counts++;
})
.width(100).height(50).backgroundColor(0x317aff)
}.width(100).height(50)
// Number badge
Badge({
count: this.counts,
maxCount: 99,
position: BadgePosition.Right,
style: { color: 0xFFFFFF, fontSize: 16, badgeSize: 20, badgeColor: Color.Red }
}) {
Button('message')
.onClick(() => {
this.counts++;
})
.width(100).height(50).backgroundColor(0x317aff)
}.width(100).height(50)
}.margin(10)
Text('stringBadge').width('80%')
Row({ space: 30 }) {
Badge({
value: this.message,
style: { color: 0xFFFFFF, fontSize: 9, badgeSize: 20, badgeColor: Color.Blue }
}) {
Text('message')
.width(80).height(50).fontSize(16).lineHeight(37)
.borderRadius(10).textAlign(TextAlign.Center).backgroundColor(0xF3F4ED)
.width(80)
.height(50)
.fontSize(16)
.lineHeight(37)
.borderRadius(10)
.textAlign(TextAlign.Center)
.backgroundColor(0xF3F4ED)
}.width(80).height(50)
// When value is null, the dot-style badge is used.
Badge({
value: '',
position: 1,
position: BadgePosition.Right,
style: { badgeSize: 6, badgeColor: Color.Red }
}) {
Text('message')
.width(90).height(50).fontSize(16).lineHeight(37)
.borderRadius(10).textAlign(TextAlign.Center).backgroundColor(0xF3F4ED)
.width(90)
.height(50)
.fontSize(16)
.lineHeight(37)
.borderRadius(10)
.textAlign(TextAlign.Center)
.backgroundColor(0xF3F4ED)
}.width(90).height(50)
}.width('100%').margin({ top: 5 })
}.margin(10)
}
}
}
```
![en-us_image_0000001212218470](figures/en-us_image_0000001212218470.gif)
![badge](figures/badge.png)
# Column
The **\<Column>** component lays out child components vertically.
The **<Column\>** component lays out child components vertically.
> **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
This component can contain child components.
Supported
## APIs
......@@ -23,19 +17,17 @@ This component can contain child components.
Column(value?:{space?: string | number})
**Parameters**
| Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- |
| space | string\|numbe | No| 0 | Space between two adjacent child components in the vertical layout.|
## Attributes
| Name| Type| Default Value| Description|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| alignItems | [HorizontalAlign](ts-appendix-enums.md#horizontalalign) | HorizontalAlign.Center | Alignment mode of the child components in the horizontal direction.|
| justifyContent<sup>8+</sup> | [FlexAlign](ts-container-flex.md) | FlexAlign.Start | Alignment mode of the child components in the vertical direction.|
| space | string \| number | No| Space between two adjacent child components in the vertical layout.<br>Default value: **0**|
## Attributes
| Name| Type| Description|
| -------- | -------- | -------- |
| alignItems | [HorizontalAlign](ts-appendix-enums.md#horizontalalign) | Alignment mode of the child components in the horizontal direction.<br>Default value: **HorizontalAlign.Center**|
| justifyContent<sup>8+</sup> | [FlexAlign](ts-appendix-enums.md#flexalign) | Alignment mode of the child components in the vertical direction.<br>Default value: **FlexAlign.Start**|
## Example
......
......@@ -23,20 +23,20 @@ Flex(value?: { direction?: FlexDirection, wrap?: FlexWrap, justifyContent?: Fle
Creates a standard **\<Flex>** component.
- Parameters
| Name | Type | Mandatory | Default Value | Description |
| -------------- | ---------------------------------------- | ---- | ----------------- | ---------------------------------------- |
| direction | [FlexDirection](ts-appendix-enums.md#flexdirection) | No | FlexDirection.Row | Direction in which child components are arranged in the **\<Flex>** component, that is, the direction of the main axis. |
| wrap | [FlexWrap](ts-appendix-enums.md#flexwrap) | No | FlexWrap.NoWrap | Whether the **\<Flex>** component has a single line or multiple lines. |
| justifyContent | [FlexAlign](ts-appendix-enums.md#flexalign) | No | FlexAlign.Start | Alignment mode of the child components in the **\<Flex>** component along the main axis. |
| alignItems | [ItemAlign](ts-appendix-enums.md#itemalign) | No | ItemAlign.Stretch | Alignment mode of the child components in the **\<Flex>** component along the cross axis. |
| alignContent | [FlexAlign](ts-appendix-enums.md#flexalign) | No | FlexAlign.Start | Alignment mode of the child components in a multi-line **<Flex>** component along the cross axis. This parameter is valid only when **wrap** is set to **Wrap** or **WrapReverse**.|
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| -------------- | ---------------------------------------- | ---- | ----------------- | ---------------------------------------- |
| direction | [FlexDirection](ts-appendix-enums.md#flexdirection) | No | FlexDirection.Row | Direction in which child components are arranged in the **\<Flex>** component, that is, the direction of the main axis. |
| wrap | [FlexWrap](ts-appendix-enums.md#flexwrap) | No | FlexWrap.NoWrap | Whether the **\<Flex>** component has a single line or multiple lines. |
| justifyContent | [FlexAlign](ts-appendix-enums.md#flexalign) | No | FlexAlign.Start | Alignment mode of the child components in the **\<Flex>** component along the main axis. |
| alignItems | [ItemAlign](ts-appendix-enums.md#itemalign) | No | ItemAlign.Stretch | Alignment mode of the child components in the **\<Flex>** component along the cross axis. |
| alignContent | [FlexAlign](ts-appendix-enums.md#flexalign) | No | FlexAlign.Start | Alignment mode of the child components in a multi-line **<Flex>** component along the cross axis. This parameter is valid only when **wrap** is set to **Wrap** or **WrapReverse**.|
## Example
```ts
// xxx.ets
```
// Example 01
@Entry
@Component
struct FlexExample1 {
......@@ -98,8 +98,8 @@ struct FlexExample1 {
![en-us_image_0000001256978365](figures/en-us_image_0000001256978365.gif)
```ts
// xxx.ets
```
// Example 02
@Entry
@Component
struct FlexExample2 {
......@@ -144,8 +144,8 @@ struct FlexExample2 {
![en-us_image_0000001211898500](figures/en-us_image_0000001211898500.png)
```ts
// xxx.ets
```
// Example 03
@Component
struct JustifyContentFlex {
@Prop justifyContent : number
......@@ -193,8 +193,8 @@ struct FlexExample3 {
![en-us_image_0000001212218462](figures/en-us_image_0000001212218462.gif)
```ts
// xxx.ets
```
// Example 04
@Component
struct AlignItemsFlex {
@Prop alignItems : number
......@@ -242,10 +242,9 @@ struct FlexExample4 {
![en-us_image_0000001257138371](figures/en-us_image_0000001257138371.jpg)
![en-us_image_0000001212378426](figures/en-us_image_0000001212378426.gif)
```ts
// xxx.ets
```
// Example 05
@Component
struct AlignContentFlex {
@Prop alignContent: number
......
# 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.
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
The **&lt;List&gt;** 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.
## Required Permissions
None
> **NOTE**
>
> - 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.
## Child Components
This component contains the child component [\<ListItem>](ts-container-listitem.md).
This component supports the [\<ListItem>](ts-container-listitem.md) child components.
## APIs
List(value:{space?: number, initialIndex?: number})
- Parameters
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| space | number | No | 0 | Spacing between list items. |
| initialIndex | number | No | 0 | Item displayed at the beginning of the component when the current list is loaded for the first time, that is, the first item to be displayed. If the configured sequence number is greater than the sequence number of the last item, the setting does not take effect. |
List(value?:{space?: number | string, initialIndex?: number, scroller?: Scroller})
## Attributes
**Parameters**
| Name | Type | Default Value | Description |
| Name| Type| Mandatory| 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 **&lt;List&gt;** 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 disabled. |
| 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 **&lt;List&gt;** component, the status includes the item serial number displayed at the start position. |
| 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.|
- EdgeEffect enums
| Name | Description |
| -------- | -------- |
| Spring | Similar to the physical dynamic effect of a spring. After scrolling to the edge, you can continue to scroll for a distance based on the initial speed or by touching the knob of the scrollbar. After you release your hand, the knob is rebounded. |
| None | No effect after the scroll bar is moved to the edge. |
## Attributes
| 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#resourcecolor8),<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 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.|
## Events
| Name | Description |
| Name| Description|
| -------- | -------- |
| onItemDelete(index: number) =&gt; boolean | Triggered when a list item is deleted. |
| onScrollIndex(firstIndex: number, lastIndex: number) =&gt; void | Triggered when the start position and end position of the current list are changed. |
| onItemDelete(event: (index: number) => boolean) | Triggered when a list item is deleted.<br>- **index**: index of the deleted list item.|
| onScroll(event: (scrollOffset: number, scrollState: ScrollState) => void) | Triggered when the list scrolls.<br>- **scrollOffset**: scroll offset.<br>- **scrollState**: current scroll state. |
| onScrollIndex(event: (start: number, end: number) => void) | Triggered when scrolling starts.<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.|
| onReachEnd(event: () => void) | Triggered when the list reaches the end position.|
| 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. |
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> **NOTE**
>
> To enable the editable mode for a list, the following conditions must be met:
>
> - **editMode** is set to **true**.
>
> - The list is bound to the **onItemDelete** event and the event returns **true** during event 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**.
>
......@@ -73,8 +82,8 @@ List(value:{space?: number, initialIndex?: number})
## Example
```
```ts
// xxx.ets
@Entry
@Component
struct ListExample {
......@@ -94,8 +103,8 @@ struct ListExample {
}, item => item)
}
.listDirection(Axis.Vertical) // Arrangement direction
.divider({ strokeWidth: 2, color: 0xFFFFFF, startMargin: 20, endMargin: 20 }) // Divider line
.edgeEffect(EdgeEffect.None) // No effect when sliding to the edge
.divider({ strokeWidth: 2, color: 0xFFFFFF, startMargin: 20, endMargin: 20 }) // Divider
.edgeEffect(EdgeEffect.None) // No effect when the list scrolls to the edge.
.chainAnimation(false) // Chained animations are disabled.
.onScrollIndex((firstIndex: number, lastIndex: number) => {
console.info('first' + firstIndex)
......
# Row
The **<Row\>** component lays out child components horizontally.
> **NOTE**
......@@ -8,11 +7,6 @@ The **<Row\>** component lays out child components horizontally.
> 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
Supported
......@@ -20,20 +14,21 @@ Supported
## APIs
Row(value?:{space?: string&nbsp;|&nbsp;number})
Row(value?:{space?: string \| number })
**Parameters**
| Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- |
| space | string&nbsp;\|&nbsp;number | No| 0 | Space between two adjacent child components in the horizontal layout.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| space | string \| number | No| Space between two adjacent child components in the horizontal layout.<br>Default value: **0**, in vp |
## Attributes
| Name| Type| Default Value| Description|
| -------- | -------- | -------- | -------- |
| alignItems | [VerticalAlign](ts-appendix-enums.md#verticalalign) | VerticalAlign.Center | Alignment mode of the child components in the vertical direction.|
| justifyContent<sup>8+</sup> | [FlexAlign](ts-appendix-enums.md#flexalign) | FlexAlign.Start | Alignment mode of the child components in the horizontal direction.|
| Name| Type| Description|
| -------- | -------- | -------- |
| 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) | Alignment mode of the child components in the horizontal direction.<br>Default value: **FlexAlign.Start** |
## Example
......@@ -79,4 +74,4 @@ struct RowExample {
}
```
![en-us_image_0000001174422908](figures/row.png)
![en_us_image_0000001174422908](figures/row.png)
# Scroll
The **\<Scroll>** component scrolls the content when the layout size of a component exceeds the viewport of its parent component.
The **\<Scroll>** component scrolls the content when the layout size of a component exceeds the size of its parent component.
> **NOTE**
> - 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.
## Required Permissions
None
> - The prerequisite for the component to rebound is that the component is scrolled.
## Child Components
......@@ -23,42 +16,41 @@ This component supports only one child component.
Scroll(scroller?: Scroller)
## Attributes
| Name | Type | Default Value | Description |
| -------- | -------- | -------- | -------- |
| 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 | string&nbsp;\|&nbsp;number | - | Width of the scrollbar. |
| edgeEffect | [EdgeEffect](ts-appendix-enums.md#edgeeffect) | EdgeEffect.Spring | Scroll effect. For details, see **EdgeEffect**. |
In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported.
| Name | Type | Description |
| -------------- | ---------------------------------------- | --------- |
| scrollable | ScrollDirection | Scroll direction.<br>Default value: **ScrollDirection.Vertical**|
| scrollBar | [BarState](ts-appendix-enums.md#barstate) | Scrollbar status.<br>Default value: **BarState.Off**|
| scrollBarColor | string \| number \| Color | Color of the scrollbar.|
| 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**|
## ScrollDirection
| Name | Description |
| -------- | -------- |
| ---------- | ------------------------ |
| Horizontal | Only horizontal scrolling is supported. |
| Vertical | Only vertical scrolling is supported. |
| None | Scrolling is disabled. |
| Free | Both horizontal scrolling and vertical scrolling are supported. |
| Free<sup>(deprecated) </sup> | Vertical or horizontal scrolling is supported.<br> This API is deprecated since API version 9.|
## Events
| Name | Description |
| -------- | -------- |
| onScroll(event: (xOffset: number, yOffset: number) => void) | Invoked when scrolling starts. It returns the horizontal and vertical offsets. |
| ----------------------------------------------------------- | ------------------------------------------------------------ |
| 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. |
| onScrollEnd(event: () => void) | Invoked when scrolling stops. |
## Scroller
Controller of the scrollable container component. You can bind this component to the container component and use it to control the scrolling of the container component. Currently, this component can be bound to the **\<List>** and **\<Scroll>** 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
```
scroller: Scroller = new Scroller()
```
......@@ -73,11 +65,11 @@ Scrolls to the specified position.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| xOffset | number&nbsp;\|&nbsp;string | Yes | - | Horizontal scrolling offset. |
| yOffset | number&nbsp;\|&nbsp;string | Yes | - | Vertical scrolling offset. |
| animation | {<br/>duration:&nbsp;number,<br/>curve:&nbsp;[Curve](ts-animatorproperty.md)&nbsp;<br/>} | No | | Animation configuration, which includes the following:<br/>- **duration**: scrolling duration.<br/>- **curve**: scrolling curve. |
| Name | Type | Mandatory| Description |
| --------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| xOffset | number \| string | Yes | Horizontal scrolling offset. |
| yOffset | number \| string | Yes | Vertical scrolling offset. |
| animation | {<br>duration: number,<br>curve: [Curve](ts-appendix-enums.md#curve)<br>} | No | Animation configuration, which includes the following:<br>- **duration**: scrolling duration.<br>- **curve**: scrolling curve.|
### scrollEdge
......@@ -87,6 +79,7 @@ scrollEdge(value: [Edge](ts-appendix-enums.md#edge)): void
Scrolls to the edge of the container.
### scrollPage
scrollPage(value: { next: boolean, direction?: Axis }): void
......@@ -95,10 +88,10 @@ Scrolls to the next or previous page.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| next | boolean | Yes | - | Whether to turn to the next page. The value **true** means to scroll to the next page, and the value **false** means to scroll to the previous page. |
| direction | [Axis](ts-appendix-enums.md#axis) | No | - | Scrolling direction: horizontal or vertical. |
| 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. |
### currentOffset
......@@ -113,24 +106,22 @@ Obtains the scrolling offset.
scrollToIndex(value: number): void
Scrolls to the specified index.
Scrolls to the item with the specified index.
> **NOTE**
>
> Only the **\<List>** component is supported.
**Parameters**
- Parameters
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| value | number | Yes | - | Index of the item to be scrolled to in the list. |
| Name| Type| Mandatory| Description |
| ------ | -------- | ---- | ---------------------------------- |
| value | number | Yes | Index of the item to be scrolled to in the list.|
## Example
```ts
// xxx.ets
@Entry
......@@ -170,17 +161,17 @@ struct ScrollExample {
})
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 })
})
.margin({ top: 10, left: 20 })
Button('back top')
.onClick(() => {// Click to go back to the top.
.onClick(() => { // Click to go back to the top.
this.scroller.scrollEdge(Edge.Top)
})
.margin({ top: 60, left: 20 })
Button('next page')
.onClick(() => {// Click to scroll down to the bottom.
.onClick(() => { // Click to go to the next page.
this.scroller.scrollPage({ next: true })
})
.margin({ top: 110, left: 20 })
......
# SideBarContainer
> ![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 **\<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
> **NOTE**
>
> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
## Child Components
......@@ -21,50 +16,51 @@ Supported
SideBarContainer( type?: SideBarContainerType )
- Parameters
| Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- |
| type | SideBarContainerType | No| SideBarContainerType.Embed | Display type of the sidebar.|
**Parameters**
- SideBarContainerType enums
| Name| Description|
| -------- | -------- |
| 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.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | SideBarContainerType | No| Display type of the sidebar.<br>Default value: **SideBarContainerType.Embed**|
## Attributes
## SideBarContainerType enums
| Name| Type| Default Value| Description|
| -------- | -------- | -------- | -------- |
| showSideBar | boolean | true | Whether to display the sidebar.|
| controlButton | ButtonStyle | - | Attributes of the sidebar control button.|
| showControlButton | boolean | true | Whether to display the sidebar control button.|
| sideBarWidth | number | 200 | Width of the sidebar.|
| minSideBarWidth | number | 200 | Minimum width of the sidebar.|
| maxSideBarWidth | number | 280 | Maximum width of the sidebar.|
| Name| Description|
| -------- | -------- |
| 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.|
- ButtonStyle
| Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- |
| 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.|
## Attributes
| 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 | Width of the sidebar.<br>Default value: **200**, in vp|
| minSideBarWidth | number | Minimum width of the sidebar.<br>Default value: **200**, in vp|
| maxSideBarWidth | number | Maximum width of the sidebar.<br>Default value: **280**, in vp|
## ButtonStyle
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| left | number | No| Spacing between the sidebar control button and the left of the container.<br>Default value: **16**, in vp|
| top | number | No| Spacing between the sidebar control button and the top of the container.<br>Default value: **48**, in vp|
| width | number | No| Width of the sidebar control button.<br>Default value: **32**, in vp|
| height | number | No| Height of the sidebar control button.<br>Default value: **32**, in vp|
| 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.|
## Events
| Name| Description|
| -------- | -------- |
| onChange(callback: (value: boolen) =&gt; void) | Triggered when the status of the sidebar switches between shown and hidden. <p> The value **true** means that the sidebar is shown, and **false** means that the sidebar is hidden.|
| onChange(callback: (value: boolean) =&gt; void) | Triggered when the status of the sidebar switches between shown and hidden. <p>The value **true** means that the sidebar is shown, and **false** means the opposite.|
## Example
```
```ts
// xxx.ets
@Entry
@Component
struct SideBarContainerExample {
......
# Stack
The **\<Stack>** component provides a stack container where child components are successively stacked and the latter one overwrites the previous one.
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> **NOTE**
>
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
The **&lt;Stack&gt;** component provides a stack container where child components are successively stacked and the latter one overwrites the previous one.
## Required Permissions
None
## Child Components
Supported
Supported
## APIs
Stack(value:{alignContent?: Alignment})
Stack(value?: { alignContent?: Alignment })
- Parameters
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| alignContent | [Alignment](ts-appendix-enums.md#alignment-enums) | No | Center | Alignment of child components in the container. |
**Parameters**
| 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
@Component
struct StackExample {
......
# Swiper
The **\<Swiper>** component provides a container that allows users to switch among child components using swipe gestures.
> **NOTE**
......@@ -8,11 +7,6 @@ The **\<Swiper>** component provides a container that allows users to switch amo
> 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
This component can contain child components.
......@@ -20,51 +14,51 @@ This component can contain child components.
## APIs
Swiper(value:{controller?: SwiperController})
Swiper(value?:{controller?: SwiperController})
**Parameters**
| 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
[Menu control](ts-universal-attributes-menu.md) is not supported.
| Name | Type | Default Value | Description |
| --------------------------- | ---------------------------------------- | ---------------------------------------- | ---------------------------------------- |
| index | number | 0 | Index of the child component currently displayed in the container. |
| autoPlay | boolean | false | Whether to enable automatic playback for child component switching. If this attribute is **true**, the navigation dots indicator does not take effect. |
| interval | number | 3000 | Interval for automatic playback, in ms. |
| indicator | boolean | true | Whether to enable the navigation dots indicator. |
| loop | boolean | true | 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. |
| duration | number | 400 | Duration of the animation for switching child components, in ms. |
| vertical | boolean | false | Whether vertical swiping is used. |
| itemSpace | number \| string | 0 | Space between child components. |
| displayMode | SwiperDisplayMode | SwiperDisplayMode.Stretch | Mode in which elements are displayed along the main axis. This attribute takes effect only when **displayCount** is not set. |
| cachedCount<sup>8+</sup> | number | 1 | Number of child components to be cached. |
| disableSwipe<sup>8+</sup> | boolean | false | Whether to disable the swipe feature. |
| displayCount<sup>8+</sup> | number \| string | 1 | Number of elements to display. |
| effectMode<sup>8+</sup> | EdgeEffect | EdgeEffect.Spring | Swipe effect. For details, see **EdgeEffect**. |
| curve<sup>8+</sup> | [Curve](ts-appendix-enums.md#curve) \| string | Curve.Ease | 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. |
| 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#resourcecolor8),<br/>selectedColor?: [ResourceColor](ts-types.md#resourcecolor8)<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.|
| Name | Type | Description |
| --------------------------- | ---------------------------------------- | ---------------------------------------- |
| index | number | Index of the child component currently displayed in the container.<br>Default value: **0** |
| autoPlay | boolean | Whether to enable automatic playback for child component switching. If this attribute is **true**, the navigation dots indicator does not take effect.<br>Default value: **false** |
| interval | number | Interval for automatic playback, in ms.<br>Default value: **3000** |
| indicator | boolean | Whether to enable the navigation dots indicator.<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** |
| vertical | boolean | Whether vertical swiping is used.<br>Default value: **false** |
| itemSpace | number \| string | Space between child components.<br>Default value: **0** |
| displayMode | SwiperDisplayMode | Mode in which child components are displayed.<br>Default value: **SwiperDisplayMode.Stretch** |
| 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** |
| displayCount<sup>8+</sup> | number\|string | Number of child components to display per page. The value **auto** is equivalent to **SwiperDisplayMode.AutoLinear**.<br>Default value: **1** |
| effectMode<sup>8+</sup> | [EdgeEffect](ts-appendix-enums.md#edgeeffect) | Swipe effect.<br>Default value: **EdgeEffect.Spring** |
| 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?: [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#resourcecolor8),<br>selectedColor?: [ResourceColor](ts-types.md#resourcecolor8)<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.|
## SwiperDisplayMode
| Name| Description|
| ----------- | ------------------------------------------ |
| 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
| 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. |
| 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. |
| None | No effect. When at one of the edges, the component cannot move beyond the bounds. |
| 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 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 sliding to one edge, the component cannot move beyond the bounds. |
## SwiperController
......@@ -86,7 +80,7 @@ Turns to the previous page.
finishAnimation(callback?: () => void): void
Stops this animation.
Stops an animation.
**Parameters**
......@@ -98,15 +92,15 @@ Stops this animation.
### onChange
onChange( index: number) =&gt; 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**
| Name | Type | Mandatory.| Description|
| --------- | ---------- | ------ | -------- |
| index | number | Yes | Index of the currently displayed element.|
| index | number | Yes | Index of the currently displayed child component. |
## Example
......
# TabContent
The **\<TabContent>** component is used only in the **\<Tabs>** component. It corresponds to the content view of a switched tab page.
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> **NOTE**
>
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
The **&lt;TabContent&gt;** component is used only in the **&lt;Tabs&gt;** component. It corresponds to the content view of a switched tab page.
## Required Permissions
None
## Child Components
This component supports only one child component.
......@@ -27,20 +21,19 @@ TabContent()
Touch target configuration is not supported.
| Name | Type | Default Value | Description |
| -------- | -------- | -------- | -------- |
| tabBar | string \| {<br/>icon?: string,<br/>text?: string<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/>> ![icon-note.gif](public_sys-resources/icon-note.gif) **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. |
| Name| Type| Description|
| -------- | -------- | -------- |
| tabBar | string \| [Resource](ts-types.md#resource) \| {<br>icon?: string \| [Resource](ts-types.md#resource),<br>text?: string \| [Resource](ts-types.md#resource)<br>}<br>\| [CustomBuilder](ts-types.md#custombuilder8)<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. |
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> - The **&lt;TabContent&gt;** component does not support setting of the common width attribute. By default, its width is the same as that of the parent **&lt;Tabs&gt;** component.
>
> - The **&lt;TabContent&gt;** component does not support setting of the common height attribute. Its height is determined by the height of the parent **&lt;Tabs&gt;** component and the **&lt;TabBar&gt;** component.
> **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 height attribute. Its height is determined by the height of the parent **\<Tabs>** component and the **\<TabBar>** component.
## Example
```
```ts
// xxx.ets
@Entry
@Component
struct TabContentExample {
......
# Tabs
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.
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> **NOTE**
>
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
The **&lt;Tabs&gt;** component is a container component that allows users to switch between content views through tabs. Each tab page corresponds to a content view.
## Required Permissions
None
## Child Components
The **&lt;Tabs&gt;** component can contain [TabContent](ts-container-tabcontent.md) child components.
This component can contain multiple [\<TabContent>](ts-container-tabcontent.md) components.
## APIs
Tabs(value: {barPosition?: BarPosition, index?: number, controller?: [TabsController](#tabscontroller)})
Tabs(value?: {barPosition?: BarPosition, index?: number, controller?: [TabsController](#tabscontroller)})
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| barPosition | BarPosition | No| Tab bar position for creating the **\<Tabs>** container component.<br>Default value: **BarPosition.Start**|
| index | number | No| Initial tab index.<br>Default value: **0**|
| controller | [TabsController](#tabscontroller) | No| Tab controller.|
- Parameters
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| barPosition | BarPosition | No | BarPosition.Start | Tab bar position for creating the **&lt;Tabs&gt;** container component. |
| index | number | No | 0 | Initial tab index. |
| controller | [TabsController](#tabscontroller) | No | - | Tab controller. |
## BarPosition
- BarPosition enums
| Name | Description |
| -------- | -------- |
| Start | If the **vertical** attribute is set to **true**, the tab is on the left of the container. If the **vertical** attribute is set to **false**, the tab is on the top of the container. |
| End | If the **vertical** attribute is set to **true**, the tab is on the right of the container. If the **vertical** attribute is set to **false**, the tab is at the bottom of the container. |
| Name| Description|
| -------- | -------- |
| Start | If the **vertical** attribute is set to **true**, the tab is on the left of the container. If the **vertical** attribute is set to **false**, the tab is on the top of the container.|
| End | If the **vertical** attribute is set to **true**, the tab is on the right of the container. If the **vertical** attribute is set to **false**, the tab is at the bottom of the container.|
## Attributes
Touch target configuration is not supported.
| Name | Type | Default Value | Description |
| -------- | -------- | -------- | -------- |
| vertical | boolean | false | Whether a tab is a vertical tab. |
| scrollable | boolean | true | Whether page switching can be performed by swiping left or right. |
| barMode | BarMode | - | Tab bar layout mode. |
| barWidth | number | - | Width of the tab bar. If this parameter is not set, the default value in the system theme is used. |
| barHeight | number | - | Height of the tab bar. If this parameter is not set, the default value in the system theme is used. |
| animationDuration | number | 200 | Animation duration of the tab content. |
| Name| Type| Description|
| -------- | -------- | -------- |
| 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**|
| barMode | BarMode | Tab bar layout mode. For details, see **BarMode**.<br>Default value: **BarMode.Fixed**|
| barWidth | [Length](ts-types.md#length) | Width of the tab bar. |
| barHeight | [Length](ts-types.md#length) | Height of the tab bar. |
| animationDuration | number | Animation duration of the tab content.<br>Default value: **200**|
- BarMode enums
| Name | Description |
| -------- | -------- |
| Scrollable | The actual layout width of the tab bar is used. If the actual width exceeds the total length, the tab bar is scrollable. |
| Fixed | The widths of all tab bars are evenly allocated. |
## BarMode
| Name| Description|
| -------- | -------- |
| Scrollable | The width of each tab is defined by its label length. The tabs are scrollable when the total width exceeds the tab bar width.|
| Fixed | The width of each tab is fixed, determined by evenly allocating the tab bar width among the tabs.|
## Events
| 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.<br>- **index**: index of the tab. |
## TabsController
Defines a tab controller, which is used to control switching of tabs.
### Objects to Import
```
......@@ -78,16 +75,17 @@ changeIndex(value: number): void
Switches to the specified tab.
- Parameters
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| value | number | Yes | - | Index of a tab. The value starts from **0**. |
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| value | number | Yes| Index of the tab. The value starts from 0.|
## Example
## Example
```
```ts
// xxx.ets
@Entry
@Component
struct TabsExample {
......
# Circle
The **\<Circle>** component is used to draw a circle.
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> **NOTE**
>
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
The **&lt;Circle&gt;** component is used to draw a circle.
## Required Permissions
None
## Child Components
None
Not supported
## APIs
Circle(options?: {width: Length, height: Length})
- Parameters
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| options | Object | No | - | For details, see the **options** parameters. |
- options parameters
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| width | Length | Yes | - | Width. |
| height | Length | Yes | - | Height. |
Circle(options?: {width?: string | number, height?: string | number})
**Parameters**
| Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- |
| width | string \| number | No| 0 | Width of the circle.|
| height | string \| number | No| 0 | Height of the circle.|
## Attributes
| Name | Type | Default Value | Mandatory | Description |
In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported.
| Name| Type| Default Value| Mandatory| Description|
| -------- | -------- | -------- | -------- | -------- |
| width | Length | 0 | No | Width of the rectangle where the circle is located. |
| height | Length | 0 | No | Height of the rectangle where the circle is located. |
| fill | [ResourceColor](ts-types.md#resourcecolor8) | 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#resourcecolor8) | 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| Stroke opacity.|
| strokeWidth | Length | 1 | No| Stroke width.|
| antiAlias | boolean | true | No| Whether anti-aliasing is enabled.|
## Example
```
```ts
// xxx.ets
@Entry
@Component
struct CircleExample {
build() {
Flex({ justifyContent: FlexAlign.SpaceAround }) {
Column({ space: 10 }) {
// Draw a circle whose diameter is 150.
Circle({ width: 150, height: 150 })
// Draw a circle whose diameter is 150.
Circle().width(150).height(150)
}.width('100%').margin({ top: 5 })
// Draw a circle whose diameter is 150 and stroke color is red. (If the width and height values are different, the smaller value will be used as the diameter.)
Circle()
.width(150)
.height(200)
.fillOpacity(0)
.strokeWidth(3)
.stroke(Color.Red)
.strokeDashArray([1, 2])
}.width('100%')
}
}
```
......
......@@ -5,20 +5,13 @@ The **\<Shape>** component is the parent component of the drawing components. Th
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.
> **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
This component can contain child components.
......@@ -28,10 +21,11 @@ This component can contain child components.
Shape(value?: PixelMap)
- Parameters
| Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- |
| value | PixelMap | No| - | Shape to draw. You can draw a shape in the specified **PixelMap** object. If no object is specified, the shape is drawn in the current drawing target.|
**Parameters**
| Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- |
| value | PixelMap | No| - | Shape to draw. You can draw a shape in the specified **PixelMap** object. If no object is specified, the shape is drawn in the current drawing target.|
## Attributes
......@@ -41,82 +35,201 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| 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.|
| fill | [ResourceColor](../../ui/ts-types.md) | 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.|
| stroke | [ResourceColor](../../ui/ts-types.md) | Color.Black | No| Stroke color.|
| fill | [ResourceColor](ts-types.md#resourcecolor8) | 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#resourcecolor8) | Color.Black | No| Stroke color.|
| strokeDashArray | Array&lt;Length&gt; | [] | No| Stroke dash.|
| 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](../../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.|
| 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.|
## Example
### Example 1
```ts
// xxx.ets
@Entry
@Component
struct ShapeExample {
build() {
Column({ space: 5 }) {
Text('basic').fontSize(30).fontColor(0xCCCCCC).width(320)
// Draw a 300 x 50 rectangle with strokes at (-2, -2). The fill color is 0x317Af7, the stroke color is black, the stroke width is 4, the stroke dash is 20, the offset is 10 to the left, the cap style is rounded, the join style is rounded, and anti-aliasing is enabled (default).
// Draw a 300 x 50 ellipse with strokes at (-2, 58). The fill color is 0x317Af7, the stroke color is black, the stroke width is 4, the stroke dash is 20, the offset is 10 to the left, the cap style is rounded, the join style is rounded, and anti-aliasing is enabled (default).
// Draw a 300 x 10 path at (-2, 118). The fill color is 0x317Af7, the stroke color is black, the stroke width is 4, the stroke dash is 20, the offset is 10 to the left, the cap style is rounded, the join style is rounded, and anti-aliasing is enabled (default).
Column({ space: 10 }) {
Text('basic').fontSize(11).fontColor(0xCCCCCC).width(320)
// Draw a 300 x 50 rectangle with strokes at (-2, -2). The fill color is 0x317AF7, the stroke color is black, the stroke width is 4, the stroke dash is 20, the offset is 10 to the left, the cap style is rounded, the join style is rounded, and anti-aliasing is enabled (default).
// Draw a 300 x 50 ellipse with strokes at (-2, 58). The fill color is 0x317AF7, the stroke color is black, the stroke width is 4, the stroke dash is 20, the offset is 10 to the left, the cap style is rounded, the join style is rounded, and anti-aliasing is enabled (default).
// Draw a 300 x 10 straight line at (-2, 118). The fill color is 0x317AF7, the stroke color is black, the stroke width is 4, the stroke dash is 20, the offset is 10 to the left, the cap style is rounded, the join style is rounded, and anti-aliasing is enabled (default).
Shape() {
Rect().width(300).height(50)
Ellipse().width(300).height(50).offset({ x: 0, y: 60 })
Path().width(300).height(10).commands('M0 0 L900 0').offset({ x: 0, y: 120 })
}
.viewPort({ x: -2, y: -2, width: 304, height: 130 })
.fill(0x317Af7).stroke(Color.Black).strokeWidth(4)
.strokeDashArray([20]).strokeDashOffset(10).strokeLineCap(LineCapStyle.Round)
.strokeLineJoin(LineJoinStyle.Round).antiAlias(true)
// Draw a 300 x 50 rectangle with strokes at (-1, -1). The fill color is 0x317Af7, the stroke color is black, and the stroke width is 2.
.fill(0x317AF7)
.stroke(Color.Black)
.strokeWidth(4)
.strokeDashArray([20])
.strokeDashOffset(10)
.strokeLineCap(LineCapStyle.Round)
.strokeLineJoin(LineJoinStyle.Round)
.antiAlias(true)
// Draw a 300 x 50 rectangle with strokes at (0, 0) and (-5, -5). The drawing start point is the midpoint of the stroke width by default. To fully display the strokes, you must set the coordinates of the start position of the viewport to negative values so that the viewport is offset by half the stroke width.
Shape() {
Rect().width(300).height(50)
}.viewPort({ x: -1, y: -1, width: 302, height: 52 }).fill(0x317Af7).stroke(Color.Black).strokeWidth(2)
}
.viewPort({ x: 0, y: 0, width: 320, height: 70 })
.fill(0x317AF7)
.stroke(Color.Black)
.strokeWidth(10)
Text('border').fontSize(30).fontColor(0xCCCCCC).width(320).margin({top:30})
// Draw a 300 x 10 path at (0, -5). The color is 0xEE8443, the stroke width is 10, and the stroke gap is 20.
Shape() {
Path().width(300).height(10).commands('M0 0 L900 0')
}.viewPort({ x: 0, y: -5, width: 300, height: 20 }).stroke(0xEE8443).strokeWidth(10).strokeDashArray([20])
// Draw a 300 x 10 path at (0, -5). The fill color is 0xEE8443, the stroke width is 10, the stroke dash is 20, and the offset is 10 to the left.
Rect().width(300).height(50)
}
.viewPort({ x: -5, y: -5, width: 320, height: 70 })
.fill(0x317AF7)
.stroke(Color.Black)
.strokeWidth(10)
Text('path').fontSize(11).fontColor(0xCCCCCC).width(320)
// Draw a straight line at (0, -5). The fill color is 0xEE8443, the stroke width is 10, and the stroke dash is 20.
Shape() {
Path().width(300).height(10).commands('M0 0 L900 0')
}
.viewPort({ x: 0, y: -5, width: 300, height: 20 })
.stroke(0xEE8443).strokeWidth(10).strokeDashArray([20]).strokeDashOffset(10)
// Draw a 300 x 10 path at (0, -5). The fill color is 0xEE8443, the stroke width is 10, and the stroke opacity is 0.5.
.stroke(0xEE8443)
.strokeWidth(10)
.strokeDashArray([20])
// Draw a straight line at (0, -5). The fill color is 0xEE8443, the stroke width is 10, the stroke dash is 20, and the offset is 10 to the left.
Shape() {
Path().width(300).height(10).commands('M0 0 L900 0')
}.viewPort({ x: 0, y: -5, width: 300, height: 20 }).stroke(0xEE8443).strokeWidth(10).strokeOpacity(0.5)
// Draw a 300 x 10 path at (0, -5). The fill color is 0xEE8443, the stroke width is 10, the stroke dash is 20, the offset is 10 to the left, and the cap style is rounded.
}
.viewPort({ x: 0, y: -5, width: 300, height: 20 })
.stroke(0xEE8443)
.strokeWidth(10)
.strokeDashArray([20])
.strokeDashOffset(10)
// Draw a straight line at (0, -5). The fill color is 0xEE8443, the stroke width is 10, and the stroke opacity is 0.5.
Shape() {
Path().width(300).height(10).commands('M0 0 L900 0')
}
.viewPort({ x: 0, y: -5, width: 300, height: 20 })
.stroke(0xEE8443).strokeWidth(10).strokeDashArray([20]).strokeLineCap(LineCapStyle.Round)
// Draw a 300 x 50 rectangle with strokes at (-5, -5). The fill color is 0x317Af7, the stroke width is 10, the stroke color is 0xEE8443, and the join style is rounded.
.stroke(0xEE8443)
.strokeWidth(10)
.strokeOpacity(0.5)
// Draw a straight line at (0, -5). The fill color is 0xEE8443, the stroke width is 10, the stroke dash is 20, and the cap style is rounded.
Shape() {
Rect().width(300).height(100)
Path().width(300).height(10).commands('M0 0 L900 0')
}
.viewPort({ x: -5, y: -5, width: 310, height: 120 })
.fill(0x317Af7).stroke(0xEE8443).strokeWidth(10).strokeLineJoin(LineJoinStyle.Round)
.viewPort({ x: 0, y: -5, width: 300, height: 20 })
.stroke(0xEE8443)
.strokeWidth(10)
.strokeDashArray([20])
.strokeLineCap(LineCapStyle.Round)
// Draw a closed path at (-80, -5). The fill color is 0x317AF7, the stroke width is 10, the stroke color is 0xEE8443, and the join style is miter (default value).
Shape() {
Path().width(300).height(60).commands('M0 0 L400 0 L400 200 Z')
Path().width(200).height(60).commands('M0 0 L400 0 L400 150 Z')
}
.viewPort({ x: -80, y: -5, width: 310, height: 100 })
.fill(0x317Af7).stroke(0xEE8443).strokeWidth(10)
.strokeLineJoin(LineJoinStyle.Miter).strokeMiterLimit(5)
.viewPort({ x: -80, y: -5, width: 310, height: 90 })
.fill(0x317AF7)
.stroke(0xEE8443)
.strokeWidth(10)
.strokeLineJoin(LineJoinStyle.Miter)
.strokeMiterLimit(5)
}.width('100%').margin({ top: 15 })
}
}
```
![en-us_image_0000001257058393](figures/en-us_image_0000001257058393.png)
### Example 2
```ts
// xxx.ets
@Entry
@Component
struct ShapeMeshExample {
@State columnVal: number = 0;
@State rowVal: number = 0;
@State count: number = 0;
@State verts: Array<number> = [];
@State shapeWidth: number = 600;
@State shapeHeight: number = 600;
build() {
Column() {
Shape() {
Rect()
.width('250px')
.height('250px')
.radiusWidth('10px')
.radiusHeight('10px')
.stroke('10px')
.margin({ left: '10px', top: '10px' })
.strokeWidth('10px')
.fill(Color.Blue)
Rect()
.width('250px')
.height('250px')
.radiusWidth('10px')
.radiusHeight('10px')
.stroke('10px')
.margin({ left: '270px', top: '10px' })
.strokeWidth('10px')
.fill(Color.Red)
}
.mesh(this.verts, this.columnVal, this.rowVal)
.width(this.shapeWidth + 'px')
.height(this.shapeHeight + 'px')
// The mesh distortion effect is displayed when the component is touched.
.onTouch((event: TouchEvent) => {
var touchX = event.touches[0].x * 2;
var touchY = event.touches[0].y * 2;
this.columnVal = 20;
this.rowVal = 20;
this.count = (this.columnVal + 1) * (this.rowVal + 1);
var orig = [this.count * 2];
var index = 0;
for (var i = 0; i <= this.rowVal; i++) {
var fy = this.shapeWidth * i / this.rowVal;
for (var j = 0; j <= this.columnVal; j++) {
var fx = this.shapeWidth * j / this.columnVal;
orig[index * 2 + 0] = this.verts[index * 2 + 0] = fx;
orig[index * 2 + 1] = this.verts[index * 2 + 1] = fy;
index++;
}
}
for (var k = 0; k < this.count * 2; k += 2) {
var dx = touchX - orig[k + 0];
var dy = touchY - orig[k + 1];
var dd = dx * dx + dy * dy;
var d = Math.sqrt(dd);
var pull = 80000 / (dd * d);
if (pull >= 1) {
this.verts[k + 0] = touchX;
this.verts[k + 1] = touchY;
} else {
this.verts[k + 0] = orig[k + 0] + dx * pull;
this.verts[k + 1] = orig[k + 1] + dy * pull;
}
}
})
}
.width('600px')
.height('600px')
.border({ width: 3, color: Color.Black })
}
}
```
Diagram:
![en-us_image1_0000001184628104](figures/en-us_image1_0000001184628104.png)
The mesh distortion effect is displayed when the component is touched, as shown below.
![en-us_image2_0000001184628104](figures/en-us_image2_0000001184628104.png)
......@@ -9,27 +9,22 @@ You can create explicit animation with your custom settings.
| 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: [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. |
## AnimationOptions
- Attributes
| Name| Type| Default Value| Description|
| -------- | -------- | -------- | -------- |
| duration | number | 1000 | Animation duration, in ms.|
| tempo | number | 1.0 | Animation playback speed. A larger value indicates faster animation playback, and a smaller value indicates slower animation playback. The value **0** means that there is no animation.|
| curve | Curve \| Curves | Linear | Animation curve.|
| delay | number | 0 | Delay of animation playback, in ms. By default, the playback is not delayed.|
| 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.|
| playMode | [PlayMode](ts-appendix-enums.md#playmode) | Normal | Animation playback mode. By default, the animation is played from the beginning after the playback is complete.|
| Name| Type| Description|
| -------- | -------- | -------- |
| duration | number | Animation duration, in ms.<br>Default value: **1000**|
| tempo | number | Animation playback speed. A larger value indicates faster animation playback, and a smaller value indicates slower animation playback. The value **0** means that there is no animation.<br>Default value: **1.0**|
| curve | Curve \| Curves | Animation curve.<br>Default value: **Curve.Linear**|
| delay | number | Delay of animation playback, in ms. By default, the playback is not delayed.<br>Default value: **0**|
| iterations | number | 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**|
| playMode | [PlayMode](ts-appendix-enums.md#playmode) | Animation playback mode. By default, the animation is played from the beginning after the playback is complete.<br>Default value: **PlayMode.Normal**|
| onFinish | () =&gt; void | Callback invoked when the animation playback is complete.|
- APIs
| Name| Description|
| -------- | -------- |
| onFinish() =&gt; void | Callback invoked when the animation playback is complete.|
## Example
......@@ -68,7 +63,7 @@ struct AnimateToExample {
} else {
animateTo({
duration: 200, // Animation duration
curve: Curve.Ease, // Animation curve
curve: Curve.Ease, // Animated curve
delay: 200, // Animation delay
iterations: 1, // Number of playback times
playMode: PlayMode.Normal // Animation playback mode
......
# Gesture Binding Methods
# Gesture Binding
Bind different types of gesture events to components and set response methods for them.
> **NOTE**<br>
> This method is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
None
> **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.
## Binding Gesture Recognition
......@@ -16,80 +13,128 @@ 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.
| Name | Type | Default Value | Description |
| Name | Type| Default Value| Description|
| -------- | -------- | -------- | -------- |
| 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**: 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**: 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 bound to both the parent and child components can be triggered, thereby implementing a bubbling effect. |
| 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**: 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**: 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
| Name | Description |
- GestureMask
| Name| Description|
| -------- | -------- |
| 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/>However, 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. |
| 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>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
| Name | Description |
- GestureType
| Name| Description|
| -------- | -------- |
| TapGesture | Tap gesture, which can be a single-tap or multi-tap gesture. |
| LongPressGesture | Long press gesture. |
| PanGesture | Pan gesture. |
| PinchGesture | Pinch gesture. |
| RotationGesture | Rotation gesture. |
| SwipeGesture | Swipe gesture, which can be idenfied when the swipe speed is 100 vp/s or higher. |
| GestureGroup | A group of gestures. Continuous recognition, parallel recognition, and exclusive recognition are supported. |
| TapGesture | Tap gesture, which can be a single-tap or multi-tap gesture.|
| LongPressGesture | Long press gesture.|
| PanGesture | Pan gesture, which requires a minimum 5 vp movement distance of a finger on the screen.|
| PinchGesture | Pinch gesture.|
| RotationGesture | Rotation gesture.|
| 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
A 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 definition, 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
| Name | Description |
- TapGesture
| 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
| Name | Type | Description |
| Name| Type| Description|
| -------- | -------- | -------- |
| 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 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|
| -------- | -------- | -------- |
| timestamp | number | Timestamp of the event. |
| target<sup>8+</sup> | [EventTarget](ts-universal-events-click.md) | Object that triggers the gesture event. |
| 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
```ts
// xxx.ets
@Entry
@Component
struct GestureSettingsExample {
@State value: string = ''
@State priorityTestValue: string = '';
@State parallelTestValue: string = '';
build() {
Column(){
Column() {
Text('Click\n' + this.value)
Column() {
Text('TapGesture:' + this.priorityTestValue).fontSize(28)
.gesture(
TapGesture()
.onAction(() => {
this.value = 'gesture onAction'
this.priorityTestValue += '\nText';
}))
}.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.
}
.height(200)
.width(250)
.padding(20)
.margin(20)
.border({ width: 3 })
// When priorityGesture is set, the tap gesture on the <Column> component is prioritized over the tap gesture on the child <Text> component.
.priorityGesture(
TapGesture()
.onAction((event: GestureEvent) => {
this.value = 'priorityGesture onAction' + '\ncomponent globalPos:('
+ event.target.area.globalPosition.x + ',' + event.target.area.globalPosition.y + ')\nwidth:'
+ event.target.area.width + '\nheight:' + event.target.area.height
}), GestureMask.IgnoreInternal
)
}.padding(60)
this.priorityTestValue += '\nColumn';
}), GestureMask.IgnoreInternal)
Column() {
Text('TapGesture:' + this.parallelTestValue).fontSize(28)
.gesture(
TapGesture()
.onAction(() => {
this.parallelTestValue += '\nText';
}))
}
.height(200)
.width(250)
.padding(20)
.margin(20)
.border({ width: 3 })
// When parallelGesture is set, the tap gestures on the <Column> component and on the child <Text> component are both recognized.
.parallelGesture(
TapGesture()
.onAction((event: GestureEvent) => {
this.parallelTestValue += '\nColumn';
}), GestureMask.Normal)
}
}
}
```
![en-us_image_0000001256858411](figures/en-us_image_0000001256858411.gif)
\ No newline at end of file
![en-us_image_0000001257058419](figures/en-us_image_0000001257058419.gif)
# Interpolation Calculation
> **NOTE**<br>
> **NOTE**
>
> This animation is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
......
# Video
The **\<Video>** component provides a video player.
The **\<Video>** component is used to play a video and control its playback.
> **NOTE**
>
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
To use online videos, you need to add the **ohos.permission.INTERNET** permission to the corresponding **abilities** in the **config.json** or **module.json** file, whichever is appropriate.
To use online videos, you must apply for the **ohos.permission.INTERNET** permission. For details about how to apply for the permission, see [Declaring Permissions](../../security/accesstoken-guidelines.md).
```
"abilities":[
{
...
"permissions": ["ohos.permission.INTERNET"],
...
}
]
```
## Child Components
Not supported
## APIs
Video(value: {src?: string | Resource, currentProgressRate?: number | string | PlaybackSpeed, previewUri?: string | PixelMap | Resource, controller?: VideoController})
**Parameters**
| Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- |
| 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).|
| currentProgressRate | number \| PlaybackSpeed<sup>8+</sup> | No| 1.0 \| PlaybackSpeed.<br>Speed_Forward_1_00_X | 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**. |
| previewUri | string \| PixelMap<sup>8+</sup> \| [Resource](ts-types.md#resource) | No| - | Path of the preview image.|
| controller | [VideoController](#videocontroller) | No| - | Controller.|
| Name | Type | Mandatory| Description |
| ------------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| 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 |
| previewUri | string \| PixelMap<sup>8+</sup> \| [Resource](ts-types.md#resource) | No | Path of the preview image. |
| controller | [VideoController](#videocontroller) | No | Controller. |
## PlaybackSpeed<sup>8+</sup>
| Name | Description |
| -------------------- | --------------------- |
| Speed_Forward_0_75_X | 0.75x playback speed. |
| -------------------- | --------- |
| Speed_Forward_0_75_X | 0.75x playback speed.|
| Speed_Forward_1_00_X | 1x playback speed. |
| Speed_Forward_1_25_X | 1.25x playback speed. |
| Speed_Forward_1_75_X | 1.75x playback speed. |
| Speed_Forward_1_25_X | 1.25x playback speed.|
| Speed_Forward_1_75_X | 1.75x playback speed.|
| Speed_Forward_2_00_X | 2x playback speed. |
## Attributes
| Name | Type | Default Value | Description |
| --------- | ---------------------------------------- | ------------- | -------------------------------------------------- |
| muted | boolean | false | Whether to mute the video. |
| autoPlay | boolean | false | Whether to enable auto play. |
| controls | boolean | true | Whether to display the video playback control bar. |
| objectFit | [ImageFit](ts-basic-components-image.md) | Cover | Video scale type. |
| loop | boolean | false | Whether to repeat the video. |
| Name | Type | Description |
| --------- | ---------------------------------------- | ----------------------------------------------- |
| muted | boolean | Whether to mute the video.<br>Default value: **false** |
| autoPlay | boolean | Whether to enable auto play.<br>Default value: **false** |
| controls | boolean | Whether to display the video playback control bar.<br>Default value: **true**|
| objectFit | [ImageFit](ts-appendix-enums.md#imagefit) | Video scale type.<br>Default value: **Cover** |
| loop | boolean | Whether to repeat the video.<br>Default value: **false** |
## Events
| Name| Description|
| -------- | -------- |
| onStart(event:() =&gt; void) | Triggered when the video is played.|
| onPause(event:() =&gt; void) | Triggered when the video playback is paused.|
| onFinish(event:() =&gt; void) | Triggered when the video playback is finished.|
| 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**.|
| onSeeking(callback:(event?: { time: number }) =&gt; void) | Triggered to report the time (in seconds) when the progress bar is being dragged.|
| 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?: { time: number }) =&gt; void) | Triggered once per 250 ms when the playback progress changes. The unit of the current playback time is second.|
| Name | Description |
| ------------------------------------------------------------ | ------------------------------------------------------------ |
| onStart(event:() =&gt; void) | Triggered when the video is played. |
| onPause(event:() =&gt; void) | Triggered when the video playback is paused. |
| onFinish(event:() =&gt; void) | Triggered when the video playback is finished. |
| 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**. |
| onSeeking(callback:(event?: { time: number }) =&gt; void) | Triggered to report the time (in seconds) when the progress bar is being dragged. |
| 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?: { time: number }) =&gt; void) | Triggered once per 250 ms when the playback progress changes. The unit of the current playback time is second. |
## VideoController
A **VideoController** object can control one or more videos.
Defines a **VideoController** object to control one or more videos.
### Objects to Import
```
```ts
controller: VideoController = new VideoController();
```
......@@ -109,9 +101,9 @@ Sets the video playback position.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ----- | ------ | --------- | ------------- | ------------------------ |
| value | number | Yes | - | Video playback position. |
| Name| Type| Mandatory| Description |
| ------ | -------- | ---- | --------------------------- |
| value | number | Yes | Video playback position. |
### requestFullscreen
......@@ -121,9 +113,9 @@ Requests full-screen mode.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ----- | ------ | --------- | ------------- | -------------------------------------------- |
| value | boolean | Yes | false | Whether the playback is in full-screen mode. |
| Name | Type | Mandatory | Description |
| ----- | ------ | ---- | ------- |
| value | boolean | Yes | Whether the playback is in full-screen mode.<br>Default value: **false**|
### exitFullscreen
......@@ -139,19 +131,20 @@ Sets the video playback position with the specified seek mode.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | --------- | ------------- | ----------------------- |
| value | number | Yes | - | Video playback position. |
| seekMode | SeekMode | Yes | - | Seek mode. |
| Name | Type| Mandatory| Description |
| -------- | -------- | ---- | ------------------ |
| value | number | Yes | Video playback position.|
| seekMode | SeekMode | Yes | Seek mode. |
## SeekMode<sup>8+</sup>
| Name | Description |
| ---------------- | ------------------------------------------------------------------------- |
| ---------------- | -------------- |
| PreviousKeyframe | Seeks to the nearest previous keyframe. |
| NextKeyframe | Seeks to the nearest next keyframe. |
| ClosestKeyframe | Seeks to the nearest keyframe. |
| Accurate | Seeks to a specific frame, regardless of whether the frame is a keyframe. |
| Accurate | Seeks to a specific frame, regardless of whether the frame is a keyframe.|
## Example
......@@ -161,12 +154,13 @@ Sets the video playback position with the specified seek mode.
@Entry
@Component
struct VideoCreateComponent {
@State srcs: Resource = $rawfile('video1');
@State srcs: Resource = $rawfile('video1.mp4');
@State previewUris: Resource = $r('app.media.img');
@State currentProgressRates: number = 1;
@State autoPlays: boolean = false;
@State controlsss: boolean = true;
controller: VideoController = new VideoController();
build() {
Column() {
Video({
......@@ -203,7 +197,7 @@ struct VideoCreateComponent {
})
Row() {
Button("src").onClick(() => {
this.srcs = $rawfile('video2');
this.srcs = $rawfile('video2.mp4');
});
Button("previewUri").onClick(() => {
this.previewUris = $r('app.media.img1');
......
# Action Sheet
> ![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.
An action sheet is a dialog box that displays actions a user can take.
> **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
......@@ -15,39 +14,41 @@ None
## 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 the action sheet.
- paramObject1 parameters
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| title | string \|[Resource](../../ui/ts-types.md#resource) | No | None | Title of the dialog box. |
| message | string \|[Resource](../../ui/ts-types.md#resource) | | | 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#resource),<br>action: () =&gt; void<br/>} | number | string | 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 | No | DialogAlignment.Default | Alignment mode of the dialog box in the vertical direction. |
| 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. |
| sheets | Array&lt;SheetInfo&gt; | Yes | - | Options in the dialog box. Each option supports the image, text, and callback. |
- SheetInfo parameters
| | | | | |
| -------- | -------- | -------- | -------- | -------- |
| Name | Type | Mandatory | Default Value | Description |
| title | string | Yes | - | Sheet text. |
| icon | string | No | None | Sheet icon. |
| action | ()=&gt;void | Yes | - | Callback when the sheet is selected. |
**Parameters**
| Name | Type | Mandatory | Description |
| ---------- | -------------------------- | ------- | ----------------------------- |
| title | string \| [Resource](ts-types.md#resource) | Yes | Title of the dialog box.|
| message | string \| [Resource](ts-types.md#resource) | Yes | Content of the dialog box. |
| autoCancel | boolean | No | Whether to close the dialog box when the overlay is clicked.<br>Default value: **true**|
| 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: number \| string \| [Resource](ts-types.md#resource),<br/>dy: number \| string \| [Resource](ts-types.md#resource)<br/>} | No | Offset of the dialog box relative to the alignment position.<br>Default value: **{<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.|
## Example
## SheetInfo
| 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
// xxx.ets
@Entry
@Component
struct ActionSheetExapmle {
struct ActionSheetExample {
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Button('Click to Show ActionSheet')
......@@ -58,26 +59,26 @@ struct ActionSheetExapmle {
confirm: {
value: 'Confirm button',
action: () => {
console.log('Get Alert Dialog handled')
console.log('Get Alert Dialog handled');
}
},
sheets: [
{
title: 'apples',
action: () => {
console.error('apples')
console.log('apples');
}
},
{
title: 'bananas',
action: () => {
console.error('bananas')
console.log('bananas');
}
},
{
title: 'pears',
action: () => {
console.error('pears')
console.log('pears');
}
}
]
......@@ -89,6 +90,4 @@ struct ActionSheetExapmle {
}
```
![en-us_image_0000001212058508](figures/en-us_image_0000001212058508.gif)
# Alert Dialog Box
You can set the text content and response callback for an alert dialog box.
> **NOTE**
>
> This method is 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.
> 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
| Name | Type | Default Value | Description |
| -------- | -------- | -------- | -------- |
| show | options: { paramObject1 \| paramObject2} | - | Defines and displays the **<AlertDialog\>** component. |
- paramObject1 parameters
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| title | string \| [Resource](../../ui/ts-types.md#resource-type) | No | - | Title of a dialog box. |
| message | string \| [Resource](../../ui/ts-types.md#resource-type) | Yes | - | 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#resource-type),<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. |
| 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#resource-type),<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. |
| Name | Type | Description|
| ---- | --------------- | -------- |
| show | AlertDialogParamWithConfirm \| AlertDialogParamWithButtons | Shows the **\<AlertDialog>** component. |
- paramObject2 parameters
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| title | string \| [Resource](../../ui/ts-types.md#resource-type) | No | - | Title of a dialog box. |
| message | string \| [Resource](../../ui/ts-types.md#resource-type) | 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#resource-type),<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#resource-type),<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#resource-type),<br/>dy: Length \| [Resource](../../ui/ts-types.md#resource-type)<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. |
## AlertDialogParamWithConfirm
| Name | Type | Mandatory | Description |
| ---------- | ---------------- | ---------- | ------------------------------- |
| title | string \| [Resource](ts-types.md#resource) | No | Title of the dialog box.|
| message | string \| [Resource](ts-types.md#resource) | Yes | Content of the dialog box.|
| autoCancel | boolean | No | Whether to close the dialog box when the overlay is clicked.<br>Default value: **true**|
| 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.|
| 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](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 | number | No | Number of grid columns occupied by the width of the dialog box. |
## AlertDialogParamWithButtons
| Name | Type | Mandatory | Description |
| --------------- | ---------------------- | ------------ | --------------------- |
| title | string \| [Resource](ts-types.md#resource) | No | Title of the dialog box. |
| message | string \| [Resource](ts-types.md#resource) | 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 | {<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 | number | No | Number of grid columns occupied by the width of the dialog box. |
## Example
```ts
// xxx.ets
@Entry
@Component
struct AlertDialogExample {
build() {
Column({ space: 5 }) {
Button('one button dialog')
......
# Custom Dialog Box
A custom dialog box is a dialog box you customize by using APIs of the **CustomDialogController** class. You can set the style and content to your preference for a custom dialog box.
> **NOTE**<br>
> This method 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.
The **CustomDialogController** class is used to display a custom dialog box.
## APIs
CustomDialogController(value:{builder: CustomDialog, cancel?: () =&gt; void, autoCancel?: boolean, alignment?: DialogAlignment, offset?: Offset, customStyle?: boolean})
- Parameters
| Name | Type | Mandatory | Default Value | 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. |
| autoCancel | boolean | No | true | Whether to allow users to click the overlay to exit. |
| alignment | DialogAlignment | No | DialogAlignment.Default | Alignment mode of the dialog box in the vertical direction. |
| 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. |
| customStyle | boolean | No | false | Whether the style of the dialog box is customized. |
| gridCount<sup>8+</sup> | number | No | - | Count of grid columns occupied by the dialog box. |
- DialogAlignment enums
| Name | Description |
| -------- | -------- |
| Top | Aligns vertically to the top. |
| Center | Aligns vertically to the middle. |
| Bottom | Aligns vertically to the bottom. |
| Default | Default alignment. |
| TopStart<sup>8+</sup> | Top left alignment. |
| TopEnd<sup>8+</sup> | Top right alignment. |
| CenterStart<sup>8+</sup> | Center left alignment. |
| CenterEnd<sup>8+</sup> | Center right alignment. |
| BottomStart<sup>8+</sup> | Bottom left alignment. |
| BottomEnd<sup>8+</sup> | Bottom right alignment. |
CustomDialogController(value:{builder: CustomDialog, cancel?: () =&gt; void, autoCancel?: boolean, alignment?: DialogAlignment, offset?: Offset, customStyle?: boolean, gridCount?: number})
## CustomDialogController
**Parameters**
| Name | Type | Mandatory | Description |
| ---------------------- | ---------------------------------------- | ------------------------- | ---------------------- |
| builder | any | Yes | Constructor of the custom dialog box content. |
| cancel | () =&gt; void | No | Callback invoked when the dialog box is closed after the overlay exits. |
| autoCancel | boolean | No | Whether to allow users to click the overlay to exit.<br>Default value: **true** |
| alignment | [DialogAlignment](#dialogalignment) | No | Alignment mode of the dialog box in the vertical direction.<br>Default value: **DialogAlignment.Default** |
| 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.|
| 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. |
### Objects to Import
## DialogAlignment
| Name | Description |
| ------------------------ | ------- |
| Top | Vertical top alignment.|
| Center | Vertical center alignment.|
| Bottom | Vertical bottom alignment.|
| Default | Default alignment.<br/>**NOTE**<br/>This value is equivalent to **Center**. |
| TopStart<sup>8+</sup> | Top left alignment. |
| TopEnd<sup>8+</sup> | Top right alignment. |
| CenterStart<sup>8+</sup> | Center left alignment. |
| CenterEnd<sup>8+</sup> | Center right alignment. |
| BottomStart<sup>8+</sup> | Bottom left alignment. |
| BottomEnd<sup>8+</sup> | Bottom right alignment. |
```
## CustomDialogController
### Objects to Import
```ts
dialogController : CustomDialogController = new CustomDialogController(value:{builder: CustomDialog, cancel?: () => void, autoCancel?: boolean})
```
......@@ -59,25 +60,30 @@ Opens the content of the custom dialog box. If the content has been displayed, t
### close
close(): void
Closes the custom dialog box. If the dialog box is closed, the setting does not take effect.
Closes the custom dialog box. If the dialog box is closed, this API does not take effect.
## Example
## Example
```ts
// xxx.ets
@CustomDialog
struct CustomDialogExample {
@Link textValue: string
@Link inputValue: string
controller: CustomDialogController
cancel: () => void
confirm: () => void
build() {
Column() {
Text('Software uninstall').width('70%').fontSize(20).margin({ top: 10, bottom: 10 })
Image($r('app.media.icon')).width(80).height(80)
Text('Whether to uninstall a software?').fontSize(16).margin({ bottom: 10 })
Text('Change text').fontSize(20).margin({ top: 10, bottom: 10 })
TextInput({ placeholder: '', text: this.textValue }).height(60).width('90%')
.onChange((value: string) => {
this.textValue = value
})
Text('Whether to change a text?').fontSize(16).margin({ bottom: 10 })
Flex({ justifyContent: FlexAlign.SpaceAround }) {
Button('cancel')
.onClick(() => {
......@@ -86,6 +92,7 @@ struct CustomDialogExample {
}).backgroundColor(0xffffff).fontColor(Color.Black)
Button('confirm')
.onClick(() => {
this.inputValue = this.textValue
this.controller.close()
this.confirm()
}).backgroundColor(0xffffff).fontColor(Color.Red)
......@@ -97,8 +104,10 @@ struct CustomDialogExample {
@Entry
@Component
struct CustomDialogUser {
@State textValue: string = ''
@State inputValue: string = 'click me'
dialogController: CustomDialogController = new CustomDialogController({
builder: CustomDialogExample({ cancel: this.onCancel, confirm: this.onAccept }),
builder: CustomDialogExample({ cancel: this.onCancel, confirm: this.onAccept, textValue: $textValue, inputValue: $inputValue }),
cancel: this.existApp,
autoCancel: true
})
......@@ -115,7 +124,7 @@ struct CustomDialogUser {
build() {
Column() {
Button('click me')
Button(this.inputValue)
.onClick(() => {
this.dialogController.open()
}).backgroundColor(0x317aff)
......
# Text Picker Dialog Box
> ![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.
A text picker dialog box is a dialog box that allows users to select text from the given range.
> **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.
You can display a text picker in a dialog box to allow users to select text from the given range.
## Required Permissions
......@@ -19,21 +21,23 @@ Shows a text picker in the given settings.
| Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- |
| range | string[] | Yes| - | Data selection range of the picker.|
| selected | number | No| First element| Index value of the selected item in the range.|
| defaultPickerItemHeight | number | No| - | Height of the default selected item in the picker.|
| onAccept | (value: TextPickerResult) => void | No| - | Triggered when the OK button in the dialog box is clicked.|
| onCancel | () => void | No| - | Triggered when the Cancel button in the dialog box is clicked.|
| onChange | (value: TextPickerResult) => void | No| - | Triggered when the selected item in the picker changes.|
| 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. This parameter does not take effect when the **selected** parameter is set. |
| 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.|
| 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.|
- TextPickerResult
| Name| Type| Description|
| -------- | -------- | -------- |
| value | string | Text of the selected item.|
| index | number | Index value of the selected item in the range.|
| value | string | Value of the selected item.|
| index | number | Index of the selected item in the range.|
## Example
```
```ts
// xxx.ets
@Entry
@Component
struct TextPickerDialogExample {
......
# 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**
>
> 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
OffscreenCanvasRenderingContext2D(width: number, height: number, setting: RenderingContextSettings)
- Parameters
| Name | Type | Mandatory | Default Value | Description |
| ------- | ---------------------------------------- | --------- | ------------- | ------------------------------- |
| width | number | Yes | - | Width of the offscreen canvas. |
| height | number | Yes | - | Height of the offscreen canvas. |
| setting | [RenderingContextSettings](ts-canvasrenderingcontext2d.md#renderingcontextsettings) | Yes | - | See RenderingContextSettings. |
**Parameters**
| Name | Type | Mandatory| Description |
| ------- | ------------------------------------------------------------ | ---- | ------------------------------------ |
| width | number | Yes | Width of the offscreen canvas. |
| height | number | Yes | Height of the offscreen canvas. |
| setting | [RenderingContextSettings](ts-canvasrenderingcontext2d.md#renderingcontextsettings) | Yes | See RenderingContextSettings.|
## Attributes
| Name | Type | Default Value | 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. |
| [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. |
| [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. |
| [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**. |
| [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. |
| [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'**. |
| [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**. |
| [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. |
| [globalAlpha](#globalalpha) | number | - | Opacity. **0.0**: completely transparent; **1.0**: completely opaque. |
| [lineDashOffset](#linedashoffset) | number | 0.0 | Offset of the dashed line. The precision is float. |
| [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'**. |
| [shadowBlur](#shadowblur) | number | 0.0 | Blur level during shadow drawing. A larger value indicates a more blurred effect. The precision is float. |
| [shadowColor](#shadowcolor) | &lt;color&gt; | - | Shadow color. |
| [shadowOffsetX](#shadowoffsetx) | number | - | X-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. |
| imageSmoothingQuality | string | 'low' | Image smoothness. The value can be **'low'**, **'medium'**, or **'high'**. |
| Name | Type | Description |
| ---------------------------------------- | ---------------------------------------- | ---------------------------------------- |
| [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 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. |
| [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) | 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) | 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 | 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 | 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) | 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) | 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.<br>**0.0**: completely transparent.<br>**1.0**: completely opaque. |
| [lineDashOffset](#linedashoffset) | number | Offset of the dashed line. The precision is float.<br>- Default value: **0.0**|
| [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 | Blur level during shadow drawing. A larger value indicates a more blurred effect. The precision is float.<br>- Default value: **0.0**|
| [shadowColor](#shadowcolor) | string | Shadow color. |
| [shadowOffsetX](#shadowoffsetx) | number | X-axis shadow offset relative to the original object. |
| [shadowOffsetY](#shadowoffsety) | number | Y-axis shadow offset relative to the original object. |
| [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**|
> **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
```ts
// xxx.ets
@Entry
......@@ -84,7 +83,6 @@ struct FillStyleExample {
### lineWidth
```ts
// xxx.ets
@Entry
......@@ -118,7 +116,6 @@ struct LineWidthExample {
### strokeStyle
```ts
// xxx.ets
@Entry
......@@ -148,13 +145,11 @@ struct StrokeStyleExample {
}
```
![en-us_image_0000001257058429](figures/en-us_image_0000001257058429.png)
### lineCap
```ts
// xxx.ets
@Entry
......@@ -192,7 +187,6 @@ struct LineCapExample {
### lineJoin
```ts
// xxx.ets
@Entry
......@@ -231,7 +225,6 @@ struct LineJoinExample {
### miterLimit
```ts
// xxx.ets
@Entry
......@@ -270,7 +263,6 @@ struct MiterLimit {
### font
```ts
// xxx.ets
@Entry
......@@ -304,7 +296,6 @@ struct Fonts {
### textAlign
```ts
// xxx.ets
@Entry
......@@ -353,7 +344,6 @@ struct CanvasExample {
### textBaseline
```ts
// xxx.ets
@Entry
......@@ -402,7 +392,6 @@ struct TextBaseline {
### globalAlpha
```ts
// xxx.ets
@Entry
......@@ -439,7 +428,6 @@ struct GlobalAlpha {
### lineDashOffset
```ts
// xxx.ets
@Entry
......@@ -458,6 +446,7 @@ struct LineDashOffset {
.onReady(() =>{
this.offContext.arc(100, 75, 50, 0, 6.28)
this.offContext.setLineDash([10,20])
this.offContext.lineDashOffset = 10.0;
this.offContext.stroke();
var image = this.offContext.transferToImageBitmap()
this.context.transferFromImageBitmap(image)
......@@ -467,27 +456,26 @@ struct LineDashOffset {
.height('100%')
}
}
```
```
![en-us_image_0000001212058506](figures/en-us_image_0000001212058506.png)
### globalCompositeOperation
| Name | Description |
| ---------------- | ---------------------------------------- |
| ---------------- | ------------------------ |
| 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-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-atop | Displays the existing drawing on the top of 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. |
| lighter | Displays both the new drawing and the existing drawing. |
| destination-out | Displays the existing drawing outside the new drawing. |
| lighter | Displays both the new and 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
// xxx.ets
......@@ -530,7 +518,6 @@ struct GlobalCompositeOperation {
### shadowBlur
```ts
// xxx.ets
@Entry
......@@ -566,7 +553,6 @@ struct ShadowBlur {
### shadowColor
```ts
// xxx.ets
@Entry
......@@ -587,8 +573,7 @@ struct ShadowColor {
this.offContext.shadowColor = 'rgb(0,0,255)'
this.offContext.fillStyle = 'rgb(255,0,0)'
this.offContext.fillRect(30, 30, 100, 100)
var image = this.offContext.transferToImageBitmap
()
var image = this.offContext.transferToImageBitmap()
this.context.transferFromImageBitmap(image)
})
}
......@@ -603,7 +588,6 @@ struct ShadowColor {
### shadowOffsetX
```ts
// xxx.ets
@Entry
......@@ -640,7 +624,6 @@ struct ShadowOffsetX {
### shadowOffsetY
```ts
// xxx.ets
@Entry
......@@ -677,7 +660,6 @@ struct ShadowOffsetY {
### imageSmoothingEnabled
```ts
// xxx.ets
@Entry
......@@ -719,18 +701,19 @@ fillRect(x: number, y: number, w: number, h: number): void
Fills a rectangle on the canvas.
- 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. |
**Parameters**
- 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
// xxx.ets
// xxx.ets
@Entry
@Component
struct FillRect {
......@@ -765,23 +748,26 @@ strokeRect(x: number, y: number, w: number, h: number): void
Draws an outlined rectangle on the canvas.
- 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. |
**Parameters**
- 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
// xxx.ets
@Entry
@Component
struct StrokeRect {
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)
......@@ -809,24 +795,26 @@ clearRect(x: number, y: number, w: number, h: number): void
Clears the content in a rectangle on the canvas.
- 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. |
**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
**Example**
```ts
// xxx.ets
// xxx.ets
@Entry
@Component
struct ClearRect {
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)
......@@ -835,8 +823,8 @@ Clears the content in a rectangle on the canvas.
.backgroundColor('#ffff00')
.onReady(() =>{
this.offContext.fillStyle = 'rgb(0,0,255)'
this.offContext.fillRect(0,0,500,500)
this.offContext.clearRect(20,20,150,100)
this.offContext.fillRect(20,20,200,200)
this.offContext.clearRect(30,30,150,100)
var image = this.offContext.transferToImageBitmap()
this.context.transferFromImageBitmap(image)
})
......@@ -852,27 +840,30 @@ Clears the content in a rectangle on the canvas.
### 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.
- 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. |
**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.|
| maxWidth | number | No | - | Maximum width allowed for the text. |
- Example
**Example**
```ts
// xxx.ets
// xxx.ets
@Entry
@Component
struct FillText {
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)
......@@ -901,22 +892,26 @@ strokeText(text: string, x: number, y: number): void
Draws a text stroke on the canvas.
- 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. |
**Parameters**
- 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 of the text to be drawn. |
```
**Example**
```ts
// xxx.ets
@Entry
@Component
struct StrokeText {
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)
......@@ -945,31 +940,47 @@ measureText(text: string): TextMetrics
Returns a **TextMetrics** object used to obtain the width of specified text.
- Parameters
| Name | Type | Mandatory | Default Value | Description |
| ---- | ------ | --------- | ------------- | -------------------- |
| text | string | Yes | "" | Text to be measured. |
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ---- | ------ | ---- | ---- | ---------- |
| text | string | Yes | "" | Text to be measured.|
**Return value**
| Type | Description |
| ----------- | ------- |
| TextMetrics | **TextMetrics** object.|
- Return value
| Type | Description |
| ----------- | ----------------------- |
| TextMetrics | **TextMetrics** object. |
**TextMetrics** attributes
- **TextMetrics** attributes
| Name | Type | Description |
| ----- | ------ | ------------------ |
| width | number | Width of the text. |
| 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
**Example**
```ts
// xxx.ets
// xxx.ets
@Entry
@Component
struct MeasureText {
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)
......@@ -999,20 +1010,23 @@ stroke(path?: Path2D): void
Strokes a path.
- Parameters
| Name | Type | Mandatory | Default Value | Description |
| ---- | ---------------------------------------- | --------- | ------------- | -------------------------- |
| path | [Path2D](ts-components-canvas-path2d.md) | No | null | A **Path2D** path to draw. |
**Parameters**
- Example
| Name | Type | Mandatory | Default Value | Description |
| ---- | ---------------------------------------- | ---- | ---- | ------------ |
| path | [Path2D](ts-components-canvas-path2d.md) | No | null | A **Path2D** path to draw.|
```
**Example**
```ts
// xxx.ets
@Entry
@Component
struct Stroke {
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)
......@@ -1022,6 +1036,8 @@ Strokes a path.
.onReady(() =>{
this.offContext.moveTo(25, 25)
this.offContext.lineTo(25, 105)
this.offContext.lineTo(75, 105)
this.offContext.lineTo(75, 25)
this.offContext.strokeStyle = 'rgb(0,0,255)'
this.offContext.stroke()
var image = this.offContext.transferToImageBitmap()
......@@ -1043,16 +1059,17 @@ beginPath(): void
Creates a drawing path.
- Example
**Example**
```ts
// xxx.ets
// xxx.ets
@Entry
@Component
struct BeginPath {
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)
......@@ -1085,22 +1102,24 @@ moveTo(x: number, y: number): void
Moves a drawing path to a target position on the canvas.
- 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. |
**Parameters**
- 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
// xxx.ets
// xxx.ets
@Entry
@Component
struct MoveTo {
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)
......@@ -1131,22 +1150,24 @@ lineTo(x: number, y: number): void
Connects the current point to a target position using a straight line.
- 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. |
**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
**Example**
```ts
// xxx.ets
// xxx.ets
@Entry
@Component
struct LineTo {
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)
......@@ -1177,16 +1198,17 @@ closePath(): void
Draws a closed path.
- Example
**Example**
```ts
// xxx.ets
// xxx.ets
@Entry
@Component
struct ClosePath {
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)
......@@ -1215,20 +1237,27 @@ Draws a closed path.
### 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.
- 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'**. |
**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"**.|
**Return value**
| Type | Description |
| ------------------------------- | ----------------------- |
| [CanvasPattern](#canvaspattern) | Created pattern for image filling based on a specified source image and repetition mode.|
- Example
**Example**
```ts
// xxx.ets
// xxx.ets
@Entry
@Component
struct CreatePattern {
......@@ -1236,6 +1265,7 @@ Creates a pattern for image filling based on a specified source image and repeti
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private img:ImageBitmap = new ImageBitmap("common/images/icon.jpg")
private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings)
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context)
......@@ -1265,26 +1295,28 @@ bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number,
Draws a cubic bezier curve on the canvas.
- Name
| 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. |
| cp2x | number | Yes | 0 | X-coordinate of the second parameter of the bezier curve. |
| cp2y | number | Yes | 0 | Y-coordinate of the second parameter of 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. |
**Parameters**
| 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.|
| cp2x | number | Yes | 0 | X-coordinate of the second parameter of the bezier curve.|
| cp2y | number | Yes | 0 | Y-coordinate of the second parameter of 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
// xxx.ets
@Entry
@Component
struct BezierCurveTo {
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)
......@@ -1315,24 +1347,26 @@ quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void
Draws a quadratic curve on the canvas.
- 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. |
**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
**Example**
```ts
// xxx.ets
// xxx.ets
@Entry
@Component
struct QuadraticCurveTo {
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)
......@@ -1359,30 +1393,32 @@ Draws a quadratic curve on the canvas.
### 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.
- Parameters
| 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. |
| radius | number | Yes | 0 | Radius of the arc. |
| startAngle | number | Yes | 0 | Start radian of the arc. |
| endAngle | number | Yes | 0 | End radian of the arc. |
| anticlockwise | boolean | No | false | Whether to draw the arc counterclockwise. |
**Parameters**
| 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.|
| radius | number | Yes | 0 | Radius of the arc. |
| startAngle | number | Yes | 0 | Start radian of the arc. |
| endAngle | number | Yes | 0 | End radian of the arc. |
| counterclockwise | boolean | No | false | Whether to draw the arc counterclockwise.|
- Example
**Example**
```ts
// xxx.ets
// xxx.ets
@Entry
@Component
struct Arc {
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)
......@@ -1412,25 +1448,27 @@ arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void
Draws an arc based on the radius and points on the arc.
- 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. |
**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
**Example**
```ts
// xxx.ets
// xxx.ets
@Entry
@Component
struct ArcTo {
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)
......@@ -1456,27 +1494,27 @@ Draws an arc based on the radius and points on the arc.
### 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
| 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. |
**Parameters**
- 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
// xxx.ets
// xxx.ets
@Entry
@Component
struct CanvasExample {
......@@ -1491,7 +1529,7 @@ Draws an ellipse in the specified rectangular region.
.backgroundColor('#ffff00')
.onReady(() =>{
this.offContext.beginPath()
this.offContext.ellipse(200, 200, 50, 100, Math.PI * 0.25, Math.PI * 0.5, Math.PI)
this.offContext.ellipse(200, 200, 50, 100, Math.PI * 0.25, Math.PI * 0.5, Math.PI * 2)
this.offContext.stroke()
var image = this.offContext.transferToImageBitmap()
this.context.transferFromImageBitmap(image)
......@@ -1508,28 +1546,30 @@ Draws an ellipse in the specified rectangular region.
### 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 |
| ------ | ------ | --------- | ------------- | ---------------------------------------- |
| 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. |
| 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
**Example**
```ts
// xxx.ets
// 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)
......@@ -1554,20 +1594,25 @@ Creates a rectangle.
### fill
fill(): void
fill(fillRule?: CanvasFillRule): void
Fills the area inside a closed path on the canvas.
Fills the area inside a closed 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 fill.<br>The options are **"nonzero"** and **"evenodd"**.|
```ts
// xxx.ets
// xxx.ets
@Entry
@Component
struct Fill {
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)
......@@ -1590,22 +1635,84 @@ Fills the area inside a closed path.
![en-us_image_0000001256858421](figures/en-us_image_0000001256858421.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)
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(() =>{
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.offContext.fillStyle = 'green';
this.offContext.fill(region, "evenodd");
var image = this.offContext.transferToImageBitmap()
this.context.transferFromImageBitmap(image)
})
}
.width('100%')
.height('100%')
}
}
```
![en-us_image_000000127777775](figures/en-us_image_000000127777775.png)
### clip
clip(): void
clip(fillRule?: CanvasFillRule): void
Sets the current path to a clipping path.
- Example
**Parameters**
| 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
// xxx.ets
// xxx.ets
@Entry
@Component
struct Clip {
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)
......@@ -1613,11 +1720,11 @@ Sets the current path to a clipping path.
.height('100%')
.backgroundColor('#ffff00')
.onReady(() =>{
this.offContext.rect(0, 0, 200, 200)
this.offContext.rect(0, 0, 100, 200)
this.offContext.stroke()
this.offContext.clip()
this.offContext.fillStyle = "rgb(255,0,0)"
this.offContext.fillRect(0, 0, 150, 150)
this.offContext.fillRect(0, 0, 200, 200)
var image = this.offContext.transferToImageBitmap()
this.context.transferFromImageBitmap(image)
})
......@@ -1631,27 +1738,112 @@ Sets the current path to a clipping path.
![en-us_image_0000001257058441](figures/en-us_image_0000001257058441.png)
clip(path:Path2D, fillRule?: CanvasFillRule): void
Sets a closed path to a clipping path.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------------- | ---- | --------- | ---------------------------------------- |
| path | Path2D | Yes | | A **Path2D** path to clip.|
| 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
// xxx.ets
@Entry
@Component
struct Clip {
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(() =>{
let region = new Path2D();
region.rect(80,10,20,130);
region.rect(40,50,100,50);
this.offContext.clip(region,"evenodd")
this.offContext.fillStyle = "rgb(255,0,0)"
this.offContext.fillRect(0, 0, 600, 600)
var image = this.offContext.transferToImageBitmap()
this.context.transferFromImageBitmap(image)
})
}
.width('100%')
.height('100%')
}
}
```
![en-us_image_000000127777779](figures/en-us_image_000000127777779.png)
### filter
filter(filter: string): void
Sets a filter for the image on the canvas. This API is a void API.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ------ | ------ | ---- | ---- | ------------ |
| filter | string | Yes | - | Functions that accept various filter effects.|
### getTransform
getTransform(): Matrix2D
Obtains the current transformation matrix being applied to the context. This API is a void API.
### resetTransform
resetTransform(): void
Resets the current transform to the identity matrix. This API is a void API.
### direction
direction(direction: CanvasDirection): void
Sets the text direction for drawing text. This API is a void API.
### rotate
rotate(rotate: number): void
rotate(angle: number): void
Rotates a canvas clockwise around its coordinate axes.
- 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. |
**Parameters**
| 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
**Example**
```ts
// xxx.ets
// xxx.ets
@Entry
@Component
struct Rotate {
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)
......@@ -1678,24 +1870,26 @@ Rotates a canvas clockwise around its coordinate axes.
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. |
| Name | Type | Mandatory | Default Value | Description |
| ---- | ------ | ---- | ---- | ----------- |
| x | number | Yes | 0 | Horizontal scale factor.|
| y | number | Yes | 0 | Vertical scale factor.|
- Example
**Example**
```ts
// xxx.ets
// xxx.ets
@Entry
@Component
struct Scale {
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)
......@@ -1703,9 +1897,10 @@ Scales a canvas based on scale factors.
.height('100%')
.backgroundColor('#ffff00')
.onReady(() =>{
this.offContext.strokeRect(10, 10, 25, 25)
this.offContext.lineWidth = 3
this.offContext.strokeRect(30, 30, 50, 50)
this.offContext.scale(2, 2) // Scale to 200%
this.offContext.strokeRect(10, 10, 25, 25)
this.offContext.strokeRect(30, 30, 50, 50)
var image = this.offContext.transferToImageBitmap()
this.context.transferFromImageBitmap(image)
})
......@@ -1721,37 +1916,40 @@ Scales a canvas based on scale factors.
### 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.
> **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.
>
> - x' = scaleX \* x + skewY \* y + translateX
>
> - y' = skewX \* x + scaleY \* y + translateY
- 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. |
**Parameters**
| 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
**Example**
```ts
// xxx.ets
// xxx.ets
@Entry
@Component
struct Transform {
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)
......@@ -1782,30 +1980,32 @@ Defines a transformation matrix. To transform a graph, you only need to set para
### 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()** API.
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 |
| ---------- | ------ | --------- | ------------- | ------------------- |
| 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. |
| 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
**Example**
```ts
// xxx.ets
// xxx.ets
@Entry
@Component
struct SetTransform {
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)
......@@ -1828,8 +2028,10 @@ Resets the existing transformation matrix and creates a new transformation matri
}
```
![en-us_image_0000001211898518](figures/en-us_image_0000001211898518.png)
![en-us_image_0000001193872526](figures/en-us_image_0000001193872526.png)
### translate
### translate
......@@ -1837,22 +2039,24 @@ translate(x: number, y: number): void
Moves the origin of the coordinate system.
- Parameters
| Name | Type | Mandatory | Default Value | Description |
| ---- | ------ | --------- | ------------- | ------------------- |
| x | number | Yes | 0 | X-axis translation. |
| y | number | Yes | 0 | Y-axis translation. |
**Parameters**
- Example
| Name | Type | Mandatory | Default Value | Description |
| ---- | ------ | ---- | ---- | -------- |
| x | number | Yes | 0 | X-axis translation.|
| y | number | Yes | 0 | Y-axis translation.|
**Example**
```ts
// xxx.ets
// xxx.ets
@Entry
@Component
struct Translate {
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)
......@@ -1873,40 +2077,41 @@ Moves the origin of the coordinate system.
}
```
![en-us_image_0000001256978373](figures/en-us_image_0000001256978373.png)
![en-us_image_0000001238832413](figures/en-us_image_0000001238832413.png)
### drawImage
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
| 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. |
**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** 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
// xxx.ets
// xxx.ets
@Entry
@Component
struct Index {
struct DrawImage {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private img:ImageBitmap = new ImageBitmap("common/images/icon.jpg")
......@@ -1934,77 +2139,137 @@ Draws an image.
### createImageData
createImageData(width: number, height: number): Object
createImageData(sw: number, sh: number): ImageData
Creates an **ImageData** object based on the specified width and height. For details, see [ImageData](ts-components-canvas-imagebitmap.md).
Creates an **[ImageData](ts-components-canvas-imagedata.md)** object with the specified dimensions.
- Parameters
| Name | Type | Mandatory | Default Value | Description |
| ------ | ------ | --------- | ------------- | ----------------------------------- |
| width | number | Yes | 0 | Width of the **ImageData** object. |
| height | number | Yes | 0 | Height of the **ImageData** object. |
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ---- | ------ | ---- | ---- | ------------- |
| sw | number | Yes | 0 | Width of the **ImageData** object.|
| sh | number | Yes | 0 | Height of the **ImageData** object.|
### createImageData
createImageData(imageData: ImageData): Object
createImageData(imageData: ImageData): ImageData
Creates an **ImageData** object by copying an existing **ImageData** object. For details, see [ImageData](ts-components-canvas-imagebitmap.md).
Creates an **[ImageData](ts-components-canvas-imagedata.md)** object by copying an existing **ImageData** object.
- Parameters
| Name | Type | Mandatory | Default Value | Description |
| --------- | ---------------------------------------- | --------- | ------------- | ----------------------------- |
| imagedata | [ImageData](ts-components-canvas-imagebitmap.md) | Yes | null | **ImageData** object to copy. |
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| --------- | ---------------------------------------- | ---- | ---- | ---------------- |
| imagedata | [ImageData](ts-components-canvas-imagedata.md) | Yes | null | **ImageData** object to copy.|
**Return value**
| Type | Description |
| ---------------------------------------- | ------------- |
| [ImageData](ts-components-canvas-imagedata.md) | New **ImageData** object.|
### getPixelMap
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.
- Parameters
| Name | 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. |
| sw | number | Yes | 0 | Width of the output area. |
| sh | number | Yes | 0 | Height of the output area. |
**Parameters**
| Name | 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.|
| 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(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-imagedata.md)** object created with the pixels within the specified area on the canvas.
**Parameters**
Obtains the **[ImageData](ts-components-canvas-imagebitmap.md)** object created with the pixels within the specified area on the canvas.
| Name | 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.|
| sw | number | Yes | 0 | Width of the output area. |
| sh | number | Yes | 0 | Height of the output area. |
- Parameters
| Name | 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. |
| 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-imagedata.md) | New **ImageData** object.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct GetImageData {
private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings)
private img:ImageBitmap = new ImageBitmap("/common/images/1234.png")
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context)
.width('100%')
.height('100%')
.backgroundColor('#ffff00')
.onReady(() =>{
this.offContext.drawImage(this.img,0,0,130,130);
var imagedata = this.offContext.getImageData(50,50,130,130);
this.offContext.putImageData(imagedata,150,150);
var image = this.offContext.transferToImageBitmap()
this.context.transferFromImageBitmap(image)
})
}
.width('100%')
.height('100%')
}
}
```
![en-us_image_000000127777780](figures/en-us_image_000000127777780.png)
### 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
Puts the [ImageData](ts-components-canvas-imagebitmap.md) onto a rectangular area on the canvas.
putImageData(imageData: Object, dx: number, dy: number, dirtyX: number, dirtyY: number, dirtyWidth?: number, dirtyHeight: number): void
- Parameters
| Name | 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. |
| 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. |
| 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. |
| dirtyHeight | number | No | Height of the **ImageData** object | Height of the rectangular area to crop the source image. |
Puts an **[ImageData](ts-components-canvas-imagedata.md)** object onto a rectangular area on the canvas.
- Example
**Parameters**
| Name | 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. |
| 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.|
| 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. |
| dirtyHeight | number | No | Height of the **ImageData** object| Height of the rectangular area to crop the source image. |
**Example**
```ts
// xxx.ets
// xxx.ets
@Entry
@Component
struct PutImageData {
......@@ -2038,23 +2303,191 @@ Puts the [ImageData](ts-components-canvas-imagebitmap.md) onto a rectangular are
![en-us_image_0000001212058496](figures/en-us_image_0000001212058496.png)
### setLineDash
### restore
setLineDash(segments: number[]): void
restore(): void
Sets the dash line style.
Restores the saved drawing context.
**Parameters**
- Example
| Name | 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%')
}
}
```
![en-us_image_000000127777772](figures/en-us_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 OffscreenCanvasGetLineDash {
@State message: string = 'Hello World'
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings)
build() {
Row() {
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
.onClick(()=>{
console.error('before getlinedash clicked')
let res = this.offContext.getLineDash()
console.error(JSON.stringify(res))
})
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();
let res = this.offContext.getLineDash()
var image = this.offContext.transferToImageBitmap()
this.context.transferFromImageBitmap(image)
})
}
.width('100%')
}
.height('100%')
}
}
```
![en-us_image_000000127777778](figures/en-us_image_000000127777778.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%')
}
}
```
### imageSmoothingQuality
imageSmoothingQuality(quality: imageSmoothingQuality)
Sets the quality of image smoothing. This API is a void API.
**Parameters**
| Name | Type | Description |
| ------- | --------------------- | ---------------------------------------- |
| quality | imageSmoothingQuality | Quality of image smoothing. The value can be **'low'**, **'medium'**,or **'high'**.|
### transferToImageBitmap
transferToImageBitmap(): ImageBitmap
Creates an **ImageBitmap** object on the most recently rendered image of the **OffscreenCanvas**.
**Return value**
| Type | Description |
| ---------------------------------------- | --------------- |
| [ImageBitmap](ts-components-canvas-imagebitmap.md) | Pixel data rendered on the **OffscreenCanvas**.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct CanvasExample {
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)
......@@ -2062,7 +2495,14 @@ Restores the saved drawing context.
.height('100%')
.backgroundColor('#ffff00')
.onReady(() =>{
this.offContext.restore()
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)
})
......@@ -2072,6 +2512,47 @@ Restores the saved drawing context.
}
}
```
![en-us_image_0000001238952387](figures/en-us_image_0000001238952387.png)
### restore
restore(): void
Restores the saved drawing context.
**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.save(); // save the default state
this.offContext.fillStyle = "green";
this.offContext.fillRect(20, 20, 100, 100);
this.offContext.restore(); // restore to the default state
this.offContext.fillRect(150, 75, 100, 100);
var image = this.offContext.transferToImageBitmap()
this.context.transferFromImageBitmap(image)
})
}
.width('100%')
.height('100%')
}
}
```
![en-us_image_000000127777781](figures/en-us_image_000000127777781.png)
### save
......@@ -2080,16 +2561,17 @@ save(): void
Saves the current drawing context.
- Example
**Example**
```ts
// xxx.ets
@Entry
@Component
struct CanvasExample {
// 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)
......@@ -2097,7 +2579,11 @@ Saves the current drawing context.
.height('100%')
.backgroundColor('#ffff00')
.onReady(() =>{
this.offContext.save()
this.offContext.save(); // save the default state
this.offContext.fillStyle = "green";
this.offContext.fillRect(20, 20, 100, 100);
this.offContext.restore(); // restore to the default state
this.offContext.fillRect(150, 75, 100, 100);
var image = this.offContext.transferToImageBitmap()
this.context.transferFromImageBitmap(image)
})
......@@ -2105,8 +2591,9 @@ Saves the current drawing context.
.width('100%')
.height('100%')
}
}
}
```
![en-us_image_000000127777781](figures/en-us_image_000000127777781.png)
### createLinearGradient
......@@ -2115,18 +2602,19 @@ createLinearGradient(x0: number, y0: number, x1: number, y1: number): void
Creates a linear gradient.
- Parameters
| 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. |
| x1 | number | Yes | 0 | X-coordinate of the end point. |
| y1 | number | Yes | 0 | Y-coordinate of the end point. |
**Parameters**
| 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.|
| x1 | number | Yes | 0 | X-coordinate of the end point.|
| y1 | number | Yes | 0 | Y-coordinate of the end point.|
- Example
**Example**
```ts
// xxx.ets
// xxx.ets
@Entry
@Component
struct CreateLinearGradient {
......@@ -2166,20 +2654,21 @@ createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number,
Creates a linear gradient.
- Parameters
| 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. |
| r0 | number | Yes | 0 | Radius of the start circle, which must be a non-negative finite number. |
| x1 | number | Yes | 0 | X-coordinate of the center of the end circle. |
| 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. |
**Parameters**
| 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. |
| r0 | number | Yes | 0 | Radius of the start circle, which must be a non-negative finite number.|
| x1 | number | Yes | 0 | X-coordinate of the center of the end circle. |
| 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
// xxx.ets
// xxx.ets
@Entry
@Component
struct CreateRadialGradient {
......@@ -2215,4 +2704,4 @@ Creates a linear gradient.
## CanvasPattern
Defines an object created by using the [createPattern](#createpattern) method.
Defines an object created using the **[createPattern](#createpattern)** API.
# 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**
>
......@@ -10,18 +10,19 @@ Configure the component transition animations for when a component is inserted o
## Attributes
| Name| Type| Default Value| Description|
| -------- | -------- | -------- | -------- |
| transition | Object | - | All parameters are optional. For details, see **transition**.|
| Name| Type| Description|
| -------- | -------- | -------- |
| transition | Object | Transition parameters, which are all optional. For details, see **transition**. |
- transition
| Name| Type| Default Value| Mandatory| Description|
| -------- | -------- | -------- | -------- | -------- |
| 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 | 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.|
| 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.|
| Name | Type | 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. |
| 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** |
| 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> |
| 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
......
......@@ -3,29 +3,24 @@
Shared element transition can be used for transition between pages, for example, transition from an image on the current page to the next page.
> **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.
## Type
## 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 | Type | Default Value | Mandatory | Description |
| -------- | -------- | -------- | -------- | -------- |
| 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. |
| Name | Parameters | 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.|
## 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
// xxx.ets
@Entry
@Component
struct SharedTransitionExample {
......@@ -51,11 +46,12 @@ struct SharedTransitionExample {
}
```
```
// PageB
```ts
// PageB.ets
@Entry
@Component
struct BExample {
build() {
Stack() {
Image($r('app.media.ic_health_heart')).width(150).height(150).sharedTransition('sharedImage1')
......
......@@ -18,126 +18,119 @@ If a **Resource** object is created using `$r` or `$rawfile`, modifying attribut
**filename**: name of the file in **resources/rawfile** of the project.
| Name | Type | Readable| Writable| Description |
| ----------------------- | ------ | ---- | ---- | ---------- |
| id | number | Yes | No | Resource ID. |
| type | number | Yes | No | Resource type. |
| params | any[] | Yes | No | Optional resource parameters. |
| bundleName<sup>9+</sup> | string | Yes | No | Bundle name. |
| moduleName<sup>9+</sup> | string | Yes | No | Module name.|
## 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 | Size referenced from system or application resources. |
| [Resource](#resource) | Size referenced from system or application resources. |
## ResourceStr<sup>8+</sup>
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 | String referenced from system or application resources.|
| [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 | No | Height of the padding area on the top of the component. |
| right | Length | No | Width of the padding area on the right of the component.|
| bottom | Length | No | Height of the padding area at the bottom of the component. |
| left | Length | No | Width of the padding area on the left of the 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 | No | Height of the margin area above the component. |
| right | Length | No | Width of the margin area on the right of the component.|
| bottom | Length | No | Height of the margin area below the component. |
| left | Length | No | Width of the margin area on the left of the 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.|
## Offset
The **Offset** type is used to describe the offset coordinates of a component in the layout.
| Name | Type | Mandatory| Description |
| -------- | ------ | ---- |--------------------- |
| dx | Length | Yes | Horizontal offset. |
| dy | Length | Yes | Vertical offset. |
| Name | Type | Mandatory | Description |
| ---- | ------ | ---- | -------- |
| dx | [Length](#length) | Yes | Horizontal offset.|
| dy | [Length](#length) | Yes | Vertical offset.|
## ResourceColor<sup>8+</sup>
The **ResourceColor** type is used to describe the color types of resources.
| Type | Description |
| -------- | ----------------------- |
| [Color](../reference/arkui-ts/ts-appendix-enums.md#color) | Color enum. |
| ---------------------------------------- | ------------------------------------------------- |
| [Color](ts-appendix-enums.md#color) | Color enum. |
| number | Color in the hexadecimal notation. |
| string | Color in the RGB or RGBA notion. |
| Resource | Color referenced from system or application resources.|
| [Resource](#resource) | Color referenced from system or application resources.|
## Font
The **Font** type is used to set the text style.
| Name | Type | Mandatory| Description |
| ------ | ------------------------------ | ---- | ------------------------------------------------------------ |
| size | number | No | Font size. If the value is of the number type, the unit fp is used. |
| weight | number | 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 | [FontWeight](../reference/arkui-ts/ts-appendix-enums.md#fontweight) \| number \| string | 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 | string \| Resource | No | Font 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 | 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 | 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 | 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. |
| Name | Type | Mandatory | Description |
| -------------- | ---------------------- | ------------------------------ | ------------------------------ |
| width | [Length](#length) | Yes | 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) | Yes | 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) | Yes | Position of the upper left corner of the target element relative to that of the parent element. |
| globalPosition | [Position](#position8) | Yes | 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 | No | X coordinate. The value is of the number type when being used as the return value and the unit is vp. |
| y | Length | No | Y coordinate. The value is of the number type when used as the return value and the unit is vp. |
| 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 | No | Minimum width of the element. |
| maxWidth | Length | No | Maximum width of the element. |
| minHeight | Length | No | Minimum height of the element. |
| maxHeight | Length | No | Maximum height of the element. |
| --------- | ------ | ---- | ------- |
| 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 | No | Width of the element. |
| height | Length | No | Height of the element. |
| Name | Type | Mandatory | Description |
| ------ | ------ | ---- | ----- |
| width | [Length](#length) | No | Width of the element.|
| height | [Length](#length) | No | Height of the element.|
## BorderOptions
......@@ -145,10 +138,10 @@ The **SizeOptions** type is used to set the width and height.
The **BorderOptions** type is used to provide border information.
| Name | Type | Mandatory | Description |
| ------ | ----------------------- | ---- | ----------- |
| width | Length | No | Border width. |
| color | ResourceColor | No | Border color. |
| radius | Length | No | Border radius. |
| ------ | ---------------------------------------- | ---- | ------- |
| width | [Length](#length) | No | Border width. |
| color | [ResourceColor](#resourcecolor8) | No | Border color. |
| radius | [Length](#length) | No | Radius of the rounded corner border.|
| style | [BorderStyle](ts-appendix-enums.md#borderstyle) | No | Border style. |
## CustomBuilder<sup>8+</sup>
......@@ -156,5 +149,5 @@ The **BorderOptions** type is used to provide border information.
The **CustomBuilder** type is used to define custom UI descriptions in component attribute methods.
| Name | Type | Description |
| ------------- | ---------------------- | ------------------------------------------------------------ |
| CustomBuilder | ()&nbsp;=&gt;&nbsp;any | Builder of component attribute methods for defining custom UI descriptions. This type of method must be decorated by **@Builder**. For details, see [@Builder](../../ui/ts-component-based-builder.md).|
| ------------- | ---------------------- | ---------------------------------------- |
| CustomBuilder | ()&nbsp;=&gt;&nbsp;any | Must be decorated by **@Builder**. For details, see [@Builder](../../ui/ts-component-based-builder.md).|
......@@ -4,24 +4,16 @@ You can set the background of a component.
> **NOTE**
>
> This attribute is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
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
| Name | Type | Description |
| Name| Type| Description|
| -------- | -------- | -------- |
| backgroundColor | [ResourceColor](ts-types.md#resourcecolor) | Background color of a component. |
| backgroundImage | src:&nbsp;[ResourceStr](ts-types.md#resourcestr),<br/>repeat?:&nbsp;[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?:&nbsp;[Length](ts-types.md#length),<br/>height?:&nbsp;[Length](ts-types.md#length)<br/>}&nbsp;\|&nbsp;[ImageSize](ts-appendix-enums.md#imagesize) | 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.<br>Default value: **ImageSize.Auto** |
| backgroundImagePosition | {<br/>x?:&nbsp;[Length](ts-types.md#length),<br/>y?:&nbsp;[Length](ts-types.md#length)<br/>}&nbsp;\|&nbsp;[Alignment](ts-appendix-enums.md#alignment) | Position of the background image in the component. |
| backgroundColor | [ResourceColor](ts-types.md#resourcecolor) | Background color of the component. |
| backgroundImage | src: [ResourceStr](ts-types.md#resourcestr),<br>repeat?: [ImageRepeat](ts-appendix-enums.md#imagerepeat) | Background image of the component.<br>**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**|
| backgroundImagePosition | {<br/>x?: [Length](ts-types.md#length),<br/>y?: [Length](ts-types.md#length)<br/>} \| [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>}** |
## Example
......
# Border
The border attribute is used to set border styles for components.
The border attributes are used to set border styles for components.
> **NOTE**
>
......@@ -9,16 +9,13 @@ The border attribute is used to set border styles for components.
## Attributes
| Name | Type | Description |
| ------------ | ------------- | ------------------------ |
| border | {<br/>width?:&nbsp;[Length](ts-types.md#length),<br/>color?:&nbsp;[ResourceColor](ts-types.md#resourcecolor),<br/>radius?:&nbsp;[Length](ts-types.md#length),<br/>style?:&nbsp;[BorderStyle](ts-appendix-enums.md#borderstyle)<br/>}s | Unified border style. |
| ------------ | ------------------------------------------------------------ | ------------------------------------------------------------ |
| border | {<br>width?: [Length](ts-types.md#length),<br>color?: [ResourceColor](ts-types.md#resourcecolor),<br>radius?: [Length](ts-types.md#length),<br>style?: [BorderStyle](ts-appendix-enums.md#borderstyle)<br>} | Unified border style. |
| borderStyle | [BorderStyle](ts-appendix-enums.md#borderstyle) | Border style of an element.<br>Default value: **BorderStyle.Solid** |
| borderWidth | [Length](ts-types.md#length) | Border width of an element. |
| borderWidth | [Length](ts-types.md#length) | Border width. |
| borderColor | [ResourceColor](ts-types.md#resourcecolor) | Border color of an element. |
| borderRadius | [Length](ts-types.md#length) | Border radius of an element.|
| borderRadius | [Length](ts-types.md#length) | Border radius. |
## Example
......@@ -27,6 +24,7 @@ The border attribute is used to set border styles for components.
@Entry
@Component
struct BorderExample {
build() {
Flex({ justifyContent: FlexAlign.SpaceAround, alignItems: ItemAlign.Center }) {
// Dashed border
......
# Click Control
Click control attributes are used to set whether a component can respond to finger interactions such as click and touch events.
> ![icon-note.gif](public_sys-resources/icon-note.gif) **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
> **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.
## Attributes
| **Name** | **Type** | **Default Value** | **Description** |
| -------- | -------- | -------- | -------- |
| touchable | boolean | true | Whether the current component is touchable. |
| Name | Type| Description |
| ----------- | -------- | ------------------------ |
| touchable | boolean | Whether the component can respond to finger interactions such as click and touch events.<br>Default value: **true**|
## Example
```
```ts
// xxx.ets
@Entry
@Component
struct TouchAbleExample {
......@@ -48,5 +45,4 @@ struct TouchAbleExample {
}
```
![en-us_image_0000001257138351](figures/en-us_image_0000001257138351.gif)
# Enable/Disable
The **enabled** attribute sets whether a component responds to user interactions, such as [click events](ts-universal-events-click.md), [touch events](ts-universal-events-touch.md), [drag events](ts-universal-events-drag-drop.md), [key events](ts-universal-events-key.md), [focus events](ts-universal-focus-event.md), and [mouse events](ts-universal-mouse-key.md).
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> This attribute is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
None
> **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.
## Attributes
| Name | Type | Default Value | Description |
| -------- | -------- | -------- | -------- |
| enabled | boolean | true | The value **true** means that the component is available and can respond to operations such as clicking. The value **false** means that the component does not respond to operations such as clicking. |
| 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** |
## Example
```
```ts
// xxx.ets
@Entry
@Component
struct EnabledExample {
build() {
Flex({ justifyContent: FlexAlign.SpaceAround }) {
// No response upon a click.
// The component does not respond to clicks.
Button('disable').enabled(false).backgroundColor(0x317aff).opacity(0.4)
Button('enable').backgroundColor(0x317aff)
}
......
# Flex Layout
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> - This attribute 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.
>
> - This attribute is valid only when the parent component is a **Flex** component.
## Required Permissions
None
> - The flex layout is valid only when the parent component is a **\<Flex>**, **\<Column>**, or **\<Row>** component.
## Attributes
| Name | Type | Default Value | Description |
| -------- | -------- | -------- | -------- |
| flexBasis | 'auto' \| Length | 'auto' | Base dimension of a component in the main axis of the **Flex** layout. |
| flexGrow | number | 0 | Percentage of the **Flex** layout's remaining space that is allocated to the component. |
| flexShrink | number | 1 | Percentage of the **Flex** layout's shrink size that is allocated to the component. |
| alignSelf | [ItemAlign](ts-appendix-enums.md#itemalign-enums) | Auto | Alignment mode, which overwrites the default **alignItems** configuration in the **Flex** layout. |
| Name | Type | Description |
| ---------- | ---------------------------------------- | ---------------------------------------- |
| flexBasis | string \| number | 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)|
| flexGrow | number | Percentage of the parent container's remaining space that is allocated to the component.<br>Default value: **0** |
| flexShrink | number | Percentage of the parent container's shrink size that is allocated to the component.<br>Default value: **1** |
| alignSelf | [ItemAlign](ts-appendix-enums.md#itemalign) | he default **alignItems** configuration in the parent container.<br>Default value: **ItemAlign.Auto** |
## Example
```
```ts
// xxx.ets
@Entry
@Component
struct FlexExample {
build() {
Column({ space: 5 }) {
Text('flexBasis').fontSize(9).fontColor(0xCCCCCC).width('90%')
// Base dimension 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.
// Base size in the main axis
// The value of flexBasis() can be 'auto' or a number, which is equivalent to .width()/.height().
Flex() {
Text('flexBasis(100)')
.flexBasis('100').height(100).lineHeight(70)
.backgroundColor(0xF5DEB3).textAlign(TextAlign.Center)
.flexBasis('100')
.height(100)
.lineHeight(70)
.backgroundColor(0xF5DEB3)
.textAlign(TextAlign.Center)
Text('flexBasis("auto")')
.flexBasis('auto').width('60%').height(100).lineHeight(70)
.backgroundColor(0xD2B48C).textAlign(TextAlign.Center)
.flexBasis('auto')
.width('60%')
.height(100)
.lineHeight(70)
.backgroundColor(0xD2B48C)
.textAlign(TextAlign.Center)
}.width('90%').height(120).padding(10).backgroundColor(0xAFEEEE)
Text('flexGrow').fontSize(9).fontColor(0xCCCCCC).width('90%')
......@@ -49,11 +50,17 @@ struct FlexExample {
// flexGrow() specifies the percentage of the remaining space allocated to the component.
Flex() {
Text('flexGrow(2)')
.flexGrow(2).height(100).lineHeight(70)
.backgroundColor(0xF5DEB3).textAlign(TextAlign.Center)
.flexGrow(2)
.height(100)
.lineHeight(70)
.backgroundColor(0xF5DEB3)
.textAlign(TextAlign.Center)
Text('flexGrow(1)')
.flexGrow(1).height(100).lineHeight(70)
.backgroundColor(0xD2B48C).textAlign(TextAlign.Center)
.flexGrow(1)
.height(100)
.lineHeight(70)
.backgroundColor(0xD2B48C)
.textAlign(TextAlign.Center)
}.width('90%').height(120).padding(10).backgroundColor(0xAFEEEE)
Text('flexShrink').fontSize(9).fontColor(0xCCCCCC).width('90%')
......@@ -61,23 +68,39 @@ struct FlexExample {
// The ratio of text1 is 0, and the default values of other parameters are 1. If the components cannot be completely displayed, the last two components are shrunk proportionally. The first component is not shrunk.
Flex({ direction: FlexDirection.Row }) {
Text('flexShrink(0)')
.flexShrink(0).width('50%').height(100).lineHeight(70)
.backgroundColor(0xF5DEB3).textAlign(TextAlign.Center)
.flexShrink(0)
.width('50%')
.height(100)
.lineHeight(70)
.backgroundColor(0xF5DEB3)
.textAlign(TextAlign.Center)
Text('no flexShrink')
.width('40%').height(100).lineHeight(70).backgroundColor(0xD2B48C).textAlign(TextAlign.Center)
.width('40%')
.height(100)
.lineHeight(70)
.backgroundColor(0xD2B48C)
.textAlign(TextAlign.Center)
Text('flexShrink(2)')
.flexShrink(2).width('40%').height(100) .lineHeight(70)
.backgroundColor(0xF5DEB3).textAlign(TextAlign.Center)
.flexShrink(2)
.width('40%')
.height(100)
.lineHeight(70)
.backgroundColor(0xF5DEB3)
.textAlign(TextAlign.Center)
}.width('90%').height(120).padding(10).backgroundColor(0xAFEEEE)
Text('alignSelf').fontSize(9).fontColor(0xCCCCCC).width('90%')
// alignSelf() overwrites the default alignItems configuration in the Flex layout.
// alignSelf() overwrites the default alignItems configuration in the flex layout.
Flex({ direction: FlexDirection.Row, alignItems: ItemAlign.Center }) {
Text('no alignSelf,height:80').width('33%').height(80)
.backgroundColor(0xF5DEB3).textAlign(TextAlign.Center)
Text('alignSelf stretch')
.alignSelf(ItemAlign.Stretch).width('33%').height(80).lineHeight(70)
.backgroundColor(0xD2B48C).textAlign(TextAlign.Center)
.alignSelf(ItemAlign.Stretch)
.width('33%')
.height(80)
.lineHeight(70)
.backgroundColor(0xD2B48C)
.textAlign(TextAlign.Center)
Text('no alignSelf,height:100').width('34%').height(100)
.backgroundColor(0xF5DEB3).textAlign(TextAlign.Center)
}.width('90%').height(120).padding(10).backgroundColor(0xAFEEEE)
......
......@@ -7,19 +7,14 @@ Create a more gorgeous look for a component by applying a gradient color effect
> This attribute is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
None
## Attributes
| Name| Type| Default Value| Description|
| -------- | -------- | -------- | -------- |
| linearGradient | {<br/>angle?: number\|string,<br/>direction?: [GradientDirection](ts-appendix-enums.md#gradientdirection),<br/>colors: Array&lt;any&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;any&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.|
| radialGradient | {<br/>center: Point,<br/>radius: Length,<br/>colors: Array&lt;any&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.|
| 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?: 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: 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
......
......@@ -7,16 +7,11 @@ The hover effect is applied to a component in hover state.
> 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
| Name| Type| Default Value| Description|
| -------- | -------- | -------- | -------- |
| hoverEffect | [HoverEffect](ts-appendix-enums.md#hovereffect8) | HoverEffect.Auto | Hover effect of the component in hover state.|
| Name | Type | Description |
| ----------- | --------------------------------------------------| ------------------------------------------------ |
| hoverEffect | [HoverEffect](ts-appendix-enums.md#hovereffect8) | Hover effect of the component in hover state.<br>Default value: **HoverEffect.Auto**|
## Example
......
......@@ -4,31 +4,25 @@ Image effects include background blur, content blur, grayscale, and much more.
> **NOTE**
>
> This attribute is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
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
| 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. |
| 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. |
| 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. |
| 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. |
| 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. |
| 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. |
| colorBlend<sup>8+</sup> | Color | - | 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. |
| 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**.|
| 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.|
| 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.|
| 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.|
| colorBlend <sup>8+</sup> | Color | - | 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.|
| 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**. |
## Example
......@@ -39,6 +33,7 @@ You can preview how this component looks on a real device. The preview is not ye
@Entry
@Component
struct ImageEffectsExample {
build() {
Column({space: 10}) {
// Blur the font.
......@@ -78,4 +73,4 @@ struct ImageEffectsExample {
}
```
<img src="figures/image-effect.png" alt="image-effect" />
......@@ -7,21 +7,16 @@ The location attribute sets the alignment mode, layout direction, and position o
> 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
| Name| Type| Default Value| 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.|
| direction | [Direction](ts-appendix-enums.md#direction) | Auto | Horizontal layout of the component. For details about the options, see **Direction** enums.|
| 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.|
| 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.|
| 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.|
| Name| Type| Description|
| -------- | -------- | -------- |
| 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) | Horizontal layout of the component.<br>Default value: **Direction.Auto**|
| position | {<br/>x: [Length](ts-types.md#length),<br/>y: [Length](ts-types.md#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.|
| markAnchor | {<br/>x: [Length](ts-types.md#length),<br/>y: [Length](ts-types.md#length)<br/>} | 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](ts-types.md#length),<br/>y: [Length](ts-types.md#length)<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.<br>Default value:<br>**{<br>x: 0,<br>y: 1<br>}** |
## Example
......
......@@ -7,20 +7,16 @@ A menu – a vertical list of items – can be bound to a component and displaye
> 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
| Name | Type | Description |
| ---------------------------- | ---------------------------------------- | ---------------------------------- |
| ---------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| 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](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. |
| 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
| Name | Type | Description |
| ------ | ----------------------- | ----------- |
| value | string | Menu item text. |
......@@ -66,7 +62,7 @@ struct MenuExample {
```ts
// xxx.ets
import router from '@system.router';
import router from '@system.router'
@Entry
@Component
......
# Opacity
You can set the opacity of a component.
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> This attribute is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
The attributes described in this topic are used to set the opacity of a component.
## Required Permissions
None
> **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.
## Attributes
| Name | Type | Default Value | Description |
| -------- | -------- | -------- | -------- |
| opacity | number | 1 | Opacity of a component. The value ranges from **0** to **1**. The value **1** means opaque, and **0** means completely transparent. |
| Name | Type | Description |
| ------- | ---------------------------------------- | ---------------------------------------- |
| 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/>**NOTE**<br/>A child component can inherit this attribute of its parent component.<br>Default value: **1** |
## Example
```
```ts
// xxx.ets
@Entry
@Component
struct OpacityExample {
......
# Overlay
You can set overlay text for a component.
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> This attribute is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
None
> **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.
## Attributes
| Name | Type | Default Value | Description |
| -------- | -------- | -------- | -------- |
| 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. |
| Name | Type | Description |
| ------- | ----------------------------- | ------------------------- |
| overlay | value: string,<br/>options?: {<br/>align?: [Alignment](ts-appendix-enums.md#alignment), <br/>offset?: {x?: number, y?: number}<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>} |
## Example
```
```ts
// xxx.ets
@Entry
@Component
struct OverlayExample {
......
# 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.
> **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. |
- StateStyles<sup>8+</sup>
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| 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. |
| normal | any | No| Style of the component when being stateless.|
| pressed | any | No| Style of the component in the pressed state.|
| disabled | any | No| Style of the component in disabled state.|
| focused | any | No| Style of the component in focused state.|
| clicked | any | No| Style of the component in clicked state.|
## Example
```
```ts
// xxx.ets
@Entry
@Component
struct StyleExample {
......
# Shape Clipping
Shape clipping changes the visible portion of a component through clipping or masking.
> **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.
## Required Permissions
None
## Attributes
| Name | Type | Default Value | 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. |
| mask | Shape | - | Mask of the specified shape for the current component. |
| Name | Type | Description |
| -----| ------------------------------------------ | ------------------------------------ |
| 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 | [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
```ts
// xxx.ets
@Entry
......
# Size
The size attributes are used to set the width, height, padding, and margin of a component.
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> This attribute is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
None
> **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.
## Attributes
| Name | Type | Default Value | Description |
| -------- | -------- | -------- | -------- |
| width | Length | - | Width of a component. By default, the width required to fully hold the component content is used. |
| height | Length | - | Height of the component. By default, the height required to fully hold the component content is used. |
| size | {<br/>width?: Length,<br/>height?: Length<br/>} | - | Height and width 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. |
| 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. |
| 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. |
| layoutWeight | number | 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/>> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br/>> This attribute is valid only for the **Row**, **Column**, and **Flex** layouts. |
| Name | Type | Description |
| -------------- | ---------------------------------------- | ---------------------------------------- |
| width | [Length](ts-types.md#length) | Width of the component. By default, the width 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. |
| size | {<br>width?: [Length](ts-types.md#length),<br>height?: [Length](ts-types.md#length)<br>} | Size of the component. |
| 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** |
| 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** |
| 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 | 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>Default value: **0**<br/>**NOTE**<br/>This attribute is valid only for the **\<Row>**, **\<Column>**, and **\<Flex>** layouts. |
## Example
```
```ts
// xxx.ets
@Entry
@Component
struct SizeExample {
......@@ -45,7 +39,7 @@ struct SizeExample {
}.backgroundColor(0xFFA500)
Text('layoutWeight').fontSize(12).fontColor(0xCCCCCC).width('90%')
// When the container size is determined, the layout of the component and slibing components is allocated based on the weight along the main axis. The component size setting is ignored.
// 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.
Row() {
// Weight 1
Text('layoutWeight(1)')
......
# Text Style
The text style attribute is used to set the style for text in a component.
The text style attributes are 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.
## Required Permissions
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
| Name | Type | Default Value | Description |
| -------- | -------- | -------- | -------- |
| fontColor | Color | - | Text color. |
| fontSize | Length | - | Text 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. |
| fontWeight | number&nbsp;\|[FontWeight](ts-appendix-enums.md#fontweight) | 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. |
| fontFamily | string | - | 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**. |
| Name | Type | Description |
| -----------| ---------------------------------------- | ------------------------------------ |
| fontColor | Color | Font color. |
| fontSize | Length | Font size. If the value is of the number type, the unit fp is used. |
| fontStyle | [FontStyle](ts-appendix-enums.md#fontstyle) | Font style.<br>Default value: **FontStyle.Normal** |
| fontWeight | number \| [FontWeight](ts-appendix-enums.md#fontweight) | 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>Default value: **FontWeight.FontWeightNormal** |
| fontFamily | string | 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
......
# Touch Target
> ![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 the touch target for components that support universal click events, touch events, and gestures.
## Required Permissions
None
> **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 | Default Value | Description |
| -------- | -------- | -------- | -------- |
| responseRegion | Array&lt;Rectangle&gt; \| Rectangle | {<br/>x: 0,<br/>y: 0,<br/>width: '100%',<br/>height: '100%'<br/>} | One or more touch targets, including their location and size.<br/>> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br/>> The percentage is measured relative to the component itself.<br/>> <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 offset from the right edge of the component by the component's width. When **x** is set to **'-100%'**, the touch target is offset from the left edge of the component by the component's width. When **y** is set to **'100%'**, the touch target is offset from the bottom edge of the component by the component's height. When **y** is set to **'-100%'**, the touch target is offset from the top edge of the component by the component's height.<br/>> <br/>> **width** and **height** can only be set to positive percentage values. When **width** is set to **'100%'**, the width of the touch target is equal to that of the component; when **height** is set to **'100%'**, the height of the touch target is equal to that of the component. |
| 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>}** |
- Rectangle attributes
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| x | Length | No | 0vp | X coordinate of the touch point relative to the left edge of the component. |
| y | Length | No | 0vp | Y coordinate of the touch point relative to the left edge of the component. |
| width | Length | No | 100% | Width of the touch target. |
| height | Length | No | 100% | Height of the touch target. |
### Rectangle
| Name | Type | Mandatory | Description |
| ------ | ----------------------------- | -----| -------------------------------- |
| 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](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](ts-types.md#length) | No | Width of the touch target.<br>Default value: **100%**|
| height | [Length](ts-types.md#length) | No | Height of the touch target.<br>Default value: **100%**|
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> When both **x** and **y** are set to positive values, the entire touch target offsets towards the lower right corner of the component. How much the touch target offsets is subject to the set values.
> **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.
>
> **width** and **height** can only be set to positive percentage values. When **width** is set to **'100%'**, the width of the touch target is equal to that of the component; when **height** is set to **'100%'**, the height of the touch target is equal to that of the component.
>
> The percentage is measured relative to the component itself.
## Example
```
```ts
// xxx.ets
@Entry
@Component
struct ResponseRegionExample {
......
# Transformation
Transformation attributes allow you to rotate, translate, scale, or transform a component.
> **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.
## Required Permissions
None
## Attributes
| Name | Type | Description |
| --------- | ------------------------------------------------------------------------ | ---------------------------------------- |
| rotate | {<br/>x?: number,<br/>y?: number,<br/>z?: number,<br/>angle?: number \| string,<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?: 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?: 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. |
| Name | Type | Default Value | 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. |
| 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**. |
| 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. |
| transform | matrix: Matrix4 | - | Transformation matrix of the component. |
## Example
```ts
// xxx.ets
import Matrix4 from '@ohos.matrix4'
......
......@@ -4,20 +4,13 @@ The visibility attribute controls whether a component is visible.
> **NOTE**
>
> This attribute is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
None
> This event is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Attributes
| Name| Type| Default Value| Description|
| -------- | -------- | -------- | -------- |
| visibility | [Visibility](ts-appendix-enums.md#visibility) | Visibility.Visible | Whether the component is visible. |
| Name | Type | Description |
| ---------- | ---------------------------- | ------------------------------------------ |
| visibility | [Visibility](ts-appendix-enums.md#visibility) | Whether the component is visible.<br>Default value: **Visibility.Visible** |
## Example
......
# Component Area Change Event
The area change event is triggered when the component's size, position, or any other attribute that may affect its display area changes.
> **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
> 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 | Bubble 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. |
| Name | Bubbling Supported| Description |
| ---------------------------------------- | ---- | ---------------------------------------- |
| onAreaChange(event: (oldValue: [Area](ts-types.md#area8), newValue: [Area](ts-types.md#area8)) =&gt; void) | No | Triggered when the component area changes.|
## Example
```ts
// xxx.ets
@Entry
@Component
struct AreaExample {
@State value: string = 'Text'
@State size1: string = ''
@State sizeValue: string = ''
build() {
Column() {
......@@ -38,9 +33,9 @@ struct AreaExample {
})
.onAreaChange((oldValue: Area, newValue: Area) => {
console.info(`Ace: on area change, oldValue is ${JSON.stringify(oldValue)} value is ${JSON.stringify(newValue)}`)
this.size1 = JSON.stringify(newValue)
this.sizeValue = JSON.stringify(newValue)
})
Text('new area is: \n' + this.size).margin({ right: 30, left: 30 })
Text('new area is: \n' + this.sizeValue).margin({ right: 30, left: 30 })
}
.width('100%').height('100%').margin({ top: 30 })
}
......
# Drag/Drop Event
# Drag Event
A drag event is triggered when a component is dragged.
> **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 |
| -------- | -------- | -------- |
| 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. |
| 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. |
| 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. |
| 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. |
| 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**. |
| Name | Bubbling Supported| Description |
| ---------------------------------------- | ---- | ---------------------------------------- |
| 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(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(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(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(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 |
| --------- | ---------------------------------------- | ---- | --------------------------------- |
| 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.|
| extraInfo | string | No | Extra information of the dragged item. |
Returns 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**.
## extraParam
| 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. |
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 |
| -------- | -------- | -------- |
| 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. |
## DragEvent
| 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
......
......@@ -4,40 +4,28 @@ A key event is triggered when a component interacts with a keyboard, remote cont
> **NOTE**
>
> This event is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
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.
## Events
| Name | Bubbling Supported | Description |
| -------- | -------- | -------- |
| onKeyEvent(event: (event?: KeyEvent) =&gt; void) | Yes | Called when a key event occurs. For details about **event**, see [KeyEvent](#keyevent). |
| Name | Bubbling Supported| Description |
| ---------------------------------------- | ---- | ---------------------------------------- |
| onKeyEvent(event: (event?: KeyEvent) =&gt; void) | Yes | Triggered when a key event occurs. For details about **event**, see [KeyEvent](#keyevent).|
## KeyEvent
- Attributes
| Name | Type | Description |
| ------------------------------------- | --------------------------- | -------------------------- |
| type | [KeyType](ts-appendix-enums.md#keytype) | Type of a key. |
| [keyCode](../apis/js-apis-keycode.md) | number | Key code. |
| keyText | string | Key value. |
| 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. |
| 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. |
- APIs
| Name | Description |
| -------- | -------- |
| stopPropagation(): void | Stops the event from bubbling upwards or downwards. |
| Name | Type | Description |
| ------------------------------------- | ---------------------------------------- | -------------------------- |
| type | [KeyType](ts-appendix-enums.md#keytype) | Key type. |
| keyCode | number | number | Key code. |
| keyText | string | Key value. |
| 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. |
| 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. |
| stopPropagation | () => void | Stops the event from bubbling upwards or downwards. |
## Example
......
# 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.
> **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.
## Required Permissions
None
## Events
| Name | Bubble Supported | Description |
| -------- | -------- | -------- |
| onAppear(callback: () =&gt; void) | No | Called when the component is displayed. |
| onDisappear(callback: () =&gt; void) | No | Called when the component disappears. |
| Name | Bubbling Supported| Description |
| ------------------------------------------------ | -------- | -------------------------- |
| onAppear(event: () =&gt; void) | No | Triggered when the component is displayed.|
| onDisappear(event: () =&gt; void) | No | Triggered when the component disappears.|
## Example
```ts
// xxx.ets
import prompt from '@system.prompt'
......
......@@ -10,8 +10,8 @@ A touch event is triggered when a finger is pressed, slides, or is lifted from a
## Events
| Name | Bubbling Supported| Description |
| ---------------------------------------- | ---- | ---------------------------------------- |
| onTouch(event:&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
......@@ -22,7 +22,7 @@ A touch event is triggered when a finger is pressed, slides, or is lifted from a
| touches | Array&lt;[TouchObject](#touchobject)&gt; | All finger information. |
| changedTouches | Array&lt;[TouchObject](#touchobject)&gt; | Finger information changed.|
| stopPropagation | () => void | Stops the event from bubbling upwards or downwards.|
| timestamp<sup>8+</sup> | 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) | Display area of the element that triggers the gesture event.|
| source<sup>8+</sup> | [SourceType](ts-gesture-settings.md) | Event input device.|
......@@ -30,13 +30,13 @@ A touch event is triggered when a finger is pressed, slides, or is lifted from a
## TouchObject
| Name | Type | Description |
| ------- | --------------------------- | ------------------- |
| ------- | ------------------------------------------- | ------------------------------------- |
| type | [TouchType](ts-appendix-enums.md#touchtype) | Type of the touch event. |
| id | number | Unique identifier of a finger. |
| screenX | number | X-coordinate of the touch point relative to the left edge of the screen. |
| screenY | number | Y-coordinate of the touch point relative to the upper edge of the device screen. |
| x | number | X-coordinate of the touch point relative to the left edge of the element being touched.|
| y | number | Y-coordinate of the touch point relative to the upper edge of the element being touched.|
| screenX | number | X coordinate of the touch point relative to the upper left corner of the application window. |
| screenY | number | Y 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 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
......
# 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**
> 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**
>
> 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** | **Bubble Supported** | **Description** |
| -------- | -------- | -------- |
| onFocus(callback: () =&gt; void) | No | Triggered when the current component obtains focus. |
| onBlur(callback:() =&gt; void) | No | Triggered when the current component loses focus. |
| Name | Bubbling Supported| Description |
| ---------------------------------------- | -------- | --------------- |
| onFocus(event: () =&gt; void) | No | Triggered when the current component obtains focus.|
| onBlur(event:() =&gt; void) | No | Triggered when the current component loses focus.|
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> The following components support focus events: **&lt;Button&gt;**, **&lt;Text&gt;**, **&lt;Image&gt;**, **&lt;List&gt;**, and **&lt;Grid&gt;**.
> **NOTE**
>
> The following components support focus events: **\<Button>**, **\<Text>**, **\<Image>**, **\<List>**, and **\<Grid>**.
## Example
```
```ts
// xxx.ets
@Entry
@Component
struct FocusEventExample {
......
......@@ -4,37 +4,32 @@ If an action triggers multiple events, the order of these events is fixed. By de
> **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
> 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 |
| -------- | -------- | -------- |
| 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(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. |
| Name | Bubbling Supported| Description |
| ------------------------------------------------------------ | -------- | ------------------------------------------------------------ |
| 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(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
| Name | Type | Description |
| -------- | -------- | -------- |
| timestamp | number | Timestamp when the event is triggered. |
| screenX | number | X-coordinate of the clicked point relative to the upper left corner of the screen. |
| screenY | number | Y-coordinate of the clicked point relative to the upper left corner of the screen. |
| x | number | X-coordinate of the clicked point relative to the upper left corner of the component. |
| y | number | Y-coordinate of the clicked point relative to the upper left corner of the component. |
| --------- | ------------------------------- | -------------------- |
| screenX | number | X coordinate of the click point relative to the upper left corner of the application window.|
| screenY | number | Y coordinate of the click point relative to the upper left corner of the application window.|
| x | number | X coordinate of the click point relative to the upper left corner of the component being clicked.|
| y | number | Y coordinate of the click point relative to the upper left corner of the component being clicked.|
| button | [MouseButton](ts-appendix-enums.md#mousebutton) | Mouse button. |
| 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.|
| 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.|
| 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
```ts
......
# UI Development
- [ArkUI Overview](arkui-overview.md)
- TypeScript-based Declarative Development Paradigm
- UI Development with eTS-based Declarative Development Paradigm
- [Overview](ui-ts-overview.md)
- Framework Overview
- File Organization
......@@ -10,7 +10,7 @@
- ["js" Tag](ts-framework-js-tag.md)
- Resource Management
- [Resource File Categories](ui-ts-basic-resource-file-categories.md)
- [Accessing Resources](ts-resource-access.md)
- [Resource Access](ts-resource-access.md)
- [Pixel Units](ts-pixel-units.md)
- Declarative Syntax
- [Overview](ts-syntax-intro.md)
......@@ -73,7 +73,7 @@
- [Implementing Page Redirection and Data Transmission](ui-ts-page-redirection-data-transmission.md)
- [Recommendations for Improving Performance](ts-performance-improvement-recommendation.md)
- JavaScript-based Web-like Development Paradigm
- UI Development with JavaScript-compatible Web-like Development Paradig
- [Overview](ui-js-overview.md)
- Framework
- [File Organization](js-framework-file.md)
......@@ -99,14 +99,14 @@
- [Defining Gesture Events](ui-js-building-ui-event.md)
- [Defining Page Routes](ui-js-building-ui-routes.md)
- Common Component Development Guidelines
- Container Components
- Container Component Development
- [List Development](ui-js-components-list.md)
- [Dialog Development](ui-js-components-dialog.md)
- [Form Development](ui-js-components-form.md)
- [Stepper Development](ui-js-components-stepper.md)
- [Tabs Development](ui-js-component-tabs.md)
- [Swiper Development](ui-js-components-swiper.md)
- Basic Components
- Basic Component Development
- [Text Development](ui-js-components-text.md)
- [Input Development](ui-js-components-input.md)
- [Button Development](ui-js-components-button.md)
......@@ -127,8 +127,8 @@
- [CanvasRenderingContext2D](ui-js-components-canvasrenderingcontext2d.md)
- [Path2D](ui-js-components-path2d.md)
- [OffscreenCanvas](ui-js-components-offscreencanvas.md)
- [Grid-container Development](ui-js-components-grid.md)
- Svg
- [Grid Container Development](ui-js-components-grid.md)
- SVG Development
- [Basics](ui-js-components-svg-overview.md)
- [Graph Drawing](ui-js-components-svg-graphics.md)
- [Path Drawing](ui-js-components-svg-path.md)
......
......@@ -21,7 +21,7 @@ ArkUI is a UI development framework that provides what you'll need to develop ap
- Drawing: ArkUI offers advanced drawing capabilities that allow you to draw custom shapes with a range of editors, from images to fill colors and texts.
- Interaction: ArkUI allows users to interact with your application UI properly, regardless of the system platform and input device. By default, the UI accepts input from touch gestures, remote controls, and mouse devices, with support for the event notification capability.
- Platform API channel: ArkUI provides an API extension mechanism through which platform capabilities are encapsulated to produce JavaScript APIs in a unified style.
- Two development paradigms: ArkUI comes with two development paradigms: JavaScript-based web-like development paradigm (web-like development paradigm for short) and TypeScript-based declarative development paradigm (declarative development paradigm for short). You can choose whichever development paradigm that aligns with your practice.
- Two development paradigms: ArkUI comes with two development paradigms: eTS-based declarative development paradigm (declarative development paradigm for short) and JavaScript-compatible web-like development paradigm (web-like development paradigm for short). You can choose whichever development paradigm that aligns with your practice.
| Development Paradigm | Description | Applicable To | Intended Audience |
| -------- | -------- | -------- | -------- |
......
......@@ -4,18 +4,14 @@
The application code files can be accessed in the following ways:
- Use a relative path to reference the code file. For example, if the upper-level directory is ../common/utils/utils.ets, use ./common/utils/utils.ets for the current directory.
- Use the root path of the current module to reference the code file, for example, common/utils/utils.ets.
- Store common code files in the common directory.
- Use a relative path to reference the code file. Specifically, use **../** to refer to the upper-level directory and **./** to refer to the current directory.
- Use the root path of the current module to reference the code file, for example, **common/utils/utils**.
## Example
```
import { FoodData, FoodList } from "../common/utils/utils.ets";
import { FoodData, FoodList } from "../common/utils/utils";
@Entry
@Component
......@@ -33,10 +29,9 @@ struct FoodCategoryList {
}
```
Example for importing a code file:
Imported **utils.ets** file:
```
```ts
//common/utils/utils.ets
export class FoodData {
......
......@@ -8,11 +8,11 @@ The **&lt;tabs&gt;** component is a common UI component for navigation. It allow
Create a **&lt;tabs&gt;** component in the .hml file under **pages/index**.
```
<!-- index.hml -->
<div class="container" >
<tabs> <tab-bar>
<!-- xxx.hml -->
<div class="container">
<tabs>
<tab-bar>
<text>item1</text>
<text>item2</text>
</tab-bar>
......@@ -28,7 +28,6 @@ Create a **&lt;tabs&gt;** component in the .hml file under **pages/index**.
</div>
```
```
/* xxx.css */
.container {
......@@ -52,7 +51,6 @@ Create a **&lt;tabs&gt;** component in the .hml file under **pages/index**.
By default, the active tab of a **&lt;tabs&gt;** component is the one with the specified **index**. To show the **&lt;tabs&gt;** vertically, set the **vertical** attribute to **true**.
```
<!-- index.hml -->
<div class="container" style="background-color:#F1F3F5;">
......@@ -77,7 +75,6 @@ By default, the active tab of a **&lt;tabs&gt;** component is the one with the s
Set the **mode** attribute to enable the child components of the **&lt;tab-bar&gt;** to be evenly distributed. Set the **scrollable** attribute to disable scrolling of the **&lt;tab-content&gt;**.
```
<!-- index.hml -->
<div class="container" style="background-color:#F1F3F5;">
......@@ -103,7 +100,7 @@ Set the **mode** attribute to enable the child components of the **&lt;tab-bar&g
## Setting Styles
Set the background color, border, and tab-content layout of the **&lt;tabs&gt;** component.
Set the background color, border, and tab-content layout of the **&lt;tabs&gt;** component.
```
<!-- index.hml -->
......@@ -125,7 +122,6 @@ Set the **mode** attribute to enable the child components of the **&lt;tab-bar&g
</div>
```
```
/* xxx.css */
.container {
......@@ -161,7 +157,6 @@ Set the **mode** attribute to enable the child components of the **&lt;tab-bar&g
Add the **change** event for the **&lt;tabs&gt;** component to display the index of the current tab after tab switching.
```
<!-- index.hml -->
<div class="container" style="background-color:#F1F3F5;">
......@@ -182,7 +177,6 @@ Add the **change** event for the **&lt;tabs&gt;** component to display the index
</div>
```
```
/* index.js */
import prompt from '@system.prompt';
......@@ -198,7 +192,7 @@ export default {
![en-us_image_0000001222807772](figures/en-us_image_0000001222807772.gif)
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> **NOTE**
>
> A **&lt;tabs&gt;** can wrap at most one [**&lt;tab-bar&gt;**](../reference/arkui-js/js-components-container-tab-bar.md) and at most one [**&lt;tab-content&gt;**](../reference/arkui-js/js-components-container-tab-content.md).
......@@ -209,7 +203,6 @@ In this example, you can switch between tabs and the active tab has the title te
Use the **&lt;tabs&gt;**, **&lt;tab-bar&gt;**, and **&lt;tab-content&gt;** components to implement tab switching. Then define the arrays and attributes. Add the **change** event to change the attribute values in the arrays so that the active tab has a different font color and an underline.
```
<!-- index.hml -->
<div class="container">
......@@ -238,7 +231,6 @@ Use the **&lt;tabs&gt;**, **&lt;tab-bar&gt;**, and **&lt;tab-content&gt;** compo
</div>
```
```
/* xxx.css */
.container{
......@@ -275,7 +267,6 @@ background-color:#F1F3F5;
}
```
```
/* index.js */
import prompt from '@system.prompt';
......
# Overview
The web-like development paradigm uses the classical three-stage programming model, in which OpenHarmony Markup Language (HML) is used for building layouts, CSS for defining styles, and JavaScript for adding processing logic. UI components are associated with data through one-way data-binding. This means that when data changes, the UI automatically updates with the new data. This development paradigm has a low learning curve for frontend web developers, allowing them to quickly transform existing web applications into ArkUI applications. It could be helpful if you are developing small- and medium-sized applications with simple UIs.
The JavaScript-compatible web-like development paradigm uses the classical three-stage programming model, in which OpenHarmony Markup Language (HML) is used for building layouts, CSS for defining styles, and JavaScript for adding processing logic. UI components are associated with data through one-way data-binding. This means that when data changes, the UI automatically updates with the new data. This development paradigm has a low learning curve for frontend web developers, allowing them to quickly transform existing web applications into ArkUI applications. It could be helpful if you are developing small- and medium-sized applications with simple UIs.
For details about the components, see [Component Reference (JavaScript-based Web-like Development Paradigm)](../reference/arkui-js/js-components-common-attributes.md).
For details about the components, see [Component Reference (JavaScript-compatible Web-like Development Paradigm)](../reference/arkui-js/js-components-common-attributes.md).
## Overall Architecture
ArkUI with the JavaScript-based web-like development paradigm consists of the following layers: application layer, frontend framework layer, engine layer, and porting layer.
ArkUI with the JavaScript-compatible web-like development paradigm consists of the following layers: application layer, frontend framework layer, engine layer, and porting layer.
......
# Creating a Simple Page
In this section, we will develop an infographic food details page, by building custom components through the container components **\<Stack>** and **\<Flex>** as well as basic components **\<Image>** and **\<Text>**.
......@@ -24,11 +23,11 @@ In this section, we will develop an infographic food details page, by building c
}
```
![en-us_image_0000001222967780](figures/en-us_image_0000001222967780.png)
![en-us_image_0000001222967780](figures/en-us_image_0000001222967780.png)
2. Display food pictures.
Create an **\<Image>** component and specify a URL for it. The **\<Image>** and **\<Text>** components are mandatory. To display the **\<Text>** component above the **\<Image>** component, you need to declare the **\<Image>** component first. Image resources are stored in the **rawfile** folder in **resources**. When referencing the resources in the **rawfile** folder, use the `"$rawfile('filename')"` format, where **filename** indicates the relative path of the file in the **rawfile** folder. Currently, `$rawfile` only allows the **\<Image>** component to reference image resources.
Create an **\<Image>** component and specify a URL for it. To display the **\<Text>** component above the **\<Image>** component, declare the **\<Image>** component first. Image resources are stored in the **rawfile** folder in **resources**. When referencing the resources in the **rawfile** folder, use the `$rawfile('filename')` format, where **filename** indicates the relative path of the file in the **rawfile** folder. Currently,` $rawfile` only allows the **\<Image>** component to reference image resources.
```
@Entry
......@@ -45,17 +44,17 @@ In this section, we will develop an infographic food details page, by building c
}
```
![en-us_image_0000001267887861](figures/en-us_image_0000001267887861.png)
3. Access images through resources.
![en-us_image_0000001267887861](figures/en-us_image_0000001267887861.png)
In addition to specifying the image path, you can also use the media resource symbol `$r` to reference resources in the **resources** folder based on the resource qualifier rules. Right-click the **resources** folder, choose **New** &gt; **Resource Directory**, and set **Resource Type** to **Media (image resource)**.
3. Access images through resources.
Place **Tomato.png** in the **media** folder. You can then can reference the application resource in the `$r('app.type.name')` format, that is, `$r('app.media.Tomato')`.
In addition to specifying the image path, you can also use the media resource symbol **$r** to reference resources based on the resource qualifier rules in the **resources** folder. Right-click the **resources** folder, choose **New** > **Resource Directory** from the shortcut menu, and set **Resource Type** to **Media** (image resource).
Place **Tomato.png** in the **media** folder. You can then reference the application resources in the `$r('app.type.name')` format, which is `$r('app.media.Tomato')` in this example.
```
@Entry
```
@Entry
@Component
struct MyComponent {
build() {
......@@ -69,15 +68,18 @@ In this section, we will develop an infographic food details page, by building c
}
}
}
```
```
4. Set the width and height of the image, and set the **objectFit** attribute of the image to **ImageFit.Contain**, which means to keep the aspect ratio of the image to ensure that the image is completely displayed within the boundary. If the image fills the entire screen, the possible causes are as follows:
1. The width and height of the image are not set.
2. The default attribute of **objectFit** of the image is **ImageFit.Cover**, that is, the image is zoomed in or zoomed out to fill the entire display boundary with the aspect ratio locked.
4. Set the width and height of the image, and set the **objectFit** attribute of the image to **ImageFit.Contain**, which means to keep the aspect ratio of the image to ensure that the image is completely displayed within the boundary.
```
@Entry
If the image fills the entire screen, the possible causes are as follows:
- The width and height of the image are not set.
- The default attribute of **objectFit** of the image is **ImageFit.Cover**, that is, the image is zoomed in or zoomed out to fill the entire display boundary with the aspect ratio locked.
```
@Entry
@Component
struct MyComponent {
build() {
......@@ -91,14 +93,17 @@ In this section, we will develop an infographic food details page, by building c
}
}
}
```
```
![en-us_image_0000001223127732](figures/en-us_image_0000001223127732.png)
![en-us_image_0000001223127732](figures/en-us_image_0000001223127732.png)
5. Set the food image and name layout. Set **alignContent** to **Alignment.BottomStart**. Similar to **FontWeight**, **Alignment** is a built-in enumeration type provided by the framework.
5. Set the food image and name layout.
Set **alignContent** of the **\<Stack>** component to **Alignment.BottomStart**. Similar to **FontWeight**, **Alignment** is a built-in enumeration type provided by the framework.
```
@Entry
@Entry
@Component
struct MyComponent {
build() {
......@@ -114,15 +119,19 @@ In this section, we will develop an infographic food details page, by building c
}
```
![en-us_image_0000001267647873](figures/en-us_image_0000001267647873.png)
6. You can change the background color of the food image by setting the background color of the **\<Stack>** component in either of the following ways:
1. Using the built-in **Color** enums provided by the framework. For example, **backgroundColor(Color.Red)** indicates that the background color is set to red.
2. Using the string-type parameter. The supported color formats are rgb, rgba, and HEX. For example, you can set the background color to blue by setting **backgroundColor(??\#0000FF??)** and set the background color to white by setting **backgroundColor(??rgb(255, 255, 255)??)**.
6. You can change the background color of the food image by setting the background color of the **\<Stack>** component in any of the following ways:
1. Using a built-in enumeration value of **Color** provided by the framework. For example, **backgroundColor(Color.Red)** indicates that the background color is set to red.
2. Using a value of the string type. The supported color formats are rgb, rgba, and HEX. For example, you can set the background color to blue through **backgroundColor(??#0000FF??)** and set the background color to white through **backgroundColor(??rgb(255, 255, 255)??)**.
3. Using a value of the number type. Hexadecimal color values are supported. For example, **backgroundColor(0xFF0000)** indicates that the background color is red.
4. Using a value of the Resource type. For details about the Resource type, see [Resource Access](ts-resource-access.md).
```
@Entry
```
@Entry
@Component
struct MyComponent {
build() {
......@@ -136,18 +145,19 @@ In this section, we will develop an infographic food details page, by building c
}
.backgroundColor('#FFedf2f5')
}
}
```
}
```
![en-us_image_0000001222967772](figures/en-us_image_0000001222967772.png)
7. Adjust the left and bottom margin of the **\<Text>** component. **Margin** is a shorthand attribute. You can specify the margins of the four edges in a unified manner or separately. The configuration method is as follows:
1. To set the margins of the four edges in a unified manner, use the **Margin(Length)** format. For example, **margin(20)** indicates that the outer margins of the top, right, bottom, and left edges are all 20.
2. To set the margins of the four edges separately, use the **{top?: Length, right?: Length, bottom?: Length, left?:Length}** format. For example, **margin({ left: 26, bottom: 17.4 })** indicates that the left margin is 26 and the bottom margin is 17.4.
7. Adjust the left and bottom margin of the **\<Text>** component. Margin is a shorthand attribute. You can specify the margins of the four edges in a unified manner or separately.
- To set the margins of the four edges in a unified manner, use the **Margin(Length)** format. For example, **margin(20)** indicates that the margins of the top, right, bottom, and left edges are all 20.
- To set the margins of the four edges separately, use the **{top?: Length, right?: Length, bottom?: Length, left?:Length}** format. For example, **margin({ left: 26, bottom: 17.4 })** indicates that the left margin is 26 and the bottom margin is 17.4.
```
@Entry
```
@Entry
@Component
struct MyComponent {
build() {
......@@ -163,17 +173,17 @@ In this section, we will develop an infographic food details page, by building c
.backgroundColor('#FFedf2f5')
}
}
```
```
![en-us_image_0000001222967776](figures/en-us_image_0000001222967776.png)
8. Adjust the structure between components and semanticize component names. Create the **FoodDetail** page entry component, create a column in **FoodDetail**, and set the alignment to **alignItems(HorizontalAlign.Center)**. Change the name of the **MyComponent** component to **FoodImageDisplay**, which is a child component of the **FoodDetail** component.
![en-us_image_0000001222967776](figures/en-us_image_0000001222967776.png)
A column is a container component whose child components are vertically arranged. It is a linear layout in essence. Therefore, only the alignment in the cross axis direction can be set.
8. Adjust the structure between components and semanticize component names. Create the **FoodDetail** page entry component, create a **\<Column>** component in **FoodDetail**, and set the alignment to **alignItems(HorizontalAlign.Center)**. Change the name of the **MyComponent** component to **FoodImageDisplay**, which is a child component of the **FoodDetail** component.
The **\<Column>** component is a container whose child components are vertically arranged. It is in linear layout in essence. Therefore, only the alignment in the cross axis direction can be set.
```
@Component
```
@Component
struct FoodImageDisplay {
build() {
Stack({ alignContent: Alignment.BottomStart }) {
......@@ -199,17 +209,18 @@ In this section, we will develop an infographic food details page, by building c
.alignItems(HorizontalAlign.Center)
}
}
```
```
## Building the Flex Layout
You can use the Flex layout to build a food composition table. In this way you do not need to worry about the width and height calculation. The size of different cells can be flexibly set based on the proportion.
Use the **Flex** layout to build a food composition table. In this way, cell sizes are flexibly set based on the proportion, eliminating the need for width and height calculation.
1. Create a **ContentTable** component as a child component of the **FoodDetail** component.
```
@Component
```
@Component
struct FoodImageDisplay {
build() {
Stack({ alignContent: Alignment.BottomStart }) {
......@@ -241,19 +252,19 @@ You can use the Flex layout to build a food composition table. In this way you d
.alignItems(HorizontalAlign.Center)
}
}
```
```
2. Create a Flex component to display two food composition categories in the tomato: **Calories** and **Nutrition**.
2. Create a **\<Flex>** component to display two food composition categories in the tomato: **Calories** and **Nutrition**.
**Calories** contains information about calories. **Nutrition** contains information about protein, fat, carbohydrates, and vitamin C.
Create the **Calories** class. Create a Flex component and set its height to 280, and the top, right, and left margins to 30. The Flex component contains three **\<Text>** child components, which represent the category name (**Calories**), content name (**Calories**), and contain value (**17 kcal**), respectively. By default, child components in the Flex component are arranged horizontally.
Create the **Calories** class. Create a **\<Flex>** component and set its height to **280**, and the top, right, and left margins to **30**. The **Flex** component contains three **\<Text>** child components, which represent the category name (**Calories**), content name (**Calories**), and contain value (**17 kcal**), respectively. By default, child components in the **Flex** component are arranged horizontally.
In the following example, code of **FoodImageDisplay** is omitted, and only code of **ContentTable** is provided.
```
@Component
```
@Component
struct ContentTable {
build() {
Flex() {
......@@ -281,18 +292,19 @@ You can use the Flex layout to build a food composition table. In this way you d
.alignItems(HorizontalAlign.Center)
}
}
```
```
![en-us_image_0000001267767869](figures/en-us_image_0000001267767869.png)
3. Adjust the layout and set the proportion (**layoutWeight**) of each part. Set the proportion of the category name to **1**, and the total proportion of content name and content value to **2**. The content name and content value are in a same Flex, and the content name occupies all remaining space **flexGrow(1)**.
3. Adjust the layout and set the proportion (**layoutWeight**) of each part. Set **layoutWeight** of the category name to **1**, and **layoutWeight** of the content name and content value to **2**. The content name and content value are in a same **Flex**, and the content name occupies all remaining space **flexGrow(1)**.
```
@Component
```
@Component
struct FoodImageDisplay {
build() {
Stack({ alignContent: Alignment.BottomStart }) {
Image($r('app.media.Tomato'))
Image($m('Tomato.png'))
.objectFit(ImageFit.Contain)
.height(357)
Text('Tomato')
......@@ -337,7 +349,8 @@ You can use the Flex layout to build a food composition table. In this way you d
.alignItems(HorizontalAlign.Center)
}
}
```
```
![en-us_image_0000001267607901](figures/en-us_image_0000001267607901.png)
......@@ -345,9 +358,8 @@ You can use the Flex layout to build a food composition table. In this way you d
Set **FlexDirection.Column**, **FlexAlign.SpaceBetween**, and **ItemAlign.Start**.
```
@Component
```
@Component
struct ContentTable {
build() {
Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.SpaceBetween, alignItems: ItemAlign.Start }) {
......@@ -438,18 +450,18 @@ You can use the Flex layout to build a food composition table. In this way you d
.alignItems(HorizontalAlign.Center)
}
}
```
```
5. Use the custom constructor @Builder to simplify the code. It can be found that the food groups in each food composition table are actually of the same UI structure.
![en-us_image_0000001223287704](figures/en-us_image_0000001223287704.png)
5. Use the custom constructor **\@Builder** to simplify the code. It can be found that the food groups in each food composition table are actually of the same UI structure.
Currently, all food groups are declared, resulting in code duplication and redundancy. You can use @Builder to build a custom method and abstract the same UI structure declaration. The @Builder decorated method and the build method for the @Component decorated component are used to declare some UI rendering structures and comply with the same eTS syntax. You can define one or more methods decorated by @Builder, but a component decorated by @Component can have only one build method.
![en-us_image_0000001223287704](figures/en-us_image_0000001223287704.png)
Declare the **IngredientItem** method decorated by @Builder in **ContentTable** to declare the UI descriptions for the category name, content name, and content value.
Currently, all food groups are declared, resulting in code duplication and redundancy. You can use **\@Builder** to build a custom method and abstract the same UI structure declaration. The **\@Builder** decorated method and the **build** method for the **@Component** decorated component are used to declare some UI rendering structures and comply with the same ArkTS syntax. You can define one or more methods decorated by **\@Builder**, but a component decorated by **@Component** can have only one **build** method.
Declare the **IngredientItem** method decorated by **\@Builder** in **ContentTable** to declare the UI descriptions for the category name, content name, and content value.
```
```
@Component
struct ContentTable {
@Builder IngredientItem(title:string, name: string, value: string) {
......@@ -469,13 +481,13 @@ You can use the Flex layout to build a food composition table. In this way you d
}
}
}
```
```
When the `IngredientItem` API is called in the **build** method of **ContentTable**, `this` needs to be used to invoke the method in the scope of the component to distinguish the global method call.
When the **IngredientItem** API is called in the **build** method of **ContentTable**, **this** needs to be used to invoke the method in the scope of the component to distinguish the global method call.
```
@Component
```
@Component
struct ContentTable {
......
build() {
......@@ -490,13 +502,13 @@ You can use the Flex layout to build a food composition table. In this way you d
.padding({ top: 30, right: 30, left: 30 })
}
}
```
```
The overall code of the **ContentTable** component is as follows:
The overall code of the **ContentTable** component is as follows:
```
@Component
```
@Component
struct ContentTable {
@Builder IngredientItem(title:string, name: string, value: string) {
Flex() {
......@@ -526,6 +538,7 @@ You can use the Flex layout to build a food composition table. In this way you d
.height(280)
.padding({ top: 30, right: 30, left: 30 })
}
}
@Entry
......@@ -539,8 +552,9 @@ You can use the Flex layout to build a food composition table. In this way you d
.alignItems(HorizontalAlign.Center)
}
}
```
```
![en-us_image_0000001222807792](figures/en-us_image_0000001222807792.png)
![en-us_image_0000001222807792](figures/en-us_image_0000001222807792.png)
You've learned how to build a simple food details page. Read on to learn how to define the page layout and connection.
......@@ -34,13 +34,12 @@
- [Test Framework Usage](ability/ability-delegator.md)
- UI
- [ArkUI Overview](ui/arkui-overview.md)
- TypeScript-based Declarative Development Paradigm
- eTS-based Declarative Development Paradigm
- [Overview](ui/ui-ts-overview.md)
- Framework Overview
- File Organization
- [Directory Structure](ui/ts-framework-directory.md)
- [Rules for Accessing Application Code Files](ui/ts-framework-file-access-rules.md)
- ["js" Tag](ui/ts-framework-js-tag.md)
- Resource Access
- [Resource File Categories](ui/ui-ts-basic-resource-file-categories.md)
- [Accessing Application Resources](ui/ts-resource-access.md)
......@@ -103,7 +102,8 @@
- [Building a Food Category List Layout](ui/ui-ts-building-category-list-layout.md)
- [Building a Food Category Grid Layout](ui/ui-ts-building-category-grid-layout.md)
- [Implementing Page Redirection and Data Transmission](ui/ui-ts-page-redirection-data-transmission.md)
- JavaScript-based Web-Like Development Paradigm
- [Recommendations for Improving Performance](ui/ts-performance-improvement-recommendation.md)
- JavaScript-compatible Web-Like Development Paradigm
- [Overview](ui/ui-js-overview.md)
- Framework
- [File Organization](ui/js-framework-file.md)
......@@ -290,7 +290,7 @@
- [Samples](https://gitee.com/openharmony/applications_app_samples/blob/master/README.md)
- [Codelabs](https://gitee.com/openharmony/codelabs)
- API References
- Component Reference (TypeScript-based Declarative Development Paradigm)
- Component Reference (eTS-based Declarative Development Paradigm)
- Universal Components
- Universal Events
- [Click Event](reference/arkui-ts/ts-universal-events-click.md)
......@@ -436,7 +436,8 @@
- [Text Picker Dialog Box](reference/arkui-ts/ts-methods-textpicker-dialog.md)
- [Menu](reference/arkui-ts/ts-methods-menu.md)
- [Built-in Enums](reference/arkui-ts/ts-appendix-enums.md)
- Component Reference (JavaScript-based Web-like Development Paradigm)
- [Types](reference/arkui-ts/ts-types.md)
- Component Reference (JavaScript-compatible Web-like Development Paradigm)
- Common
- [Universal Attributes](reference/arkui-js/js-components-common-attributes.md)
- [Universal Styles](reference/arkui-js/js-components-common-styles.md)
......
......@@ -9,19 +9,19 @@ Data提供方可以自定义数据的增、删、改、查,以及文件打开
**表1** Data中相关生命周期API功能介绍
|接口名|描述|
|:------|:------|
|onInitialized?(info: AbilityInfo): void|在Ability初始化调用,通过此回调方法执行RDB等初始化操作。|
|update?(uri: string, valueBucket: rdb.ValuesBucket, predicates: dataAbility.DataAbilityPredicates, callback: AsyncCallback\<number>): void|更新数据库中的数据。|
|query?(uri: string, columns: Array\<string>, predicates: dataAbility.DataAbilityPredicates, callback: AsyncCallback\<ResultSet>): void|查询数据库中的数据。|
|delete?(uri: string, predicates: dataAbility.DataAbilityPredicates, callback: AsyncCallback\<number>): void|删除一条或多条数据。|
|normalizeUri?(uri: string, callback: AsyncCallback\<string>): void|对URI进行规范化。一个规范化的URI可以支持跨设备使用、持久化、备份和还原等,当上下文改变时仍然可以引用到相同的数据项。|
|batchInsert?(uri: string, valueBuckets: Array\<rdb.ValuesBucket>, callback: AsyncCallback\<number>): void|向数据库中插入多条数据。|
|denormalizeUri?(uri: string, callback: AsyncCallback\<string>): void|将一个由normalizeUri生产的规范化URI转换成非规范化的URI。|
|insert?(uri: string, valueBucket: rdb.ValuesBucket, callback: AsyncCallback\<number>): void|向数据中插入一条数据。|
|openFile?(uri: string, mode: string, callback: AsyncCallback\<number>): void|打开一个文件。|
|getFileTypes?(uri: string, mimeTypeFilter: string, callback: AsyncCallback<Array\<string>>): void|获取文件的MIME类型。|
|getType?(uri: string, callback: AsyncCallback\<string>): void|获取URI指定数据相匹配的MIME类型。|
|executeBatch?(ops: Array\<DataAbilityOperation>, callback: AsyncCallback\<Array\<DataAbilityResult>>): void|批量操作数据库中的数据。|
|call?(method: string, arg: string, extras: PacMap, callback: AsyncCallback\<PacMap>): void|自定义方法。|
|onInitialized(info: AbilityInfo): void|在Ability初始化调用,通过此回调方法执行RDB等初始化操作。|
|update(uri: string, valueBucket: rdb.ValuesBucket, predicates: dataAbility.DataAbilityPredicates, callback: AsyncCallback\<number>): void|更新数据库中的数据。|
|query(uri: string, columns: Array\<string>, predicates: dataAbility.DataAbilityPredicates, callback: AsyncCallback\<ResultSet>): void|查询数据库中的数据。|
|delete(uri: string, predicates: dataAbility.DataAbilityPredicates, callback: AsyncCallback\<number>): void|删除一条或多条数据。|
|normalizeUri(uri: string, callback: AsyncCallback\<string>): void|对URI进行规范化。一个规范化的URI可以支持跨设备使用、持久化、备份和还原等,当上下文改变时仍然可以引用到相同的数据项。|
|batchInsert(uri: string, valueBuckets: Array\<rdb.ValuesBucket>, callback: AsyncCallback\<number>): void|向数据库中插入多条数据。|
|denormalizeUri(uri: string, callback: AsyncCallback\<string>): void|将一个由normalizeUri生产的规范化URI转换成非规范化的URI。|
|insert(uri: string, valueBucket: rdb.ValuesBucket, callback: AsyncCallback\<number>): void|向数据中插入一条数据。|
|openFile(uri: string, mode: string, callback: AsyncCallback\<number>): void|打开一个文件。|
|getFileTypes(uri: string, mimeTypeFilter: string, callback: AsyncCallback<Array\<string>>): void|获取文件的MIME类型。|
|getType(uri: string, callback: AsyncCallback\<string>): void|获取URI指定数据相匹配的MIME类型。|
|executeBatch(ops: Array\<DataAbilityOperation>, callback: AsyncCallback\<Array\<DataAbilityResult>>): void|批量操作数据库中的数据。|
|call(method: string, arg: string, extras: PacMap, callback: AsyncCallback\<PacMap>): void|自定义方法。|
## 开发步骤
......@@ -32,6 +32,7 @@ Data提供方可以自定义数据的增、删、改、查,以及文件打开
创建Data的代码示例如下:
```javascript
import featureAbility from '@ohos.ability.featureAbility'
import dataAbility from '@ohos.data.dataAbility'
import dataRdb from '@ohos.data.rdb'
......@@ -43,7 +44,8 @@ Data提供方可以自定义数据的增、删、改、查,以及文件打开
export default {
onInitialized(abilityInfo) {
console.info('DataAbility onInitialized, abilityInfo:' + abilityInfo.bundleName)
dataRdb.getRdbStore(STORE_CONFIG, 1, (err, store) => {
let context = featureAbility.getContext()
dataRdb.getRdbStore(context, STORE_CONFIG, 1, (err, store) => {
console.info('DataAbility getRdbStore callback')
store.executeSql(SQL_CREATE_TABLE, [])
rdbStore = store
......
# Rating
评分条组件。
提供在给定范围内选择评分的组件。
> **说明:**
>
> 该组件从API Version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
## 权限列表
## 子组件
......@@ -23,24 +18,25 @@ Rating(options?: { rating: number, indicator?: boolean })
**参数:**
| 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 |
| --------- | ------- | ---- | ----- | -------------- |
| rating | number | 是 | 0 | 设置并接收评分值。 |
| indicator | boolean | 否 | false | 仅作为指示器使用,不可操作。 |
| 参数名 | 参数类型 | 必填 | 参数描述 |
| -------- | -------- | -------- | -------- |
| rating | number | 是 | 设置并接收评分值。<br/>默认值:0 |
| indicator | boolean | 否 | 设置评分组件作为指示器使用,不可改变评分。<br/>默认值:false, 可进行评分 |
## 属性
| 名称 | 参数类型 | 默认值 | 描述 |
| --------- | ---------------------------------------- | ---- | ---------------------------------------- |
| stars | number | 5 | 设置评星总数。 |
| stepSize | number | 0.5 | 操作评级的步长。 |
| starStyle | {<br/>backgroundUri:&nbsp;string,<br/>foregroundUri:&nbsp;string,<br/>secondaryUri?:&nbsp;string<br/>} | - | backgroundSrc:未选中的星级的图片链接,可由用户自定义或使用系统默认图片,仅支持本地。<br/>foregroundSrc:选中的星级的图片路径,可由用户自定义或使用系统默认图片,仅支持本地。<br/>secondarySrc:部分选中的星级的图片路径,可由用户自定义或使用系统默认图片,仅支持本地。 |
| 名称 | 参数类型 | 描述 |
| -------- | -------- | -------- |
| stars | number | 设置评星总数。<br/>默认值:5 |
| stepSize | number | 操作评级的步长。<br/>默认值:0.5 |
| starStyle | {<br/>backgroundUri:&nbsp;string,<br/>foregroundUri:&nbsp;string,<br/>secondaryUri?:&nbsp;string<br/>} | backgroundUri:未选中的星级的图片链接,可由用户自定义或使用系统默认图片,仅支持本地图片。<br/>foregroundUri:选中的星级的图片路径,可由用户自定义或使用系统默认图片,仅支持本地图片。<br/>secondaryUir:部分选中的星级的图片路径,可由用户自定义或使用系统默认图片,仅支持本地图片。 |
## 事件
| 名称 | 功能描述 |
| ---------------------------------------- | ------------------- |
| -------- | -------- |
| onChange(callback:(value:&nbsp;number)&nbsp;=&gt;&nbsp;void) | 操作评分条的评星发生改变时触发该回调。 |
......
......@@ -1421,7 +1421,7 @@ ellipse(x: number, y: number, radiusX: number, radiusY: number, rotation: number
| rotation | number | 是 | 0 | 椭圆的旋转角度,单位为弧度。 |
| startAngle | number | 是 | 0 | 椭圆绘制的起始点角度,以弧度表示。 |
| endAngle | number | 是 | 0 | 椭圆绘制的结束点角度,以弧度表示。 |
| counterclockwise | boolean | 否 | false | 是否以逆时针方向绘制椭圆。 |
| counterclockwise | boolean | 否 | false | 是否以逆时针方向绘制椭圆。<br>true:逆时针方向绘制椭圆。<br>false:顺时针方向绘制椭圆。 |
**示例:**
......
......@@ -383,7 +383,7 @@ arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void
## ellipse
ellipse(x: number, y: number, radiusX: number, radiusY: number, rotation: number, startAngle: number, endAngle: number, counterclockwise?: number): void
ellipse(x: number, y: number, radiusX: number, radiusY: number, rotation: number, startAngle: number, endAngle: number, counterclockwise?: boolean): void
在规定的矩形区域绘制一个椭圆。
......@@ -398,7 +398,7 @@ ellipse(x: number, y: number, radiusX: number, radiusY: number, rotation: number
| rotation | number | 是 | 0 | 椭圆的旋转角度,单位为弧度。 |
| startAngle | number | 是 | 0 | 椭圆绘制的起始点角度,以弧度表示。 |
| endAngle | number | 是 | 0 | 椭圆绘制的结束点角度,以弧度表示。 |
| counterclockwise | number | 否 | 0 | 是否以逆时针方向绘制椭圆,0为顺时针,1为逆时针。(可选参数,默认为0) |
| counterclockwise | boolean | 否 | false | 是否以逆时针方向绘制椭圆。<br>true:逆时针方向绘制椭圆。<br>false:顺时针方向绘制椭圆。 |
**示例:**
......
......@@ -46,12 +46,13 @@
| Left | 圆点显示在左侧纵向居中。 |
## BadgeStyle对象说明
| 名称 | 类型 | 必填 | 默认值 | 描述 |
| -------- | -------- | -------- | -------- | -------- |
| ---------- | ------------------------------------------ | ---- | ----------- | ------------------------------------------- |
| color | [ResourceColor](ts-types.md#resourcecolor) | 否 | Color.White | 文本颜色。 |
| fontSize | number&nbsp;\|&nbsp;string | 否 | 10 | 文本大小。 |
| badgeSize | number&nbsp;\|&nbsp;string | 是 | - | badge的大小。 |
| badgeColor | [ResourceColor](ts-types.md#resourcecolor) | 否 | Color.Red | badge的颜色。 |
| fontSize | number&nbsp;\|&nbsp;string | 否 | 10 | 文本大小,单位vp。 |
| badgeSize | number&nbsp;\|&nbsp;string | 否 | 16 | Badge的大小,单位vp。不支持百分比形式设置。 |
| badgeColor | [ResourceColor](ts-types.md#resourcecolor) | 否 | Color.Red | Badge的颜色。 |
## 示例
......
......@@ -22,8 +22,8 @@ GridContainer(value?: { columns?: number | auto, sizeType?: SizeType, gutter?: s
| -------- | ------------------------ | ---- | -------------------------------------------- |
| columns | number&nbsp;\|&nbsp;auto | 否 | 设置当前布局总列数。<br/>默认值:auto |
| sizeType | SizeType | 否 | 选用设备宽度类型。<br/>默认值:SizeType.Auto |
| gutter | Length | 否 | 栅格布局列间距 |
| margin | Length | 否 | 栅格布局两侧间距 |
| gutter | Length | 否 | 栅格布局列间距,不支持百分比。 |
| margin | Length | 否 | 栅格布局两侧间距,不支持百分比。 |
## SizeType枚举说明
......
......@@ -25,7 +25,7 @@ Scroll(scroller?: Scroller)
| 名称 | 参数类型 | 描述 |
| -------------- | ---------------------------------------- | --------- |
| scrollable | [ScrollDirection](#scrolldirection枚举说明) | 设置滚动方向。<br/>默认值:ScrollDirection.Vertical |
| scrollBar | [BarState](ts-appendix-enums.md#barstate) | 设置滚动条状态。<br/>默认值:BarState.Off |
| scrollBar | [BarState](ts-appendix-enums.md#barstate) | 设置滚动条状态。<br/>默认值:BarState.Auto |
| scrollBarColor | string&nbsp;\|&nbsp;number&nbsp;\|&nbsp;[Color](ts-appendix-enums.md#color) | 设置滚动条的颜色。 |
| scrollBarWidth | string&nbsp;\|&nbsp;number | 设置滚动条的宽度。 |
| edgeEffect | [EdgeEffect](ts-appendix-enums.md#edgeeffect) | 设置滑动效果,目前支持的滑动效果参见EdgeEffect的枚举说明。<br/>默认值:EdgeEffect.None |
......
......@@ -137,3 +137,48 @@ struct LineExample1 {
```
![zh-cn_image1_0000001219982725](figures/zh-cn_image1_0000001219982725.png)
### 示例3
```ts
// xxx.ets
@Entry
@Component
struct LineExample {
build() {
Column() {
Line()
.startPoint([50, 30])
.endPoint([300, 30])
.strokeWidth(10)
// 设置strokeDashArray的数组间隔为 50
Line()
.startPoint([50, 20])
.endPoint([300, 20])
.strokeWidth(10)
.strokeDashArray([50])
// 设置strokeDashArray的数组间隔为 50, 10
Line()
.startPoint([50, 20])
.endPoint([300, 20])
.strokeWidth(10)
.strokeDashArray([50, 10])
// 设置strokeDashArray的数组间隔为 50, 10, 20
Line()
.startPoint([50, 20])
.endPoint([300, 20])
.strokeWidth(10)
.strokeDashArray([50, 10, 20])
// 设置strokeDashArray的数组间隔为 50, 10, 20, 30
Line()
.startPoint([50, 20])
.endPoint([300, 20])
.strokeWidth(10)
.strokeDashArray([50, 10, 20, 30])
}
}
}
```
![zh-cn_image2_0000001219982725](figures/zh-cn_image2_0000001219982725.PNG)
\ No newline at end of file
......@@ -181,7 +181,7 @@ struct VideoCreateComponent {
console.error('onFinish');
})
.onError(() => {
console.error('onFinish');
console.error('onError');
})
.onPrepared((e) => {
console.error('onPrepared is ' + e.duration);
......
......@@ -1508,7 +1508,7 @@ ellipse(x: number, y: number, radiusX: number, radiusY: number, rotation: number
| rotation | number | 是 | 0 | 椭圆的旋转角度,单位为弧度。 |
| startAngle | number | 是 | 0 | 椭圆绘制的起始点角度,以弧度表示。 |
| endAngle | number | 是 | 0 | 椭圆绘制的结束点角度,以弧度表示。 |
| counterclockwise | boolean | 否 | false | 是否以逆时针方向绘制椭圆。 |
| counterclockwise | boolean | 否 | false | 是否以逆时针方向绘制椭圆。<br>true:逆时针方向绘制椭圆。<br>false:顺时针方向绘制椭圆。 |
**示例:**
......
......@@ -19,3 +19,38 @@
**关键的接口/组件变更**
### 状态变量多种数据类型声明使用限制。
状态变量比如@State、@Provide、 @Link和@Consume等,定义数据类型时,只能同时由简单数据类型或对象引用数据类型其中一种构成。
示例:
```ts
@Entry
@Component
struct Index {
//错误写法: @State message: string | Resource = 'Hello World'
@State message: string = 'Hello World'
build() {
Row() {
Column() {
Text(`${ this.message }`)
.fontSize(50)
.fontWeight(FontWeight.Bold)
}
.width('100%')
}
.height('100%')
}
}
```
**变更影响**
当定义的状态变量类型中同时包含简单类型和对象引用数据类型时,编译报错提示不支持。
**关键的接口/组件变更**
当定义的状态变量类型中同时包含简单类型和对象引用数据类型时,需修改为只含有其中一种,如上述示例代码所示。
\ No newline at end of file
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册