提交 8b2ee890 编写于 作者: L LiAn 提交者: Gitee

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

Signed-off-by: NLiAn <lian15@huawei.com>
...@@ -15,6 +15,7 @@ ...@@ -15,6 +15,7 @@
- Development Fundamentals - Development Fundamentals
- [Application Package Structure Configuration File (FA Model)](quick-start/package-structure.md) - [Application Package Structure Configuration File (FA Model)](quick-start/package-structure.md)
- [Application Package Structure Configuration File (Stage Model)](quick-start/stage-structure.md) - [Application Package Structure Configuration File (Stage Model)](quick-start/stage-structure.md)
- [Resource File Categories](quick-start/basic-resource-file-categories.md)
- [SysCap](quick-start/syscap.md) - [SysCap](quick-start/syscap.md)
- Development - Development
- [Ability Development](ability/Readme-EN.md) - [Ability Development](ability/Readme-EN.md)
...@@ -42,6 +43,9 @@ ...@@ -42,6 +43,9 @@
- [Component Reference (TypeScript-based Declarative Development Paradigm)](reference/arkui-ts/Readme-EN.md) - [Component Reference (TypeScript-based Declarative Development Paradigm)](reference/arkui-ts/Readme-EN.md)
- [Component Reference (JavaScript-based Web-like Development Paradigm)](reference/arkui-js/Readme-EN.md) - [Component Reference (JavaScript-based Web-like Development Paradigm)](reference/arkui-js/Readme-EN.md)
- APIs - APIs
- [JS and TS APIs](reference/apis/Readme-EN.md) - [JS and TS APIs](reference/apis/Readme-EN.md)
- Native APIs
- [Standard Libraries](reference/native-lib/third_party_libc/musl.md)
- [Node_API](reference/native-lib/third_party_napi/napi.md)
- Contribution - Contribution
- [How to Contribute](../contribute/documentation-contribution.md) - [How to Contribute](../contribute/documentation-contribution.md)
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
## When to Use ## When to Use
A relational database (RDB) store allows you to operate local data with or without native SQL statements based on SQLite. A relational database (RDB) store allows you to manage local data with or without native SQL statements based on SQLite.
## Available APIs ## Available APIs
...@@ -21,11 +21,11 @@ The table below describes the APIs available for creating and deleting an RDB st ...@@ -21,11 +21,11 @@ The table below describes the APIs available for creating and deleting an RDB st
### Managing Data in an RDB Store ### Managing Data in an RDB Store
The RDB provides APIs for inserting, deleting, updating, and querying data in the local RDB store. The **RDB** module provides APIs for inserting, deleting, updating, and querying data in a local RDB store.
- **Inserting Data** - **Inserting Data**
The RDB provides APIs for inserting data through a **ValuesBucket** in a data table. If the data is inserted, the row ID of the data inserted will be returned; otherwise, **-1** will be returned. The **RDB** module provides APIs for inserting data through a **ValuesBucket** in a data table. If the data is inserted, the row ID of the data inserted will be returned; otherwise, **-1** will be returned.
**Table 2** API for inserting data **Table 2** API for inserting data
...@@ -41,7 +41,7 @@ The RDB provides APIs for inserting, deleting, updating, and querying data in th ...@@ -41,7 +41,7 @@ The RDB provides APIs for inserting, deleting, updating, and querying data in th
| Class| API| Description| | Class| API| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| RdbStore | update(values:ValuesBucket,rdbPredicates:RdbPredicates):Promise\<number> | Updates data based on the specified **RdbPredicates** object. This API uses a promise to return the result.<br>Return value: number of rows updated.<br>- **values**: data to update, which is stored in **ValuesBucket**.<br>- **rdbPredicates**: conditions for updating data. | | RdbStore | update(values:ValuesBucket,rdbPredicates:RdbPredicates):Promise\<number> | Updates data based on the specified **RdbPredicates** object. This API uses a promise to return the result.<br>Return value: number of rows updated.<br>- **values**: data to update, which is stored in **ValuesBucket**.<br>- **rdbPredicates**: conditions for updating data.|
- **Deleting Data** - **Deleting Data**
...@@ -51,7 +51,7 @@ The RDB provides APIs for inserting, deleting, updating, and querying data in th ...@@ -51,7 +51,7 @@ The RDB provides APIs for inserting, deleting, updating, and querying data in th
| Class| API| Description| | Class| API| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| RdbStore | delete(rdbPredicates:RdbPredicates):Promise\<number> | Deletes data from the RDB store based on the specified **RdbPredicates** object. This API uses a promise to return the result.<br>Return value: number of rows updated.<br>- **rdbPredicates**: conditions for deleting data. | | RdbStore | delete(rdbPredicates:RdbPredicates):Promise\<number> | Deletes data from the RDB store based on the specified **RdbPredicates** object. This API uses a promise to return the result.<br>Return value: number of rows updated.<br>- **rdbPredicates**: conditions for deleting data.|
- **Querying data** - **Querying data**
...@@ -69,19 +69,19 @@ The RDB provides APIs for inserting, deleting, updating, and querying data in th ...@@ -69,19 +69,19 @@ The RDB provides APIs for inserting, deleting, updating, and querying data in th
### Using Predicates ### Using Predicates
The RDB provides **RdbPredicates** for you to set database operation conditions. The **RDB** module provides **RdbPredicates** for you to set database operation conditions.
The following lists common predicates. For more information about predicates, see [**RdbPredicates**](../reference/apis/js-apis-data-rdb.md#rdbpredicates). The table below lists common predicates. For more information about predicates, see [**RdbPredicates**](../reference/apis/js-apis-data-rdb.md#rdbpredicates).
**Table 6** APIs for using RDB store predicates **Table 6** APIs for using RDB store predicates
| Class| API| Description| | Class| API| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| RdbPredicates | equalTo(field:string,value:ValueType):RdbPredicates | Sets an **RdbPredicates** to match the field with data type **ValueType** and value equal to the specified value.<br>- **field**: column name in the database table.<br>- **value**: value to match the **RdbPredicates**.<br>- **RdbPredicates**: **RdbPredicates** object that matches the specified field. | | RdbPredicates | equalTo(field:string,value:ValueType):RdbPredicates | Sets an **RdbPredicates** object to match the field with data type **ValueType** and value equal to the specified value.<br>- **field**: column name in the database table.<br>- **value**: value to match the **RdbPredicates**.<br>- **RdbPredicates**: **RdbPredicates** object created.|
| RdbPredicates | notEqualTo(field:string,value:ValueType):RdbPredicates | Sets an **RdbPredicates** to match the field with data type **ValueType** and value not equal to the specified value.<br>- **field**: column name in the database table.<br>- **value**: value to match the **RdbPredicates**.<br>- **RdbPredicates**: **RdbPredicates** object that matches the specified field. | | RdbPredicates | notEqualTo(field:string,value:ValueType):RdbPredicates | Sets an **RdbPredicates** object to match the field with data type **ValueType** and value not equal to the specified value.<br>- **field**: column name in the database table.<br>- **value**: value to match the **RdbPredicates**.<br>- **RdbPredicates**: **RdbPredicates** object created.|
| RdbPredicates | or():RdbPredicates | Adds the OR condition to the **RdbPredicates**.<br>- **RdbPredicates**: **RdbPredicates** with the OR condition.| | RdbPredicates | or():RdbPredicates | Adds the OR condition to the **RdbPredicates** object.<br>- **RdbPredicates**: **RdbPredicates** with the OR condition.|
| RdbPredicates | and():RdbPredicates | Adds the AND condition to the **RdbPredicates**.<br>- **RdbPredicates**: **RdbPredicates** with the AND condition.| | RdbPredicates | and():RdbPredicates | Adds the AND condition to the **RdbPredicates** object.<br>- **RdbPredicates**: **RdbPredicates** with the AND condition.|
| RdbPredicates | contains(field:string,value:string):RdbPredicats | Sets an **RdbPredicates** to match a string that contains the specified value.<br>- **field**: column name in the database table.<br>- **value**: value to match the **RdbPredicates**.<br>- **RdbPredicates**: **RdbPredicates** object that matches the specified field. | | RdbPredicates | contains(field:string,value:string):RdbPredicats | Sets an **RdbPredicates** object to match a string that contains the specified value.<br>- **field**: column name in the database table.<br>- **value**: value to match the **RdbPredicates**.<br>- **RdbPredicates**: **RdbPredicates** object created.|
### Using the Result Set ### Using the Result Set
......
...@@ -2,6 +2,7 @@ ...@@ -2,6 +2,7 @@
- [Using Native APIs in Application Projects](napi-guidelines.md) - [Using Native APIs in Application Projects](napi-guidelines.md)
- [Drawing Development](drawing-guidelines.md) - [Drawing Development](drawing-guidelines.md)
- [Native Window Development](native_window-guidelines.md)
- [Raw File Development](rawfile-guidelines.md) - [Raw File Development](rawfile-guidelines.md)
- [Native Window Development](native-window-guidelines.md)
# Timer # Timer
The **Timer** module provides basic timer capabilities. You can use the APIs of this module to execute functions at the specified time.
> **NOTE**
>
> The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## setTimeout ## setTimeout
...@@ -7,6 +12,8 @@ setTimeout(handler[,delay[,…args]]): number ...@@ -7,6 +12,8 @@ setTimeout(handler[,delay[,…args]]): number
Sets a timer for the system to call a function after the timer goes off. Sets a timer for the system to call a function after the timer goes off.
**System capability**: SystemCapability.ArkUI.ArkUI.Full
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
...@@ -23,15 +30,15 @@ Sets a timer for the system to call a function after the timer goes off. ...@@ -23,15 +30,15 @@ Sets a timer for the system to call a function after the timer goes off.
**Example** **Example**
```js ```js
export default { export default {
setTimeOut() { setTimeOut() {
var timeoutID = setTimeout(function() { var timeoutID = setTimeout(function() {
console.log('delay 1s'); console.log('delay 1s');
}, 1000); }, 1000);
}
} }
} ```
```
## clearTimeout ## clearTimeout
...@@ -40,6 +47,8 @@ clearTimeout(timeoutID: number): void ...@@ -40,6 +47,8 @@ clearTimeout(timeoutID: number): void
Cancels the timer created via **setTimeout()**. Cancels the timer created via **setTimeout()**.
**System capability**: SystemCapability.ArkUI.ArkUI.Full
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
...@@ -48,16 +57,16 @@ Cancels the timer created via **setTimeout()**. ...@@ -48,16 +57,16 @@ Cancels the timer created via **setTimeout()**.
**Example** **Example**
```js ```js
export default { export default {
clearTimeOut() { clearTimeOut() {
var timeoutID = setTimeout(function() { var timeoutID = setTimeout(function() {
console.log('do after 1s delay.'); console.log('do after 1s delay.');
}, 1000); }, 1000);
clearTimeout(timeoutID); clearTimeout(timeoutID);
}
} }
} ```
```
## setInterval ## setInterval
...@@ -66,6 +75,8 @@ setInterval(handler[, delay[, ...args]]): number ...@@ -66,6 +75,8 @@ setInterval(handler[, delay[, ...args]]): number
Sets a repeating timer for the system to repeatedly call a function at a fixed interval. Sets a repeating timer for the system to repeatedly call a function at a fixed interval.
**System capability**: SystemCapability.ArkUI.ArkUI.Full
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
...@@ -82,15 +93,15 @@ Sets a repeating timer for the system to repeatedly call a function at a fixed i ...@@ -82,15 +93,15 @@ Sets a repeating timer for the system to repeatedly call a function at a fixed i
**Example** **Example**
```js ```js
export default { export default {
setInterval() { setInterval() {
var intervalID = setInterval(function() { var intervalID = setInterval(function() {
console.log('do very 1s.'); console.log('do very 1s.');
}, 1000); }, 1000);
}
} }
} ```
```
## clearInterval ## clearInterval
...@@ -99,6 +110,8 @@ clearInterval(intervalID: number): void ...@@ -99,6 +110,8 @@ clearInterval(intervalID: number): void
Cancels the repeating timer set via **setInterval()**. Cancels the repeating timer set via **setInterval()**.
**System capability**: SystemCapability.ArkUI.ArkUI.Full
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
...@@ -107,13 +120,13 @@ Cancels the repeating timer set via **setInterval()**. ...@@ -107,13 +120,13 @@ Cancels the repeating timer set via **setInterval()**.
**Example** **Example**
```js ```js
export default { export default {
clearInterval() { clearInterval() {
var intervalID = setInterval(function() { var intervalID = setInterval(function() {
console.log('do very 1s.'); console.log('do very 1s.');
}, 1000); }, 1000);
clearInterval(intervalID); clearInterval(intervalID);
}
} }
} ```
```
\ No newline at end of file
...@@ -10,7 +10,6 @@ This module provides the following common window-related functions: ...@@ -10,7 +10,6 @@ This module provides the following common window-related functions:
> >
> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import ## Modules to Import
```js ```js
...@@ -35,10 +34,10 @@ Enumerates the types of the area where the window cannot be displayed. ...@@ -35,10 +34,10 @@ Enumerates the types of the area where the window cannot be displayed.
**System capability**: SystemCapability.WindowManager.WindowManager.Core **System capability**: SystemCapability.WindowManager.WindowManager.Core
| Name | Value | Description | | Name | Value | Description |
| ----------- | ---- | ------------------ | |----------------------------------|-----| ----------------- |
| TYPE_SYSTEM | 0 | Default area of the system.| | TYPE_SYSTEM | 0 | Default area of the system.|
| TYPE_CUTOUT | 1 | Notch. | | TYPE_CUTOUT | 1 | Notch. |
## WindowMode<sup>7+</sup> ## WindowMode<sup>7+</sup>
...@@ -64,11 +63,11 @@ Describes the properties of the status bar and navigation bar. ...@@ -64,11 +63,11 @@ Describes the properties of the status bar and navigation bar.
| Name | Type| Readable| Writable| Description | | Name | Type| Readable| Writable| Description |
| -------------------------------------- | -------- | ---- | ---- | ------------------------------------------------------------ | | -------------------------------------- | -------- | ---- | ---- | ------------------------------------------------------------ |
| statusBarColor | string | Yes | Yes | Background color of the status bar. The value is a hexadecimal RGB or aRGB color value and is case insensitive, for example, `#00FF00` or `#FF00FF00`.| | statusBarColor | string | No | Yes | Background color of the status bar. The value is a hexadecimal RGB or aRGB color value and is case insensitive, for example, `#00FF00` or `#FF00FF00`.|
| isStatusBarLightIcon<sup>7+</sup> | boolean | No | Yes | Whether any icon on the status bar is highlighted. | | isStatusBarLightIcon<sup>7+</sup> | boolean | No | Yes | Whether any icon on the status bar is highlighted. |
| statusBarContentColor<sup>8+</sup> | string | No | Yes | Color of the text on the status bar. | | statusBarContentColor<sup>8+</sup> | string | No | Yes | Color of the text on the status bar. |
| navigationBarColor | string | Yes | Yes | Background color of the navigation bar. The value is a hexadecimal RGB or aRGB color value and is case insensitive, for example, `#00FF00` or `#FF00FF00`.| | navigationBarColor | string | No | Yes | Background color of the navigation bar. The value is a hexadecimal RGB or aRGB color value and is case insensitive, for example, `#00FF00` or `#FF00FF00`.|
| isNavigationBarLightIcon<sup>7+</sup> | boolean | No | No | Whether any icon on the navigation bar is highlighted. | | isNavigationBarLightIcon<sup>7+</sup> | boolean | No | Yes | Whether any icon on the navigation bar is highlighted. |
| navigationBarContentColor<sup>8+</sup> | string | No | Yes | Color of the text on the navigation bar. | | navigationBarContentColor<sup>8+</sup> | string | No | Yes | Color of the text on the navigation bar. |
## SystemBarRegionTint<sup>8+</sup> ## SystemBarRegionTint<sup>8+</sup>
...@@ -81,11 +80,11 @@ Describes the callback for a single system bar. ...@@ -81,11 +80,11 @@ Describes the callback for a single system bar.
| Name | Type | Readable| Writable| Description | | Name | Type | Readable| Writable| Description |
| --------------- | ------------------------- | ---- | ---- | ------------------------------------------------------------ | | --------------- | ------------------------- | ---- | ---- | ------------------------------------------------------------ |
| type | [WindowType](#windowtype) | Yes | Yes | Type of the system bar whose properties are changed. Only the status bar and navigation bar are supported.| | type | [WindowType](#windowtype) | Yes | No | Type of the system bar whose properties are changed. Only the status bar and navigation bar are supported.|
| isEnable | boolean | Yes | Yes | Whether the system bar is displayed. | | isEnable | boolean | Yes | No | Whether the system bar is displayed. |
| region | [Rect](#rect) | Yes | Yes | Current position and size of the system bar. | | region | [Rect](#rect) | Yes | No | Current position and size of the system bar. |
| backgroundColor | string | Yes | Yes | Background color of the system bar. The value is a hexadecimal RGB or aRGB color value and is case insensitive, for example, `#00FF00` or `#FF00FF00`.| | backgroundColor | string | Yes | No | Background color of the system bar. The value is a hexadecimal RGB or aRGB color value and is case insensitive, for example, `#00FF00` or `#FF00FF00`.|
| contentColor | string | Yes | Yes | Color of the text on the system bar. | | contentColor | string | Yes | No | Color of the text on the system bar. |
## SystemBarTintState<sup>8+</sup> ## SystemBarTintState<sup>8+</sup>
...@@ -98,7 +97,7 @@ Describes the callback for the current system bar. ...@@ -98,7 +97,7 @@ Describes the callback for the current system bar.
| Name | Type | Readable| Writable| Description | | Name | Type | Readable| Writable| Description |
| ---------- | --------------------------------------------------- | ---- | ---- | ---------------------------- | | ---------- | --------------------------------------------------- | ---- | ---- | ---------------------------- |
| displayId | number | Yes | No | ID of the current physical screen. | | displayId | number | Yes | No | ID of the current physical screen. |
| regionTint | Array<[SystemBarRegionTint](#systembarregiontint8)> | Yes | Yes | All system bar information that has been changed.| | regionTint | Array<[SystemBarRegionTint](#systembarregiontint8)> | Yes | No | All system bar information that has been changed.|
## Rect<sup>7+</sup> ## Rect<sup>7+</sup>
...@@ -126,6 +125,7 @@ Describes the area where the window cannot be displayed. ...@@ -126,6 +125,7 @@ Describes the area where the window cannot be displayed.
| rightRect | [Rect](#rect) | Yes | Yes | Rectangle on the right of the screen.| | rightRect | [Rect](#rect) | Yes | Yes | Rectangle on the right of the screen.|
| bottomRect | [Rect](#rect) | Yes | Yes | Rectangle at the bottom of the screen.| | bottomRect | [Rect](#rect) | Yes | Yes | Rectangle at the bottom of the screen.|
## Size<sup>7+</sup> ## Size<sup>7+</sup>
Describes the window size. Describes the window size.
...@@ -143,20 +143,20 @@ Describes the window properties. ...@@ -143,20 +143,20 @@ Describes the window properties.
**System capability**: SystemCapability.WindowManager.WindowManager.Core **System capability**: SystemCapability.WindowManager.WindowManager.Core
| Name | Type | Readable| Writable| Description | | Name | Type | Readable| Writable| Description |
| ------------------------------- | ------------------------- | ---- | ---- | -------------------------------------------- | | ------------------------------------- | ------------------------- | ---- | ---- | ------------------------------------------------------------ |
| windowRect<sup>7+</sup> | [Rect](#rect) | Yes | Yes | Window size. | | windowRect<sup>7+</sup> | [Rect](#rect) | Yes | Yes | Window size. |
| type<sup>7+</sup> | [WindowType](#windowtype) | Yes | Yes | Window type. | | type<sup>7+</sup> | [WindowType](#windowtype) | Yes | Yes | Window type. |
| isFullScreen | boolean | Yes | Yes | Whether the window is displayed in full screen mode. The default value is `false`. | | isFullScreen | boolean | Yes | Yes | Whether the window is displayed in full screen mode. The default value is `false`. |
| isLayoutFullScreen<sup>7+</sup> | boolean | Yes | Yes | Whether the window layout is in full-screen mode (whether the window is immersive). The default value is `false`. | | isLayoutFullScreen<sup>7+</sup> | boolean | Yes | Yes | Whether the window layout is in full-screen mode (whether the window is immersive). The default value is `false`. |
| focusable<sup>7+</sup> | boolean | Yes | No | Whether the window can gain focus. The default value is `true`. | | focusable<sup>7+</sup> | boolean | Yes | No | Whether the window can gain focus. The default value is `true`. |
| touchable<sup>7+</sup> | boolean | Yes | No | Whether the window is touchable. The default value is `true`. | | touchable<sup>7+</sup> | boolean | Yes | No | Whether the window is touchable. The default value is `true`. |
| brightness | number | Yes | Yes | Screen brightness. The value ranges from 0 to 1. The value `1` indicates the maximum brightness. | | brightness | number | Yes | Yes | Screen brightness. The value ranges from 0 to 1. The value `1` indicates the maximum brightness. |
| dimBehindValue<sup>7+</sup> | number | Yes | Yes | Dimness of the window that is not on top. The value ranges from 0 to 1. The value `1` indicates the maximum dimness.| | dimBehindValue<sup>7+</sup> | number | Yes | Yes | Dimness of the window that is not on top. The value ranges from 0 to 1. The value `1` indicates the maximum dimness. |
| isKeepScreenOn | boolean | Yes | Yes | Whether the screen is always on. The default value is `false`. | | isKeepScreenOn | boolean | Yes | Yes | Whether the screen is always on. The default value is `false`. |
| isPrivacyMode<sup>7+</sup> | boolean | Yes | Yes | Whether the window is in privacy mode. The default value is `false`. | | isPrivacyMode<sup>7+</sup> | boolean | Yes | Yes | Whether the window is in privacy mode. The default value is `false`. |
| isRoundCorner<sup>7+</sup> | boolean | Yes | Yes | Whether the window has rounded corners. The default value is `false`. | | isRoundCorner<sup>7+</sup> | boolean | Yes | Yes | Whether the window has rounded corners. The default value is `false`. |
| isTransparent<sup>7+</sup> | boolean | Yes | Yes | Whether the window is transparent. The default value is `false`. | | isTransparent<sup>7+</sup> | boolean | Yes | Yes | Whether the window is transparent. The default value is `false`. |
## ColorSpace<sup>8+</sup> ## ColorSpace<sup>8+</sup>
...@@ -245,7 +245,7 @@ Creates a subwindow. This API uses an asynchronous callback to return the result ...@@ -245,7 +245,7 @@ Creates a subwindow. This API uses an asynchronous callback to return the result
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | -------------------------------------- | ---- | ------------------------------------------------------------ | | -------- | -------------------------------------- | ---- | ------------------------------------------------------------ |
| ctx | [Context](js-apis-Context.md) | Yes | Current application context.| | ctx | [Context](js-apis-Context.md) | Yes | Current application context.|
| id | string | Yes | Window ID. | | id | string | Yes | Window ID. |
| type | [WindowType](#windowtype) | Yes | Window type. | | type | [WindowType](#windowtype) | Yes | Window type. |
| callback | AsyncCallback&lt;[Window](#window)&gt; | Yes | Callback used to return the subwindow created. | | callback | AsyncCallback&lt;[Window](#window)&gt; | Yes | Callback used to return the subwindow created. |
...@@ -430,7 +430,7 @@ Obtains the top window of the current application. This API uses an asynchronous ...@@ -430,7 +430,7 @@ Obtains the top window of the current application. This API uses an asynchronous
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | -------------------------------------- | ---- | ------------------------------------------------------------ | | -------- | -------------------------------------- | ---- | ------------------------------------------------------------ |
| ctx | [Context](js-apis-Context.md) | Yes | Current application context. | | ctx | [Context](js-apis-Context.md) | Yes | Current application context.|
| callback | AsyncCallback&lt;[Window](#window)&gt; | Yes | Callback used to return the top window obtained. | | callback | AsyncCallback&lt;[Window](#window)&gt; | Yes | Callback used to return the top window obtained. |
**Example** **Example**
...@@ -937,8 +937,8 @@ Obtains the area where this window cannot be displayed, for example, the system ...@@ -937,8 +937,8 @@ Obtains the area where this window cannot be displayed, for example, the system
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | | -------- |-----------------------------------------------| ---- | ------------------------------------------------------------ |
| type | [AvoidAreaType](#avoidareatype) | Yes | Type of the area. `TYPE_SYSTEM` indicates the default area of the system. `TYPE_CUTOUT` indicates the notch.| | type | [AvoidAreaType](#avoidareatype) | Yes | Type of the area. `TYPE_SYSTEM` indicates the default area of the system. `TYPE_CUTOUT` indicates the notch.|
| callback | AsyncCallback&lt;[AvoidArea](#avoidarea)&gt; | Yes | Callback used to return the area. | | callback | AsyncCallback&lt;[AvoidArea](#avoidarea)&gt; | Yes | Callback used to return the area. |
...@@ -965,20 +965,21 @@ Obtains the area where this window cannot be displayed, for example, the system ...@@ -965,20 +965,21 @@ Obtains the area where this window cannot be displayed, for example, the system
**Parameters** **Parameters**
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ------------------------------- | ---- | ------------------------------------------------------------ | | ------ |----------------------------------| ---- | ------------------------------------------------------------ |
| type | [AvoidAreaType](#avoidareatype) | Yes | Type of the area. `TYPE_SYSTEM` indicates the default area of the system. `TYPE_CUTOUT` indicates the notch.| | type | [AvoidAreaType](#avoidareatype) | Yes | Type of the area. `TYPE_SYSTEM` indicates the default area of the system. `TYPE_CUTOUT` indicates the notch.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| -------------------------------------- | ----------------------------------- | |-----------------------------------------| ----------------------------------- |
| Promise&lt;[AvoidArea](#avoidarea)&gt; | Promise used to return the area.| | Promise&lt;[AvoidArea](#avoidarea)&gt; | Promise used to return the area.|
**Example** **Example**
```js ```js
let promise = windowClass.getAvoidArea(); var type = window.AvoidAreaType.TYPE_SYSTEM;
let promise = windowClass.getAvoidArea(type);
promise.then((data)=> { promise.then((data)=> {
console.info('Succeeded in obtaining the area. Data:' + JSON.stringify(data)); console.info('Succeeded in obtaining the area. Data:' + JSON.stringify(data));
}).catch((err)=>{ }).catch((err)=>{
...@@ -1315,7 +1316,7 @@ Checks whether this window is displayed. This API uses an asynchronous callback ...@@ -1315,7 +1316,7 @@ Checks whether this window is displayed. This API uses an asynchronous callback
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ---------------------------- | ---- | ------------------------------------------------------------ | | -------- | ---------------------------- | ---- | ------------------------------------------------------------ |
| callback | AsyncCallback&lt;boolean&gt; | Yes | Callback used to return the result. The value `true` means that this window is displayed, and `false` means the opposite.| | callback | AsyncCallback&lt;boolean&gt; | Yes | Callback used to return the result. The value `true` means that the window is displayed, and `false` means the opposite.|
**Example** **Example**
...@@ -1341,7 +1342,7 @@ Checks whether this window is displayed. This API uses a promise to return the r ...@@ -1341,7 +1342,7 @@ Checks whether this window is displayed. This API uses a promise to return the r
| Type | Description | | Type | Description |
| ---------------------- | ------------------------------------------------------------ | | ---------------------- | ------------------------------------------------------------ |
| Promise&lt;boolean&gt; | Promise used to return the result. The value `true` means that this window is displayed, and `false` means the opposite.| | Promise&lt;boolean&gt; | Promise used to return the result. The value `true` means that the window is displayed, and `false` means the opposite.|
**Example** **Example**
...@@ -1408,9 +1409,9 @@ Enables listening for changes to the area where the window cannot be displayed. ...@@ -1408,9 +1409,9 @@ Enables listening for changes to the area where the window cannot be displayed.
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ------------------------------------------------------------ | | -------- |------------------------------------------| ---- | ------------------------------------------------------- |
| type | string | Yes | Event type. The value is fixed at `systemAvoidAreaChange`, indicating the event of changes to the area where the window cannot be displayed.| | type | string | Yes | Event type. The value is fixed at `systemAvoidAreaChange`, indicating the event of changes to the area where the window cannot be displayed.|
| callback | Callback&lt;[AvoidArea](#avoidarea)&gt; | Yes | Callback used to return the area. | | callback | Callback&lt;[AvoidArea](#avoidarea)&gt; | Yes | Callback used to return the area. |
**Example** **Example**
...@@ -1431,10 +1432,10 @@ Disables listening for changes to the area where the window cannot be displayed. ...@@ -1431,10 +1432,10 @@ Disables listening for changes to the area where the window cannot be displayed.
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ------------------------------------------------------------ | | -------- |------------------------------------------| ---- | ------------------------------------------------------- |
| type | string | Yes | Event type. The value is fixed at `systemAvoidAreaChange`, indicating the event of changes to the area where the window cannot be displayed.| | type | string | Yes | Event type. The value is fixed at `systemAvoidAreaChange`, indicating the event of changes to the area where the window cannot be displayed.|
| callback | Callback&lt;[AvoidArea](#avoidarea)&gt; | No | Callback used to return the area. | | callback | Callback&lt;[AvoidArea](#avoidarea)&gt; | No | Callback used to return the area. |
**Example** **Example**
...@@ -1658,7 +1659,7 @@ Sets the background color for this window. This API uses an asynchronous callbac ...@@ -1658,7 +1659,7 @@ Sets the background color for this window. This API uses an asynchronous callbac
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------- | ---- | ------------------------------------------------------------ | | -------- | ------------------------- | ---- | ------------------------------------------------------------ |
| color | string | Yes | Background color to set. The value is a hexadecimal color value and is case insensitive, for example, `#00FF00` or `#FF00FF00`.| | color | string | Yes | Background color to set. The value is a hexadecimal color code and is case insensitive, for example, `#00FF00` or `#FF00FF00`.|
| callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result. | | callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result. |
**Example** **Example**
...@@ -1686,7 +1687,7 @@ Sets the background color for this window. This API uses a promise to return the ...@@ -1686,7 +1687,7 @@ Sets the background color for this window. This API uses a promise to return the
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------------------------------------------------------------ | | ------ | ------ | ---- | ------------------------------------------------------------ |
| color | string | Yes | Background color to set. The value is a hexadecimal color value and is case insensitive, for example, `#00FF00` or `#FF00FF00`.| | color | string | Yes | Background color to set. The value is a hexadecimal color code and is case insensitive, for example, `#00FF00` or `#FF00FF00`.|
**Return value** **Return value**
...@@ -1772,8 +1773,9 @@ setDimBehind(dimBehindValue: number, callback: AsyncCallback&lt;void&gt;): void ...@@ -1772,8 +1773,9 @@ setDimBehind(dimBehindValue: number, callback: AsyncCallback&lt;void&gt;): void
Sets the dimness of the window that is not on top. This API uses an asynchronous callback to return the result. Sets the dimness of the window that is not on top. This API uses an asynchronous callback to return the result.
> **NOTE**: This API cannot be used. > **NOTE**
>
> This API cannot be used.
**System capability**: SystemCapability.WindowManager.WindowManager.Core **System capability**: SystemCapability.WindowManager.WindowManager.Core
...@@ -1802,8 +1804,9 @@ setDimBehind(dimBehindValue: number): Promise&lt;void&gt; ...@@ -1802,8 +1804,9 @@ setDimBehind(dimBehindValue: number): Promise&lt;void&gt;
Sets the dimness of the window that is not on top. This API uses a promise to return the result. Sets the dimness of the window that is not on top. This API uses a promise to return the result.
> **NOTE**: This API cannot be used. > **NOTE**
>
> This API cannot be used.
**System capability**: SystemCapability.WindowManager.WindowManager.Core **System capability**: SystemCapability.WindowManager.WindowManager.Core
...@@ -1956,8 +1959,9 @@ setOutsideTouchable(touchable: boolean, callback: AsyncCallback&lt;void&gt;): vo ...@@ -1956,8 +1959,9 @@ setOutsideTouchable(touchable: boolean, callback: AsyncCallback&lt;void&gt;): vo
Sets whether the area outside the subwindow is touchable. This API uses an asynchronous callback to return the result. Sets whether the area outside the subwindow is touchable. This API uses an asynchronous callback to return the result.
> **NOTE**: This API cannot be used. > **NOTE**
>
> This API cannot be used.
**System capability**: SystemCapability.WindowManager.WindowManager.Core **System capability**: SystemCapability.WindowManager.WindowManager.Core
...@@ -1986,8 +1990,9 @@ setOutsideTouchable(touchable: boolean): Promise&lt;void&gt; ...@@ -1986,8 +1990,9 @@ setOutsideTouchable(touchable: boolean): Promise&lt;void&gt;
Sets whether the area outside the subwindow is touchable. This API uses a promise to return the result. Sets whether the area outside the subwindow is touchable. This API uses a promise to return the result.
> **NOTE**: This API cannot be used. > **NOTE**
>
> This API cannot be used.
**System capability**: SystemCapability.WindowManager.WindowManager.Core **System capability**: SystemCapability.WindowManager.WindowManager.Core
......
# Search # Search
The **\<Search>** component provides an input area for users to search.
> **NOTE** > **NOTE**
> >
> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. > This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
The **\<Search>** component provides an input area for users to search.
## Required Permissions ## Required Permissions
None None
...@@ -18,34 +18,34 @@ Not supported ...@@ -18,34 +18,34 @@ Not supported
Search(options?: { value?: string; placeholder?: string; icon?: string; controller?: SearchController }) Search(options?: { value?: string; placeholder?: string; icon?: string; controller?: SearchController })
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- | | ----------- | ---------------- | ---- | ---- | ---------------------------------------- |
| value | string | No| - | Text input in the search text box. | | value | string | No | - | Text input in the search text box. |
| placeholder | string | No | - | Text displayed when there is no input. | | 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. | | 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. | | controller | SearchController | No | - | Controller. |
## Attributes ## Attributes
| Name | Type | Default Value | Description | | Name | Type | Default Value | 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](../../ui/ts-types.md) | - | Placeholder text color. | | placeholderColor | [ResourceColor](ts-types.md#resourcecolor8) | - | Placeholder text color. |
| placeholderFont | [Font](../../ui/ts-types.md) | - | Placeholder text style. | | placeholderFont | [Font](ts-types.md#font) | - | Placeholder text style. |
| textFont | [Font](../../ui/ts-types.md) | - | Text font for the search text box. | | textFont | [Font](ts-types.md#font) | - | Text font for the search text box. |
## Events ## Events
| Name | Description | | Name | Description |
| -------- | -------- | | ---------------------------------------- | ---------------------------------------- |
| onSubmit(callback: (value: string) => void) | Triggered when users click the search icon or the search button, or tap the search button on a soft keyboard.<br> - **value**: current text input. | | 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. | | 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. | | 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. | | 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. | | onPaste(callback: (value: string) => void) | Triggered when data is pasted from the pasteboard.<br> -**value**: text pasted. |
## SearchController ## SearchController
...@@ -61,11 +61,11 @@ caretPosition(value: number): void ...@@ -61,11 +61,11 @@ caretPosition(value: number): void
Sets the position of the caret. Sets the position of the caret.
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| ---- | ------ | ---- | ---- | --------------------- | | ----- | ------ | ---- | ---- | ----------------- |
| value | number | Yes | - | Length from the start of the text string to the position where the caret is located. | | value | number | Yes | - | Length from the start of the character string to the position where the caret is located.|
...@@ -76,29 +76,30 @@ Sets the position of the caret. ...@@ -76,29 +76,30 @@ Sets the position of the caret.
@Entry @Entry
@Component @Component
struct SearchExample { struct SearchExample {
@State changevalue: string = '' @State changeValue: string = ''
@State submitvalue: string = '' @State submitValue: string = ''
controller: SearchController = new SearchController() controller: SearchController = new SearchController()
build() { build() {
Flex({ direction: FlexDirection.Row, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) { Flex({ direction: FlexDirection.Row, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
Text(this.submitvalue) Text(this.submitValue)
Text(this.changevalue) Text(this.changeValue)
Search({value: '', placeholder: 'Type to search', controller: this.controller}) Search({value: this.changeValue, placeholder: 'Type to search', controller: this.controller})
.searchButton('Search') .searchButton('Search')
.width(400) .width(400)
.height(35) .height(35)
.backgroundColor(Color.White) .backgroundColor(Color.White)
.placeholderColor(Color.Grey) .placeholderColor(Color.Grey)
.placeholderFont({ size: 50, weight: 10, family: 'serif', style: FontStyle.Normal }) .placeholderFont({ size: 26, weight: 10, family: 'serif', style: FontStyle.Normal })
.onSubmit((value: string) => { .onSubmit((value: string) => {
this.submitvalue = value this.submitValue = value
}) })
.onChange((value: string) => { .onChange((value: string) => {
this.changevalue = value this.changeValue = value
}) })
.margin({ top: 30 }) .margin({ top: 30, left:10, right:10 })
} }
} }
} }
``` ```
![search](figures/search.png)
...@@ -33,23 +33,23 @@ Swiper(value:{controller?: SwiperController}) ...@@ -33,23 +33,23 @@ Swiper(value:{controller?: SwiperController})
[Menu control](ts-universal-attributes-menu.md) is not supported. [Menu control](ts-universal-attributes-menu.md) is not supported.
| Name | Type | Description | | Name | Type | Default Value | Description |
| --------------------------- | ---------------------------------------- | ---------------------------------------- | | --------------------------- | ---------------------------------------- | ---------------------------------------- | ---------------------------------------- |
| index | number | Index of the child component currently displayed in the container.<br>Default value: **0** | | index | number | 0 | Index of the child component currently displayed in the container. |
| 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** | | 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 | Interval for automatic playback, in ms.<br>Default value: **3000** | | interval | number | 3000 | Interval for automatic playback, in ms. |
| indicator | boolean | Whether to enable the navigation dots indicator.<br>Default value: **true** | | indicator | boolean | true | Whether to enable the navigation dots indicator. |
| loop | boolean | Whether to enable loop playback.<br>The value **true** means to enable loop playback. When LazyForEach is used, it is recommended that the number of the components to load exceed 5.<br>Default value: **true**| | loop | boolean | 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 | Duration of the animation for switching child components, in ms.<br>Default value: **400** | | duration | number | 400 | Duration of the animation for switching child components, in ms. |
| vertical | boolean | Whether vertical swiping is used.<br>Default value: **false** | | vertical | boolean | false | Whether vertical swiping is used. |
| itemSpace | Length | Space between child components.<br>Default value: **0** | | itemSpace | number \| string | 0 | Space between child components. |
| displayMode | SwiperDisplayMode | Mode in which elements are displayed along the main axis. This attribute takes effect only when **displayCount** is not set.<br>Default value: **SwiperDisplayMode.Stretch**| | displayMode | SwiperDisplayMode | 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 | Number of child components to be cached.<br>Default value: **1** | | cachedCount<sup>8+</sup> | number | 1 | Number of child components to be cached. |
| disableSwipe<sup>8+</sup> | boolean | Whether to disable the swipe feature.<br>Default value: **false** | | disableSwipe<sup>8+</sup> | boolean | false | Whether to disable the swipe feature. |
| curve<sup>8+</sup> | [Curve](ts-animatorproperty.md#Curve) \| string | Animation curve. The ease-in/ease-out curve is used by default. For details about common curves, see [Curve enums](ts-animatorproperty.md#curve-enums). 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**| | displayCount<sup>8+</sup> | number \| string | 1 | Number of elements to display. |
| indicatorStyle<sup>8+</sup> | {<br>left?:&nbsp;Length,<br>top?:&nbsp;Length,<br>right?:&nbsp;Length,<br>bottom?:&nbsp;Length,<br>size?:&nbsp;Length,<br>color?:&nbsp;Color,<br>selectedColor?:&nbsp;Color<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.| | effectMode<sup>8+</sup> | EdgeEffect | EdgeEffect.Spring | Swipe effect. For details, see **EdgeEffect**. |
| displayCount<sup>8+</sup> | number\|string | Number of elements to display.<br>Default value: **1** | | 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. |
| effectMode<sup>8+</sup> | EdgeEffect | Swipe effect. For details, see **EdgeEffect**.<br>Default value: **EdgeEffect.Spring**| | 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.|
## SwiperDisplayMode ## SwiperDisplayMode
...@@ -98,7 +98,7 @@ Stops this animation. ...@@ -98,7 +98,7 @@ Stops this animation.
### onChange ### onChange
onChange(&nbsp;index:&nbsp;number)&nbsp;=&gt;&nbsp;void onChange( index: number) =&gt; void
Triggered when the index of the currently displayed component changes. Triggered when the index of the currently displayed component changes.
......
# Image Effect Configuration # Image Effects
Image effects include background blur, content blur, grayscale, and much more.
> **NOTE** > **NOTE**
>
> This attribute is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > This attribute is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
...@@ -15,28 +17,30 @@ None ...@@ -15,28 +17,30 @@ None
| Name | Type | Default Value | Description | | Name | Type | Default Value | Description |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| blur | number | - | Adds the content blurring for the current component. The input parameter is the blur radius. The larger the radius is, the more blurred the content is. If the value is **0**, the content is not blurred. | | blur | number | - | 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 for the current component. The input parameter is the blur radius. The larger the radius is, the more blurred the background is. If the value is **0**, the background is not blurred. | | backdropBlur | number | - | 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,<br/>offsetX?: number,<br/>offsetY?: number<br/>} | - | Adds the shadow effect to the current component. The input parameters are the fuzzy radius (mandatory), shadow color (optional; gray by default), X-axis offset (optional and 0 by default), and Y-axis offset (optional; 0 by default). The offset unit is px. | | shadow | {<br/>radius: number,<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 | The value indicates the grayscale conversion ratio. If the input value is **1.0**, the image is converted into a grayscale image. If the input value is **0.0**, the image does not change. If the input value is between **0.0** and **1.0**, the effect changes in linear mode. The unit is percentage. The unit is percentage. | | grayscale | number | 0.0 | Converts the input image to grayscale. The value indicates the grayscale conversion ratio. If the input value is **1.0**, the image is converted into a grayscale image. If the input value is **0.0**, the image does not change. If the input value is between **0.0** and **1.0**, the effect changes in linear mode. The unit is percentage. The unit is percentage. |
| brightness | number | 1.0 | Adds a brightness to the current component. The input parameter is a brightness ratio. The value **1** indicates no effects. The value **0** indicates the complete darkness. If the value is less than **1**, the brightness decreases. If the value is greater than **1**, the brightness increases. A larger value indicates a higher brightness. | | brightness | number | 1.0 | Adds a brightness to the current component. The input parameter is a brightness ratio. The value **1** indicates no effects. The value **0** indicates the complete darkness. If the value is less than **1**, the brightness decreases. If the value is greater than **1**, the brightness increases. A larger value indicates a higher brightness. |
| saturate | number | 1.0 | Adds the saturation effect to the current component. The saturation is the ratio of the chromatic component to the achromatic component (gray) in a color. When the input value is **1**, the source image is displayed. When the input value is greater than **1**, a higher percentage of the chromatic component indicates a higher saturation. When the input value is less than **1**, a higher percentage of the achromatic component indicates a lower saturation. The unit is percentage. | | saturate | number | 1.0 | Adds the saturation effect to the current component. The saturation is the ratio of the chromatic component to the achromatic component (gray) in a color. When the input value is **1**, the source image is displayed. When the input value is greater than **1**, a higher percentage of the chromatic component indicates a higher saturation. When the input value is less than **1**, a higher percentage of the achromatic component indicates a lower saturation. The unit is percentage. |
| contrast | number | 1.0 | Adds the contrast effect to the current component. The input parameter is a contrast value. If the value is **1**, the source image is displayed. If the value is greater than **1**, a larger value indicates a higher contrast and a clearer image. If the value is less than **1**, a smaller value indicates a lower contrast is. If the value is **0**, the image becomes all gray. The unit is percentage. | | contrast | number | 1.0 | Adds the contrast effect to the current component. The input parameter is a contrast value. If the value is **1**, the source image is displayed. If the value is greater than **1**, a larger value indicates a higher contrast and a clearer image. If the value is less than **1**, a smaller value indicates a lower contrast is. If the value is **0**, the image becomes all gray. The unit is percentage. |
| invert | number | 0 | Inverts the input image. The input parameter is an image inversion ratio. The value **1** indicates complete inversion. The value **0** indicates that the image does not change. The unit is percentage. | | invert | number | 0 | Inverts the input image. The input parameter is an image inversion ratio. The value **1** indicates complete inversion. The value **0** indicates that the image does not change. The unit is percentage. |
| colorBlend <sup>8+</sup> | Color | - | Adds the color blend effect to the current component. The input parameter is the blended color. | | 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. | | sepia | number | 0 | Converts the image color to sepia. The input parameter is an image inversion ratio. The value **1** indicates the image is completely sepia. The value **0** indicates that the image does not change. The unit is percentage. |
| hueRotate | number \| string | '0deg' |Adds the hue rotation effect to the current component. The input parameter is a rotation angle. If the input value is **0deg**, the image does not change (because the default rotation angle is **0deg**). The input parameter does not have the maximum value. If the value exceeds **360deg**, the image is rotated for one more circle. In other words, the value **370deg** has the same effect as **10deg**.| | hueRotate | number \| string | '0deg' | Adds the hue rotation effect to the current component. The input parameter is a rotation angle. 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 ## 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 @Entry
@Component @Component
struct ImageEffectsExample { struct ImageEffectsExample {
build() { build() {
Column({space: 10}) { Column({space: 10}) {
// Blur the font. // Blur the font.
Text('font blur').fontSize(15).fontColor(0xCCCCCC).width('90%') Text('font blur').fontSize(15).fontColor(0xCCCCCC).width('90%')
Text('text').blur(3).width('90%').height(40) Text('text').blur(3).width('90%').height(40)
......
# Standard Libraries Supported by Native APIs # Standard Libraries Supported by Native APIs
- [Standard Libraries](third_party_libc/musl.md)
- [Node_API](third_party_napi/napi.md) - [Node_API](third_party_napi/napi.md)
- [libuv](third_party_libuv/libuv.md) - [libuv](third_party_libuv/libuv.md)
- [Native API Symbols Not Exported](third_party_libc/musl-peculiar-symbol.md) - [Standard Libraries](third_party_libc/musl.md)
\ No newline at end of file - Appendix
- [Native API Symbols Not Exported](third_party_libc/musl-peculiar-symbol.md)
- [EGL Symbols Exported from Native APIs](third_party_opengl/egl-symbol.md)
- [OpenGL ES 3.0 Symbols Exported from Native APIs](third_party_opengl/openglesv3-symbol.md)
\ No newline at end of file
# UI Development # UI Development
- [ArkUI Overview](arkui-overview.md) - [ArkUI Overview](arkui-overview.md)
- TypeScript-based Declarative Development Paradigm
- [Overview](ui-ts-overview.md)
- Framework Overview
- File Organization
- [Directory Structure](ts-framework-directory.md)
- [Rules for Accessing Application Code Files](ts-framework-file-access-rules.md)
- ["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)
- [Pixel Units](ts-pixel-units.md)
- Declarative Syntax
- [Overview](ts-syntax-intro.md)
- General UI Description Specifications
- [Basic Concepts](ts-general-ui-concepts.md)
- Declarative UI Description Specifications
- [Configuration Without Parameters](ts-parameterless-configuration.md)
- [Configuration with Mandatory Parameters](ts-configuration-with-mandatory-parameters.md)
- [Attribute Configuration](ts-attribution-configuration.md)
- [Event Configuration](ts-event-configuration.md)
- [Child Component Configuration](ts-child-component-configuration.md)
- Componentization
- [@Component](ts-component-based-component.md)
- [@Entry](ts-component-based-entry.md)
- [@Preview](ts-component-based-preview.md)
- [@Builder](ts-component-based-builder.md)
- [@Extend](ts-component-based-extend.md)
- [@CustomDialog](ts-component-based-customdialog.md)
- [@Styles](ts-component-based-styles.md)
- About UI State Management
- [Basic Concepts](ts-ui-state-mgmt-concepts.md)
- Managing Component States
- [@State](ts-component-states-state.md)
- [@Prop](ts-component-states-prop.md)
- [@Link](ts-component-states-link.md)
- Managing Application States
- [AppStorage](ts-application-states-appstorage.md)
- [PersistentStorage](ts-application-states-apis-persistentstorage.md)
- [Environment](ts-application-states-apis-environment.md)
- Managing Other States
- [@Observed and @ObjectLink](ts-other-states-observed-objectlink.md)
- [@Consume and @Provide](ts-other-states-consume-provide.md)
- [@Watch](ts-other-states-watch.md)
- About Rendering Control Syntax
- [if/else](ts-rending-control-syntax-if-else.md)
- [ForEach](ts-rending-control-syntax-foreach.md)
- [LazyForEach](ts-rending-control-syntax-lazyforeach.md)
- About @Component
- [build Function](ts-function-build.md)
- [Initialization of Custom Components' Member Variables](ts-custom-component-initialization.md)
- [Custom Component Lifecycle Callbacks](ts-custom-component-lifecycle-callbacks.md)
- [Component Creation and Re-initialization](ts-component-creation-re-initialization.md)
- [About Syntactic Sugar](ts-syntactic-sugar.md)
- Common Component Development Guidelines
- [Button](ui-ts-basic-components-button.md)
- [Web](ui-ts-components-web.md)
- Common Layout Development Guidelines
- [Flex Layout](ui-ts-layout-flex.md)
- [Grid Layout](ui-ts-layout-grid-container.md)
- [Media Query](ui-ts-layout-mediaquery.md)
- Experiencing the Declarative UI
- [Creating a Declarative UI Project](ui-ts-creating-project.md)
- [Getting to Know Components](ui-ts-components.md)
- [Creating a Simple Page](ui-ts-creating-simple-page.md)
- Defining Page Layout and Connection
- [Building a Food Data Model](ui-ts-building-data-model.md)
- [Building a Food Category List Layout](ui-ts-building-category-list-layout.md)
- [Building a Food Category Grid Layout](ui-ts-building-category-grid-layout.md)
- [Implementing Page Redirection and Data Transmission](ui-ts-page-redirection-data-transmission.md)
- JavaScript-based Web-like Development Paradigm - JavaScript-based Web-like Development Paradigm
- [Overview](ui-js-overview.md) - [Overview](ui-js-overview.md)
- Framework - Framework
...@@ -73,73 +142,3 @@ ...@@ -73,73 +142,3 @@
- [Animation Effect](ui-js-animate-dynamic-effects.md) - [Animation Effect](ui-js-animate-dynamic-effects.md)
- [Animation Frame](ui-js-animate-frame.md) - [Animation Frame](ui-js-animate-frame.md)
- [Custom Components](ui-js-custom-components.md) - [Custom Components](ui-js-custom-components.md)
- TypeScript-based Declarative Development Paradigm
- [Overview](ui-ts-overview.md)
- Framework Overview
- File Organization
- [Directory Structure](ts-framework-directory.md)
- [Rules for Accessing Application Code Files](ts-framework-file-access-rules.md)
- ["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)
- [Pixel Units](ts-pixel-units.md)
- [Types](ts-types.md)
- Declarative Syntax
- [Overview](ts-syntax-intro.md)
- General UI Description Specifications
- [Basic Concepts](ts-general-ui-concepts.md)
- Declarative UI Description Specifications
- [Configuration Without Parameters](ts-parameterless-configuration.md)
- [Configuration with Mandatory Parameters](ts-configuration-with-mandatory-parameters.md)
- [Attribute Configuration](ts-attribution-configuration.md)
- [Event Configuration](ts-event-configuration.md)
- [Child Component Configuration](ts-child-component-configuration.md)
- Componentization
- [@Component](ts-component-based-component.md)
- [@Entry](ts-component-based-entry.md)
- [@Preview](ts-component-based-preview.md)
- [@Builder](ts-component-based-builder.md)
- [@Extend](ts-component-based-extend.md)
- [@CustomDialog](ts-component-based-customdialog.md)
- [@Styles](ts-component-based-styles.md)
- About UI State Management
- [Basic Concepts](ts-ui-state-mgmt-concepts.md)
- Managing Component States
- [@State](ts-component-states-state.md)
- [@Prop](ts-component-states-prop.md)
- [@Link](ts-component-states-link.md)
- Managing Application States
- [AppStorage](ts-application-states-appstorage.md)
- [PersistentStorage](ts-application-states-apis-persistentstorage.md)
- [Environment](ts-application-states-apis-environment.md)
- Managing Other States
- [@Observed and @ObjectLink](ts-other-states-observed-objectlink.md)
- [@Consume and @Provide](ts-other-states-consume-provide.md)
- [@Watch](ts-other-states-watch.md)
- About Rendering Control Syntax
- [if/else](ts-rending-control-syntax-if-else.md)
- [ForEach](ts-rending-control-syntax-foreach.md)
- [LazyForEach](ts-rending-control-syntax-lazyforeach.md)
- About @Component
- [build Function](ts-function-build.md)
- [Initialization of Custom Components' Member Variables](ts-custom-component-initialization.md)
- [Custom Component Lifecycle Callbacks](ts-custom-component-lifecycle-callbacks.md)
- [Component Creation and Re-initialization](ts-component-creation-re-initialization.md)
- [About Syntactic Sugar](ts-syntactic-sugar.md)
- Common Component Development Guidelines
- [Button](ui-ts-basic-components-button.md)
- [Web](ui-ts-components-web.md)
- Common Layout Development Guidelines
- [Flex Layout](ui-ts-layout-flex.md)
- [Grid Layout](ui-ts-layout-grid-container.md)
- [Media Query](ui-ts-layout-mediaquery.md)
- Experiencing the Declarative UI
- [Creating a Declarative UI Project](ui-ts-creating-project.md)
- [Getting to Know Components](ui-ts-components.md)
- [Creating a Simple Page](ui-ts-creating-simple-page.md)
- Defining Page Layout and Connection
- [Building a Food Data Model](ui-ts-building-data-model.md)
- [Building a Food Category List Layout](ui-ts-building-category-list-layout.md)
- [Building a Food Category Grid Layout](ui-ts-building-category-grid-layout.md)
- [Implementing Page Redirection and Data Transmission](ui-ts-page-redirection-data-transmission.md)
...@@ -85,11 +85,11 @@ The following is an example: ...@@ -85,11 +85,11 @@ The following is an example:
```css ```css
/* Page style xxx.css */ /* Page style xxx.css */
/\* Set the style for all <div> components. \*/ /* Set the style for all <div> components. */
div { div {
flex-direction: column; flex-direction: column;
} }
/* Set the style for the component whose class is title. */ /* Set the style for the component whose class is title.*/
.title { .title {
font-size: 30px; font-size: 30px;
} }
...@@ -101,13 +101,13 @@ div { ...@@ -101,13 +101,13 @@ div {
.title, .content { .title, .content {
padding: 5px; padding: 5px;
} }
/\* Set the style for all texts of components whose class is container.\*/ /* Set the style for all texts of components whose class is container.*/
.container text { .container text {
color: \#007dff; color: \#007dff;
} }
/\* Set the style for direct descendant texts of components whose class is container.\*/ /* Set the style for direct descendant texts of components whose class is container.*/
.container &gt; text { .container &gt; text {
color: \#fa2a2d; color: #fa2a2d;
} }
``` ```
...@@ -128,7 +128,7 @@ When multiple selectors point to the same element, their priorities are as follo ...@@ -128,7 +128,7 @@ When multiple selectors point to the same element, their priorities are as follo
A CSS pseudo-class is a keyword added to a selector that specifies a special state of the selected element(s). For example, :disabled can be used to select the element whose disabled attribute is true. A CSS pseudo-class is a keyword added to a selector that specifies a special state of the selected element(s). For example, :disabled can be used to select the element whose disabled attribute is true.
In addition to a single pseudo-class, a combination of pseudo-classes is supported. For example, **:focus:checked** selects the element whose focus and checked attributes are both set to true. The following table lists the supported single pseudo-class in descending order of priority. In addition to a single pseudo-class, a combination of pseudo-classes is supported. For example, :focus:checked selects the element whose focus and checked attributes are both set to true. The following table lists the supported single pseudo-class in descending order of priority.
| Pseudo-class | Available Components | Description | | Pseudo-class | Available Components | Description |
......
...@@ -21,7 +21,7 @@ By default, the attributes in the AppStorage are changeable. If needed, AppStora ...@@ -21,7 +21,7 @@ By default, the attributes in the AppStorage are changeable. If needed, AppStora
| Set | key: string,<br/>newValue: T | void | Replaces the value of a saved key. | | Set | key: string,<br/>newValue: T | void | Replaces the value of a saved key. |
| Link | key: string | @Link | Returns two-way binding to this attribute if there is data with a given key. This means that attribute changes made by a variable or component will be synchronized to the AppStorage, and attribute changes made through the AppStorage will be synchronized to the variable or component. If the attribute with this key does not exist or is read-only, undefined is returned. | | Link | key: string | @Link | Returns two-way binding to this attribute if there is data with a given key. This means that attribute changes made by a variable or component will be synchronized to the AppStorage, and attribute changes made through the AppStorage will be synchronized to the variable or component. If the attribute with this key does not exist or is read-only, undefined is returned. |
| SetAndProp | propName: string,<br/>defaultValue: S | @Prop | Works in a way similar to the Prop API. If the current key is stored in the AppStorage, the value corresponding to the key is returned. If the key has not been created, a Prop instance corresponding to the default value is created and returned. | | SetAndProp | propName: string,<br/>defaultValue: S | @Prop | Works in a way similar to the Prop API. If the current key is stored in the AppStorage, the value corresponding to the key is returned. If the key has not been created, a Prop instance corresponding to the default value is created and returned. |
| Prop | key: string | @Prop | Returns one-way binding to an attribute with a given key if the attribute exists. This means that attribute changes made through the AppStorage will be synchronized to the variable or component, but attribute changes made by the variable or component will be synchronized to the AppStorage. The variable returned by this method is an immutable one, which is applicable both to the variable and immutable state attributes. If the attribute with the specified key does not exist, undefined is returned.<br/>> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**:<br/>> The attribute value used in the prop method must be of a simple type. | | Prop | key: string | @Prop | Returns one-way binding to an attribute with a given key if the attribute exists. This means that attribute changes made through the AppStorage will be synchronized to the variable or component, but attribute changes made by the variable or component will be synchronized to the AppStorage. The variable returned by this method is an immutable one, which is applicable both to the variable and immutable state attributes. If the attribute with the specified key does not exist, undefined is returned.<br/>**NOTE**<br/>The attribute value used in the prop method must be of a simple type. |
| SetOrCreate | key: string,<br/>newValue: T | boolean | If an attribute that has the same name as the specified key exists: replaces the value of the attribute and returns true when the attribute can be modified; retains the original value of the attribute and returns false otherwise.<br/>If an attribute that has the same name as the specified key does not exist: creates an attribute whose key is key and value is newValue. The values null and undefined are not supported. | | SetOrCreate | key: string,<br/>newValue: T | boolean | If an attribute that has the same name as the specified key exists: replaces the value of the attribute and returns true when the attribute can be modified; retains the original value of the attribute and returns false otherwise.<br/>If an attribute that has the same name as the specified key does not exist: creates an attribute whose key is key and value is newValue. The values null and undefined are not supported. |
| Get | key: string | T or undefined | Obtains the value of the specified key. | | Get | key: string | T or undefined | Obtains the value of the specified key. |
| Has | propName: string | boolean | Checks whether the attribute corresponding to the specified key value exists. | | Has | propName: string | boolean | Checks whether the attribute corresponding to the specified key value exists. |
...@@ -51,9 +51,8 @@ One-way data binding can be established between components and the AppStorage th ...@@ -51,9 +51,8 @@ One-way data binding can be established between components and the AppStorage th
## Example ## Example
``` ```ts
let varA = AppStorage.Link('varA') // xxx.ets
let envLang = AppStorage.Prop('languageCode')
@Entry @Entry
@Component @Component
......
...@@ -5,10 +5,13 @@ ...@@ -5,10 +5,13 @@
To reference an application resource in a project, use the `"$r('app.type.name')"` format. **app** indicates the resource defined in the **resources** directory of the application. **type** indicates the resource type (or the location where the resource is stored). The value can be **color**, **float**, **string**, **plural**, or **media**. **name** indicates the resource name, which you set when defining the resource. To reference an application resource in a project, use the `"$r('app.type.name')"` format. **app** indicates the resource defined in the **resources** directory of the application. **type** indicates the resource type (or the location where the resource is stored). The value can be **color**, **float**, **string**, **plural**, or **media**. **name** indicates the resource name, which you set when defining the resource.
When referencing resources in the **rawfile** sub-directory, use the `"$rawfile('filename')"` format. Currently, **$rawfile** allows only the **\<Image>** component to reference image resources. **filename** indicates the relative path of a file in the **rawfile** directory, and the file name must contain the file name extension. Note that the relative path cannot start with a slash (/). When referencing resources in the **rawfile** sub-directory, use the ```"$rawfile('filename')"``` format. **filename** indicates the relative path of a file in the **rawfile** directory, and the file name must contain the file name extension. Note that the relative path cannot start with a slash (/).
> **NOTE** > **NOTE**
>
> Resource descriptors accept only strings, such as `'app.type.name'`, and cannot be combined. > Resource descriptors accept only strings, such as `'app.type.name'`, and cannot be combined.
>
> `$r` returns a **Resource** object. To obtain the corresponding string, use [getString](../reference/apis/js-apis-resource-manager.md#getstring).
In the **.ets** file, you can use the resources defined in the **resources** directory. In the **.ets** file, you can use the resources defined in the **resources** directory.
...@@ -47,7 +50,7 @@ Image($rawfile('newDir/newTest.png')) // Reference an image in the rawfile direc ...@@ -47,7 +50,7 @@ Image($rawfile('newDir/newTest.png')) // Reference an image in the rawfile direc
System resources include colors, rounded corners, fonts, spacing, character strings, and images. By using system resources, you can develop different applications with the same visual style. System resources include colors, rounded corners, fonts, spacing, character strings, and images. By using system resources, you can develop different applications with the same visual style.
To reference a system resource, use the "$r('sys.type.resource_id')" format. Wherein: sys indicates a system resource; type indicates the resource type, which can be color, float, string, or media; resource_id indicates the resource ID, which is determined when the system resource is provided. For details about available system resource IDs. To reference a system resource, use the ```"$r('sys.type.resource_id')"``` format. Wherein: **sys** indicates a system resource; **type** indicates the resource type, which can be **color**, **float**, **string**, or **media**; **resource_id** indicates the resource ID.
```ts ```ts
Text('Hello') Text('Hello')
......
# About Syntactic Sugar # About Syntactic Sugar
## Decorators ## Decorators
A decorator @Decorator can decorate a class, structure, or class attribute. Multiple decorators can be applied to the same target element and defined on a single line or multiple lines. It is recommended that the decorators be defined on multiple lines.
In the example below, the elements decorated by @Component take on the form of a component, and the variables decorated by @State can be used to represent states. A decorator **@Decorator** can decorate a class, structure, or class attribute. Multiple decorators can be applied to the same target element and defined on a single line or multiple lines. It is recommended that the decorators be defined on multiple lines.
``` In the example below, the elements decorated by **@Component** take on the form of a component, and the variables decorated by **@State** can be used to represent states.
```ts
@Component @Component
struct MyComponent { struct MyComponent {
@State count: number = 0 @State count: number = 0
} }
``` ```
Multiple decorators can be defined on a single line, as shown below: Multiple decorators can be defined on a single line, as shown below:
``` ```ts
@Entry @Component struct MyComponent { @Entry @Component struct MyComponent {
} }
``` ```
However, you are advised to define the decorators on multiple lines, as shown below: However, you are advised to define the decorators on multiple lines, as shown below:
``` ```ts
@Entry @Entry
@Component @Component
struct MyComponent { struct MyComponent {
...@@ -36,30 +39,29 @@ struct MyComponent { ...@@ -36,30 +39,29 @@ struct MyComponent {
### Supported Decorators ### Supported Decorators
| Decorator | Decorates... | Description | | Decorator | Decorates... | Description |
| -------- | -------- | -------- | | ------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| @Component | struct | The decorated structure has the component-based capability. The build method must be implemented to update the UI. | | @Component | struct | The decorated structure has the component-based capability. The **build** method must be implemented to update the UI.|
| @Entry | struct | The decorated component is used as the entry of a page. The component is rendered and displayed when the page is loaded. | | @Entry | struct | The decorated component is used as the entry of a page. The component is rendered and displayed when the page is loaded. |
| @Preview | struct | Custom components decorated by @Preview can be previewed in the Previewer of DevEco Studio. When the page is loaded, the custom components decorated by @Preview are created and displayed. | | @Preview | struct | Custom components decorated by **@Preview** can be previewed in DevEco Studio. When the target page is loaded, the custom components decorated by **@Preview** are created and displayed.|
| @Builder | Methods | In the decorated method, you can use the declarative UI description to quickly generate multiple layouts in a custom component. | | @Builder | Methods | In the decorated method, you can use the declarative UI description to quickly generate multiple layouts in a custom component.|
| @Extend | Methods | This decorator adds new attribute functions to a preset component, allowing you to quickly define and reuse the custom style of the component. | | @Extend | Methods | This decorator adds attribute functions to a preset component, allowing you to quickly define and reuse the custom style of the component.|
| @CustomDialog | struct | This decorator is used to decorate custom pop-up dialog boxes. | | @CustomDialog | struct | This decorator is used to decorate custom pop-up dialog boxes. |
| @State | Primitive data types, classes, and arrays | If the decorated state data is modified, the build method of the component will be called to update the UI. | | @State | Primitive data types, classes, and arrays | If the decorated state data is modified, the **build** method of the component will be called to update the UI. |
| @Prop | Primitive data types | This decorator is used to establish one-way data binding between the parent and child components. When the data associated with the parent component is modified, the UI of the current component is updated. | | @Prop | Primitive data types | This decorator is used to establish one-way data binding between the parent and child components. When the data associated with the parent component is modified, the UI of the current component is updated.|
| @Link | Primitive data types, classes, and arrays | This decorator is used to establish two-way data binding between the parent and child components. The internal state data of the parent component is used as the data source. Any changes made to one component will be reflected to the other. | | @Link | Primitive data types, classes, and arrays | This decorator is used to establish two-way data binding between the parent and child components. The internal state data of the parent component is used as the data source. Any changes made to one component will be reflected to the other.|
| @Observed | Classes | This decorator is used to indicate that the data changes in the class will be managed by the UI page. | | @Observed | Classes | This decorator is used to indicate that the data changes in the class will be managed by the UI page. |
| @ObjectLink | Objects of @Observed decorated classes | When the decorated state variable is modified, the parent and sibling components that have the state variable will be notified for UI re-rendering. | | @ObjectLink | Objects of **@Observed** decorated classes | When the decorated state variable is modified, the parent and sibling components that have the state variable will be notified for UI re-rendering.|
| @Consume | Primitive data types, classes, and arrays | When the @Consume decorated variable detects the update of the @Provide decorated variable, the re-rendering of the current custom component is triggered. | | @Consume | Primitive data types, classes, and arrays | When the **@Consume** decorated variable detects the update of the **@Provide** decorated variable, the re-rendering of the current custom component is triggered.|
| @Provide | Primitive data types, classes, and arrays | As the data provider, @Provide can update the data of child nodes and trigger page rendering. | | @Provide | Primitive data types, classes, and arrays | As the data provider, **@Provide** can update the data of child nodes and trigger page rendering.|
| @Watch | Variables decorated by @State, @Prop, @Link, @ObjectLink, @Provide, @Consume, @StorageProp, or @StorageLink | This decorator is used to listen for the changes of the state variables. The application can register a callback method through @Watch. | | @Watch | Variables decorated by **@State**, **@Prop**, **@Link**, **@ObjectLink**, **@Provide**, **@Consume**, **@StorageProp**, or **@StorageLink** | This decorator is used to listen for the changes of the state variables. The application can register a callback method through **@Watch**. |
## Chain Call ## Chain Call
You can configure the UI structure and its attributes and events and separate them with a dot(.) to implement chain call. You can configure the UI structure and its attributes and events and separate them with a dot(.) to implement chain call.
```ts
```
Column() { Column() {
Image('1.jpg') Image('1.jpg')
.alt('error.jpg') .alt('error.jpg')
...@@ -71,10 +73,9 @@ Column() { ...@@ -71,10 +73,9 @@ Column() {
## struct ## struct
Components can be implemented based on structs. Components cannot inherit from each other. The structs implemented components can be created and destroyed more quickly than class implemented components. Components can be implemented based on **struct**s. Components cannot inherit from each other. The **struct**s implemented components can be created and destroyed more quickly than **class** implemented components.
```ts
```
@Component @Component
struct MyComponent { struct MyComponent {
@State data: string = '' @State data: string = ''
...@@ -87,10 +88,9 @@ struct MyComponent { ...@@ -87,10 +88,9 @@ struct MyComponent {
## Instantiating a struct Without the new Keyword ## Instantiating a struct Without the new Keyword
You can omit the new keyword when instantiating a struct. You can omit the **new** keyword when instantiating a **struct**.
``` ```ts
// Definition // Definition
@Component @Component
struct MyComponent { struct MyComponent {
...@@ -98,7 +98,7 @@ struct MyComponent { ...@@ -98,7 +98,7 @@ struct MyComponent {
} }
} }
// Use // Usage
Column() { Column() {
MyComponent() MyComponent()
} }
...@@ -114,23 +114,22 @@ new Column() { ...@@ -114,23 +114,22 @@ new Column() {
TypeScript has the following restrictions on generators: TypeScript has the following restrictions on generators:
- Expressions can be used only in character strings (${expression}), if conditions, ForEach parameters, and component parameters. - Expressions can be used only in character strings (${expression}), **if** conditions, **ForEach** parameters, and component parameters.
- No expressions should cause any application state variables (@State, @Link, and @Prop) to change. Otherwise, undefined and potentially unstable framework behavior may occur. - No expressions should cause any application state variables (**@State**, **@Link**, and **@Prop**) to change. Otherwise, undefined and potentially unstable framework behavior may occur.
- The generator function cannot contain local variables. - The generator function cannot contain local variables.
None of the above restrictions apply to anonymous function implementations of event-handling functions (such as onClick) None of the above restrictions apply to anonymous function implementations of event-handling functions (such as **onClick**)
Incorrect: Incorrect:
```ts
```
build() { build() {
let a: number = 1 // invalid: variable declaration not allowed let a: number = 1 // invalid: variable declaration not allowed
Column() { Column() {
Text('Hello ${this.myName.toUpperCase()}') // ok. Text(`Hello ${this.myName.toUpperCase()}`) // ok.
ForEach(this.arr.reverse(), ..., ...) // invalid: Array.reverse modifies the @State array varible in place ForEach(this.arr.reverse(), ..., ...) // invalid: Array.reverse modifies the @State array variable in place
} }
buildSpecial() // invalid: no function calls buildSpecial() // invalid: no function calls
Text(this.calcTextValue()) // this function call is ok. Text(this.calcTextValue()) // this function call is ok.
...@@ -139,11 +138,13 @@ build() { ...@@ -139,11 +138,13 @@ build() {
## $$ ## $$
$$ supports two-way binding for simple variables and @State, @Link, and @Prop decorated variables. **$$** supports two-way binding for simple variables and **@State**, **@Link**, and **@Prop** decorated variables.
Currently, $$ supports only the rendering between the show parameter of the bindPopup attribute and the @State decorated variable, and the checked attribute of the \<Radio> component. Currently, **$$** supports only the rendering between the **show** parameter of the **[bindPopup](../reference/arkui-ts/ts-universal-attributes-popup.md)** attribute and the **@State** decorated variable, and the **checked** attribute of the **\<Radio>** component.
```
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct bindPopup { struct bindPopup {
...@@ -166,3 +167,29 @@ struct bindPopup { ...@@ -166,3 +167,29 @@ struct bindPopup {
} }
``` ```
## Restrictions on Declaring Multiple Data Types of State Variables
If a **@State**, **@Provide**, **@Link**, or **@Consume** decorated state variable supports multiple data types, they must be all simple data types or references at one time.
Example:
```ts
@Entry
@Component
struct Index {
// Incorrect: @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%')
}
}
```
# Types
## Length Type
| Name| Type| Description|
| -------- | -------- | -------- |
| Length | string \| number | Length unit. If the input is a number, use vp. If the input is a string, explicitly specify the unit, for example, '10px', or specify the length in percentage, for example, '100%'.|
## Angle Type
| Name| Type| Description|
| -------- | -------- | -------- |
| Angle | string \| number | Angle unit. If the input is a number, use deg. If the input is a string, use either of the following angle units:<br>- deg: for example, '100deg'<br>- rad: for example, '3.14rad' |
## Point Type
| Name| Type| Description|
| -------- | -------- | -------- |
| Point | [Length, Length] | Coordinates of a point. The first value is the x-axis coordinate, and the second value is the y-axis coordinate.|
## Color Type
The Color type used by component attribute methods is described as follows:
| Name| Type| Description|
| -------- | -------- | -------- |
| Color | string \| number \| Color | Color information. If the input is a string, use rgb or rgba to specify the color. If the input is a number, use Hex format to specify the color. If the input is a Color enum, use a color value to specify the color.<br>- 'rgb(255, 255, 255)'<br>- 'rgba(255, 255, 255, 1.0)'<br>- Hex format: 0xrrggbb, 0xaarrggbb, '\#FFFFFF'<br>- Enum: Color.Black, Color.White |
The supported Color enums are described as follows:
| Color| Value| Illustration|
| -------- | -------- | -------- |
| Black | 0x000000 | ![en-us_image_0000001219864153](figures/en-us_image_0000001219864153.png) |
| Blue | 0x0000ff | ![en-us_image_0000001174104404](figures/en-us_image_0000001174104404.png) |
| Brown | 0xa52a2a | ![en-us_image_0000001219744201](figures/en-us_image_0000001219744201.png) |
| Gray | 0x808080 | ![en-us_image_0000001174264376](figures/en-us_image_0000001174264376.png) |
| Green | 0x008000 | ![en-us_image_0000001174422914](figures/en-us_image_0000001174422914.png) |
| Orange | 0xffa500 | ![en-us_image_0000001219662661](figures/en-us_image_0000001219662661.png) |
| Pink | 0xffc0cb | ![en-us_image_0000001219662663](figures/en-us_image_0000001219662663.png) |
| Red | 0xff0000 | ![en-us_image_0000001219662665](figures/en-us_image_0000001219662665.png) |
| White | 0xffffff | ![en-us_image_0000001174582866](figures/en-us_image_0000001174582866.png) |
| Yellow | 0xffff00 | ![en-us_image_0000001174582864](figures/en-us_image_0000001174582864.png) |
## ColorStop Type
ColorStop is used to describe the progressive color stop.
| Name| Type| Description|
| -------- | -------- | -------- |
| ColorStop | [Color, number] | Type of the progressive color stop. The first parameter specifies the color value, and the second parameter specifies the ratio of 0 to 1.|
## Resource Type
The Resource type is used to reference resources for setting the value of a component attribute.
You can use ` $r ` or ` $rawfile ` to create a Resource object. For details, see [Resource Access](ts-application-resource-access.md).
- ` $r('belonging.type.name') `
` belonging ` : system or application resource. The value can be 'sys' or 'app'.
` type ` : resource type, which can be 'color', 'float', 'string', or 'media'.
` name ` : resource name, which is determined during resource definition.
- ` $rawfile('filename') `
` filename ` : name of the file in resources/rawfile of the project.
| Name| Type| Description|
| -------- | -------- | -------- |
| Resource | {<br>readonly id: [number];<br>readonly type: [number];<br>readonly params?: any[];<br>} | **id**: resource ID.<br>**type**: resource type (enumerated value).<br>**params**: optional parameters.<br>After a **Resource** object is created using `$r` or `$rawfile`, modifying attribute values of the object is prohibited. |
## ResourceStr Type<sup>8+</sup>
| Name| Type| Description|
| -------- | -------- | -------- |
| ResourceStr | string \| Resource| Resource string.|
## ResourceColor Type<sup>8+</sup>
| Name| Type| Description|
| -------- | -------- | -------- |
| ResourceColor | Color \| number \| string \| Resource | Resource color.|
## Font Type<sup>8+</sup>
| Name| Type| Description|
| -------- | -------- | -------- |
| Font | {<br>size?: Length;<br>weight?: FontWeight \| number \| string;<br>family?: string \| Resource;<br>style?: FontStyle;<br>} | Text style.<br>**size**: font size. For the number type, use the unit 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. The priority of the fonts is the sequence in which they are placed. An example value is **'Arial, sans-serif'**.<br>**style**: font style. |
## CustomBuilder Type<sup>8+</sup>
You can use CustomBuilder to define custom UI descriptions in component attribute methods.
| Name| Type| Description|
| -------- | -------- | -------- |
| CustomBuilder | () => any | Builder of component attribute methods for defining custom UI descriptions. This type of method must be decorated by @Builder. For details, see [@Builder](ts-component-based-builder.md).|
## Example
```
@Entry
@Component
struct dataTypeExample {
build() {
Column({ space: 5 }) {
Text('Length').fontColor(0xCCCCCC).fontSize(9).width('90%')
Text('90%').width('90%').height(40).backgroundColor(0xF9CF93)
.textAlign(TextAlign.Center).fontColor(Color.White)
Text('320').width(320).height(40).backgroundColor(0xF9CF93)
.textAlign(TextAlign.Center).fontColor(Color.White)
Text('1000px').width('1000px').height(40).backgroundColor(0xF9CF93)
.textAlign(TextAlign.Center).fontColor(Color.White)
Text('Angle').fontColor(0xCCCCCC).fontSize(9).width('90%')
Text('45deg')
.width(40).height(40)
.rotate({ x: 0, y: 0, z: 1, angle: 45, centerX: '50%', centerY: '50%' })
.fontColor(Color.White)
.backgroundColor(0xF9CF93).textAlign(TextAlign.Center)
Text('45rad')
.width(40).height(40)
.rotate({ x: 0, y: 0, z: 1, angle: '45rad', centerX: '50%', centerY: '50%' })
.fontColor(Color.White)
.backgroundColor(0xF9CF93).textAlign(TextAlign.Center).margin({ top: 30 })
Text('Point').fontColor(0xCCCCCC).fontSize(9).width('90%')
Line().width(300).height(40).startPoint([0, 20]).endPoint([300, 20])
Text('Color').fontColor('#CCCCCC').fontSize(9).width('90%')
Text('0xF9CF93')
.fontColor(Color.White).textAlign(TextAlign.Center)
.width('90%').height(40).backgroundColor(0xF9CF93)
Text('#F9CF93')
.fontColor(Color.White).textAlign(TextAlign.Center)
.width('90%').height(40).backgroundColor('#F9CF93')
Text('rgb(249, 207, 147)')
.fontColor(Color.White).textAlign(TextAlign.Center)
.width('90%').height(40).backgroundColor('rgb(249, 207, 147)')
Text('rgba(249, 207, 147, 1.0)')
.fontColor(Color.White).textAlign(TextAlign.Center)
.width('90%').height(40).backgroundColor('rgba(249, 207, 147, 1.0)')
Text('Color.Yellow')
.textAlign(TextAlign.Center)
.width('90%').height(40).backgroundColor(Color.Yellow)
}
.width('100%').margin({ top: 5 })
}
}
```
![en-us_image_0000001219982719](figures/en-us_image_0000001219982719.png)
...@@ -9,14 +9,15 @@ The **&lt;switch&gt;** component is used to switch between the on and off states ...@@ -9,14 +9,15 @@ The **&lt;switch&gt;** component is used to switch between the on and off states
Create a **&lt;switch&gt;** component in the .hml file under **pages/index**. Create a **&lt;switch&gt;** component in the .hml file under **pages/index**.
``` ```html
<!-- xxx.hml -->
<div class="container"> <div class="container">
<switch></switch> <switch></switch>
</div> </div>
``` ```
``` ```css
/* xxx.css */ /* xxx.css */
.container { .container {
flex-direction: column; flex-direction: column;
...@@ -31,9 +32,9 @@ Create a **&lt;switch&gt;** component in the .hml file under **pages/index**. ...@@ -31,9 +32,9 @@ Create a **&lt;switch&gt;** component in the .hml file under **pages/index**.
## Adding Attributes and Methods ## Adding Attributes and Methods
Use the **textoff** and **showtext** attributes to set the status when text is selected and unselected. Set the **checked** attribute to **true** (indicating that the component is on). Add the **change** event that is triggered when the component status changes. After the event is triggered, the **switchChange** function is executed to obtain the current component status (on or off). Use the **textoff** and **showtext** attributes to set the status when text is selected and unselected. Set the **checked** attribute to **true** (indicating that the component is on). Add the **change** event that is triggered when the component status changes. After the event is triggered, the **switchChange** function is executed to obtain the current component status (on or off).
``` ```html
<!-- xxx.hml --> <!-- xxx.hml -->
<div class="container"> <div class="container">
<switch showtext="true" texton="open" textoff="close" checked="true" @change="switchChange"></switch> <switch showtext="true" texton="open" textoff="close" checked="true" @change="switchChange"></switch>
...@@ -41,28 +42,26 @@ Create a **&lt;switch&gt;** component in the .hml file under **pages/index**. ...@@ -41,28 +42,26 @@ Create a **&lt;switch&gt;** component in the .hml file under **pages/index**.
``` ```
``` ```css
/* xxx.css */ /* xxx.css */
.container { .container {
width: 100%; width: 100%;
height: 100%; height: 100%;
display: flex; display: flex;
justify-content: center; justify-content: center;
align-items: center; align-items: center;
background-color: #F1F3F5; background-color: #F1F3F5;
} }
switch{ switch {
// Color of the selected text
texton-color: #002aff; texton-color: #002aff;
// Color of the unselected text textoff-color: silver;
textoff-color: silver;
text-padding: 20px; text-padding: 20px;
font-size: 50px; font-size: 50px;
} }
``` ```
``` ```js
// xxx.js // xxx.js
import prompt from '@system.prompt'; import prompt from '@system.prompt';
export default { export default {
...@@ -84,7 +83,8 @@ export default { ...@@ -84,7 +83,8 @@ export default {
![en-us_image_0000001276003505](figures/en-us_image_0000001276003505.gif) ![en-us_image_0000001276003505](figures/en-us_image_0000001276003505.gif)
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE:** > **NOTE**
>
> The text set by **texton** and **textoff** takes effect only when **showtext** is set to **true**. > The text set by **texton** and **textoff** takes effect only when **showtext** is set to **true**.
...@@ -94,7 +94,7 @@ Turn on the switch and the default delivery address is used. When the switch is ...@@ -94,7 +94,7 @@ Turn on the switch and the default delivery address is used. When the switch is
Implementation method: Create a **&lt;switch&gt;** component, set the **checked** attribute to **true**, and change the delivery address through data binding. Set the **display** attribute (the default value is **none**). When the switch is turned off and the **display** attribute is set to **flex**, the address module is displayed and clicking the button can change the color. Implementation method: Create a **&lt;switch&gt;** component, set the **checked** attribute to **true**, and change the delivery address through data binding. Set the **display** attribute (the default value is **none**). When the switch is turned off and the **display** attribute is set to **flex**, the address module is displayed and clicking the button can change the color.
``` ```html
<!-- xxx.hml --> <!-- xxx.hml -->
<div class="container"> <div class="container">
<div class="change"> <div class="change">
...@@ -113,11 +113,11 @@ Turn on the switch and the default delivery address is used. When the switch is ...@@ -113,11 +113,11 @@ Turn on the switch and the default delivery address is used. When the switch is
``` ```
``` ```css
/* xxx.css */ /* xxx.css */
.container { .container {
width: 100%; width: 100%;
height: 100%; height: 100%;
background-color: #F1F3F5; background-color: #F1F3F5;
flex-direction: column; flex-direction: column;
padding: 50px; padding: 50px;
...@@ -168,7 +168,7 @@ switch{ ...@@ -168,7 +168,7 @@ switch{
``` ```
``` ```js
// xxx.js // xxx.js
import prompt from '@system.prompt'; import prompt from '@system.prompt';
export default { export default {
......
...@@ -11,7 +11,6 @@ ...@@ -11,7 +11,6 @@
- Development Fundamentals - Development Fundamentals
- [Application Package Structure Configuration File (FA Model)](quick-start/package-structure.md) - [Application Package Structure Configuration File (FA Model)](quick-start/package-structure.md)
- [Application Package Structure Configuration File (Stage Model)](quick-start/stage-structure.md) - [Application Package Structure Configuration File (Stage Model)](quick-start/stage-structure.md)
- [Resource File Categories](quick-start/basic-resource-file-categories.md)
- [SysCap](quick-start/syscap.md) - [SysCap](quick-start/syscap.md)
- Development - Development
- Ability Development - Ability Development
...@@ -43,12 +42,11 @@ ...@@ -43,12 +42,11 @@
- [Rules for Accessing Application Code Files](ui/ts-framework-file-access-rules.md) - [Rules for Accessing Application Code Files](ui/ts-framework-file-access-rules.md)
- ["js" Tag](ui/ts-framework-js-tag.md) - ["js" Tag](ui/ts-framework-js-tag.md)
- Resource Access - Resource Access
- [Accessing Application Resources](ui/ts-application-resource-access.md) - [Resource File Categories](ui/ui-ts-basic-resource-file-categories.md)
- [Accessing System Resources](ui/ts-system-resource-access.md) - [Accessing Application Resources](ui/ts-resource-access.md)
- [Media Resource Types](ui/ts-media-resource-type.md)
- [Pixel Units](ui/ts-pixel-units.md) - [Pixel Units](ui/ts-pixel-units.md)
- [Types](ui/ts-types.md)
- Declarative Syntax - Declarative Syntax
- [Overview](ui/ts-syntax-intro.md) - [Overview](ui/ts-syntax-intro.md)
- General UI Description Specifications - General UI Description Specifications
- [Basic Concepts](ui/ts-general-ui-concepts.md) - [Basic Concepts](ui/ts-general-ui-concepts.md)
...@@ -180,11 +178,11 @@ ...@@ -180,11 +178,11 @@
- [Custom Components](ui/ui-js-custom-components.md) - [Custom Components](ui/ui-js-custom-components.md)
- Common Event and Notification - Common Event and Notification
- [Common Event and Notification Overview](notification/notification-brief.md) - [Common Event and Notification Overview](notification/notification-brief.md)
- Common Event - [Common Event Development](notification/common-event.md)
- [Common Event Development](notification/common-event.md) - [Notification Development](notification/notification-guidelines.md)
- Notification - Agent-Powered Scheduled Reminder
- [Notification Development](notification/notification.md) - [Agent-Powered Scheduled Reminder Overview](notification/background-agent-scheduled-reminder-overview.md)
- Debugging Tools - [Agent-Powered Scheduled Reminder Development](notification/background-agent-scheduled-reminder-guide.md)
- [Debugging Assistant Usage](notification/assistant-guidelines.md) - [Debugging Assistant Usage](notification/assistant-guidelines.md)
- Window Manager - Window Manager
- Window - Window
...@@ -212,6 +210,10 @@ ...@@ -212,6 +210,10 @@
- Image - Image
- [Image Development](media/image.md) - [Image Development](media/image.md)
- Security - Security
- Access Control
- [Access Control Overview](security/accesstoken-overview.md)
- [Access Control Development](security/accesstoken-guidelines.md)
- [Permission List](security/permission-list.md)
- User Authentication - User Authentication
- [User Authentication Overview](security/userauth-overview.md) - [User Authentication Overview](security/userauth-overview.md)
- [User Authentication Development](security/userauth-guidelines.md) - [User Authentication Development](security/userauth-guidelines.md)
...@@ -220,9 +222,6 @@ ...@@ -220,9 +222,6 @@
- [HUKS Development](security/huks-guidelines.md) - [HUKS Development](security/huks-guidelines.md)
- hapsigner - hapsigner
- [hapsigner Guide](security/hapsigntool-guidelines.md) - [hapsigner Guide](security/hapsigntool-guidelines.md)
- Access Control
- [Access Control Overview](security/accesstoken-overview.md)
- [Access Control Development](security/accesstoken-guidelines.md)
- Connectivity - Connectivity
- Network Management - Network Management
- [Network Management Overview](connectivity/net-mgmt-overview.md) - [Network Management Overview](connectivity/net-mgmt-overview.md)
...@@ -250,15 +249,13 @@ ...@@ -250,15 +249,13 @@
- Distributed Data Object - Distributed Data Object
- [Distributed Data Object Overview](database/database-distributedobject-overview.md) - [Distributed Data Object Overview](database/database-distributedobject-overview.md)
- [Distributed Data Object Development](database/database-distributedobject-guidelines.md) - [Distributed Data Object Development](database/database-distributedobject-guidelines.md)
- Agent-Powered Scheduled Reminders - Task Management
- [Agent-Powered Scheduled Reminder Overview](background-agent-scheduled-reminder/background-agent-scheduled-reminder-overview.md) - Background Task Management
- [Agent-Powered Scheduled Reminder Development](background-agent-scheduled-reminder/background-agent-scheduled-reminder-guide.md) - [Background Task Management Overview](background-task-management/background-task-overview.md)
- Background Task Management - [Background Task Management Development](background-task-management/background-task-dev-guide.md)
- [Background Task Management Overview](background-task-management/background-task-overview.md) - Work Scheduler
- [Background Task Management Development](background-task-management/background-task-dev-guide.md) - [Work Scheduler Overview](task-management/work-scheduler-overview.md)
- Work Scheduler - [Work Scheduler Development](task-management/work-scheduler-dev-guide.md)
- [Work Scheduler Overview](work-scheduler/work-scheduler-overview.md)
- [Work Scheduler Development](work-scheduler/work-scheduler-dev-guide.md)
- Device - Device
- USB Service - USB Service
- [USB Service Overview](device/usb-overview.md) - [USB Service Overview](device/usb-overview.md)
...@@ -292,7 +289,10 @@ ...@@ -292,7 +289,10 @@
- [Internationalization Development (i18n)](internationalization/i18n-guidelines.md) - [Internationalization Development (i18n)](internationalization/i18n-guidelines.md)
- Native APIs - Native APIs
- [Using Native APIs in Application Projects](napi/napi-guidelines.md) - [Using Native APIs in Application Projects](napi/napi-guidelines.md)
- Tools - [Drawing Development](napi/drawing-guidelines.md)
- [Raw File Development](napi/rawfile-guidelines.md)
- [NativeWindow Development](napi/native-window-guidelines.md)
- Tools
- [DevEco Studio (OpenHarmony) User Guide](quick-start/deveco-studio-user-guide-for-openharmony.md) - [DevEco Studio (OpenHarmony) User Guide](quick-start/deveco-studio-user-guide-for-openharmony.md)
- Hands-On Tutorials - Hands-On Tutorials
- [Samples](https://gitee.com/openharmony/app_samples/blob/master/README.md) - [Samples](https://gitee.com/openharmony/app_samples/blob/master/README.md)
...@@ -562,8 +562,8 @@ ...@@ -562,8 +562,8 @@
- [@ohos.application.formError](reference/apis/js-apis-formerror.md) - [@ohos.application.formError](reference/apis/js-apis-formerror.md)
- [@ohos.application.formHost](reference/apis/js-apis-formhost.md) - [@ohos.application.formHost](reference/apis/js-apis-formhost.md)
- [@ohos.application.formInfo](reference/apis/js-apis-formInfo.md) - [@ohos.application.formInfo](reference/apis/js-apis-formInfo.md)
- [@ohos.application.missionManager](reference/apis/js-apis-missionManager.md)
- [@ohos.application.formProvider](reference/apis/js-apis-formprovider.md) - [@ohos.application.formProvider](reference/apis/js-apis-formprovider.md)
- [@ohos.application.missionManager](reference/apis/js-apis-missionManager.md)
- [@ohos.ability.particleAbility](reference/apis/js-apis-particleAbility.md) - [@ohos.ability.particleAbility](reference/apis/js-apis-particleAbility.md)
- [@ohos.application.ServiceExtensionAbility](reference/apis/js-apis-service-extension-ability.md) - [@ohos.application.ServiceExtensionAbility](reference/apis/js-apis-service-extension-ability.md)
- [@ohos.application.StartOptions](reference/apis/js-apis-application-StartOptions.md) - [@ohos.application.StartOptions](reference/apis/js-apis-application-StartOptions.md)
...@@ -575,19 +575,23 @@ ...@@ -575,19 +575,23 @@
- [AbilityContext](reference/apis/js-apis-ability-context.md) - [AbilityContext](reference/apis/js-apis-ability-context.md)
- [abilityDelegator](reference/apis/js-apis-application-abilityDelegator.md) - [abilityDelegator](reference/apis/js-apis-application-abilityDelegator.md)
- [abilityDelegatorArgs](reference/apis/js-apis-application-abilityDelegatorArgs.md) - [abilityDelegatorArgs](reference/apis/js-apis-application-abilityDelegatorArgs.md)
- [AbilityManager](reference/apis/js-apis-abilityManager.md)
- [abilityMonitor](reference/apis/js-apis-application-abilityMonitor.md) - [abilityMonitor](reference/apis/js-apis-application-abilityMonitor.md)
- [AbilityRunningInfo](reference/apis/js-apis-abilityrunninginfo.md) - [AbilityRunningInfo](reference/apis/js-apis-abilityrunninginfo.md)
- [AbilityStageContext](reference/apis/js-apis-abilitystagecontext.md) - [AbilityStageContext](reference/apis/js-apis-abilitystagecontext.md)
- [Context](reference/apis/js-apis-application-context.md) - [Context](reference/apis/js-apis-application-context.md)
- [ExtensionAbilityContext](reference/apis/js-apis-extension-ability-context.md)
- [ExtensionAbilityInfo](reference/apis/js-apis-extensionAbilityInfo.md)
- [ExtensionContext](reference/apis/js-apis-extension-context.md) - [ExtensionContext](reference/apis/js-apis-extension-context.md)
- [ExtensionRunningInfo](reference/apis/js-apis-extensionrunninginfo.md) - [ExtensionRunningInfo](reference/apis/js-apis-extensionrunninginfo.md)
- [FormExtensionContext](reference/apis/js-apis-formextensioncontext.md) - [FormExtensionContext](reference/apis/js-apis-formextensioncontext.md)
- [MissionInfo](reference/apis/js-apis-application-missionInfo.md)
- [MissionSnapshot](reference/apis/js-apis-application-MissionSnapshot.md) - [MissionSnapshot](reference/apis/js-apis-application-MissionSnapshot.md)
- [PermissionRequestResult](reference/apis/js-apis-permissionrequestresult.md) - [PermissionRequestResult](reference/apis/js-apis-permissionrequestresult.md)
- [ProcessRunningInfo](reference/apis/js-apis-processrunninginfo.md) - [ProcessRunningInfo](reference/apis/js-apis-processrunninginfo.md)
- [ServiceExtAbilityContext](reference/apis/js-apis-serviceExtAbilityContext.md)
- [ServiceExtensionContext](reference/apis/js-apis-service-extension-context.md) - [ServiceExtensionContext](reference/apis/js-apis-service-extension-context.md)
- [shellCmdResult](reference/apis/js-apis-application-shellCmdResult.md) - [shellCmdResult](reference/apis/js-apis-application-shellCmdResult.md)
- [AbilityStageContext](reference/apis/js-apis-abilityStageContext.md)
- Common Event and Notification - Common Event and Notification
- [@ohos.commonEvent](reference/apis/js-apis-commonEvent.md) - [@ohos.commonEvent](reference/apis/js-apis-commonEvent.md)
- [@ohos.events.emitter](reference/apis/js-apis-emitter.md) - [@ohos.events.emitter](reference/apis/js-apis-emitter.md)
...@@ -598,6 +602,14 @@ ...@@ -598,6 +602,14 @@
- [@ohos.bundle](reference/apis/js-apis-Bundle.md) - [@ohos.bundle](reference/apis/js-apis-Bundle.md)
- [@ohos.bundleState ](reference/apis/js-apis-deviceUsageStatistics.md) - [@ohos.bundleState ](reference/apis/js-apis-deviceUsageStatistics.md)
- [@ohos.zlib](reference/apis/js-apis-zlib.md) - [@ohos.zlib](reference/apis/js-apis-zlib.md)
- [AbilityInfo](reference/apis/js-apis-bundle-AbilityInfo.md)
- [ApplicationInfo](reference/apis/js-apis-bundle-ApplicationInfo.md)
- [BundleInfo](reference/apis/js-apis-bundle-BundleInfo.md)
- [CustomizeData](reference/apis/js-apis-bundle-CustomizeData.md)
- [ExtensionAbilityInfo](reference/apis/js-apis-bundle-ExtensionAbilityInfo.md)
- [HapModuleInfo](reference/apis/js-apis-bundle-HapModuleInfo.md)
- [Metadata](reference/apis/js-apis-bundle-Metadata.md)
- [ModuleInfo](reference/apis/js-apis-bundle-ModuleInfo.md)
- UI Page - UI Page
- [@ohos.animator](reference/apis/js-apis-animator.md) - [@ohos.animator](reference/apis/js-apis-animator.md)
- [@ohos.mediaquery](reference/apis/js-apis-mediaquery.md) - [@ohos.mediaquery](reference/apis/js-apis-mediaquery.md)
...@@ -611,7 +623,6 @@ ...@@ -611,7 +623,6 @@
- [webgl2](reference/apis/js-apis-webgl2.md) - [webgl2](reference/apis/js-apis-webgl2.md)
- Media - Media
- [@ohos.multimedia.audio](reference/apis/js-apis-audio.md) - [@ohos.multimedia.audio](reference/apis/js-apis-audio.md)
- [@ohos.multimedia.camera](reference/apis/js-apis-camera.md)
- [@ohos.multimedia.image](reference/apis/js-apis-image.md) - [@ohos.multimedia.image](reference/apis/js-apis-image.md)
- [@ohos.multimedia.media](reference/apis/js-apis-media.md) - [@ohos.multimedia.media](reference/apis/js-apis-media.md)
- [@ohos.multimedia.medialibrary](reference/apis/js-apis-medialibrary.md) - [@ohos.multimedia.medialibrary](reference/apis/js-apis-medialibrary.md)
...@@ -635,7 +646,6 @@ ...@@ -635,7 +646,6 @@
- [@ohos.data.distributedData](reference/apis/js-apis-distributed-data.md) - [@ohos.data.distributedData](reference/apis/js-apis-distributed-data.md)
- [@ohos.data.distributedDataObject](reference/apis/js-apis-data-distributedobject.md) - [@ohos.data.distributedDataObject](reference/apis/js-apis-data-distributedobject.md)
- [@ohos.data.rdb](reference/apis/js-apis-data-rdb.md) - [@ohos.data.rdb](reference/apis/js-apis-data-rdb.md)
- [@ohos.settings](reference/apis/js-apis-settings.md)
- [@ohos.data.storage](reference/apis/js-apis-data-storage.md) - [@ohos.data.storage](reference/apis/js-apis-data-storage.md)
- [resultSet](reference/apis/js-apis-data-resultset.md) - [resultSet](reference/apis/js-apis-data-resultset.md)
- File Management - File Management
...@@ -643,6 +653,7 @@ ...@@ -643,6 +653,7 @@
- [@ohos.environment](reference/apis/js-apis-environment.md) - [@ohos.environment](reference/apis/js-apis-environment.md)
- [@ohos.fileio](reference/apis/js-apis-fileio.md) - [@ohos.fileio](reference/apis/js-apis-fileio.md)
- [@ohos.fileManager](reference/apis/js-apis-filemanager.md) - [@ohos.fileManager](reference/apis/js-apis-filemanager.md)
- [@ohos.securityLabel](reference/apis/js-apis-securityLabel.md)
- [@ohos.statfs](reference/apis/js-apis-statfs.md) - [@ohos.statfs](reference/apis/js-apis-statfs.md)
- [@ohos.storageStatistics](reference/apis/js-apis-storage-statistics.md) - [@ohos.storageStatistics](reference/apis/js-apis-storage-statistics.md)
- [@ohos.volumeManager](reference/apis/js-apis-volumemanager.md) - [@ohos.volumeManager](reference/apis/js-apis-volumemanager.md)
...@@ -657,12 +668,15 @@ ...@@ -657,12 +668,15 @@
- Network Management - Network Management
- [@ohos.net.connection](reference/apis/js-apis-net-connection.md) - [@ohos.net.connection](reference/apis/js-apis-net-connection.md)
- [@ohos.net.http](reference/apis/js-apis-http.md) - [@ohos.net.http](reference/apis/js-apis-http.md)
- [@ohos.request](reference/apis/js-apis-request.md)
- [@ohos.net.socket](reference/apis/js-apis-socket.md) - [@ohos.net.socket](reference/apis/js-apis-socket.md)
- [@ohos.net.webSocket](reference/apis/js-apis-webSocket.md) - [@ohos.net.webSocket](reference/apis/js-apis-webSocket.md)
- [@ohos.request](reference/apis/js-apis-request.md)
- Connectivity - Connectivity
- [@ohos.bluetooth](reference/apis/js-apis-bluetooth.md) - [@ohos.bluetooth](reference/apis/js-apis-bluetooth.md)
- [@ohos.connectedTag](reference/apis/js-apis-connectedTag.md) - [@ohos.connectedTag](reference/apis/js-apis-connectedTag.md)
- [@ohos.nfc.cardEmulation](reference/apis/js-apis-cardEmulation.md)
- [@ohos.nfc.controller](reference/apis/js-apis-nfcController.md)
- [@ohos.nfc.tag](reference/apis/js-apis-nfcTag.md)
- [@ohos.rpc](reference/apis/js-apis-rpc.md) - [@ohos.rpc](reference/apis/js-apis-rpc.md)
- [@ohos.wifi](reference/apis/js-apis-wifi.md) - [@ohos.wifi](reference/apis/js-apis-wifi.md)
- [@ohos.wifiext](reference/apis/js-apis-wifiext.md) - [@ohos.wifiext](reference/apis/js-apis-wifiext.md)
...@@ -681,6 +695,7 @@ ...@@ -681,6 +695,7 @@
- [@ohos.screenLock](reference/apis/js-apis-screen-lock.md) - [@ohos.screenLock](reference/apis/js-apis-screen-lock.md)
- [@ohos.systemTime](reference/apis/js-apis-system-time.md) - [@ohos.systemTime](reference/apis/js-apis-system-time.md)
- [@ohos.wallpaper](reference/apis/js-apis-wallpaper.md) - [@ohos.wallpaper](reference/apis/js-apis-wallpaper.md)
- [console](reference/apis/js-apis-logs.md)
- [Timer](reference/apis/js-apis-timer.md) - [Timer](reference/apis/js-apis-timer.md)
- Device Management - Device Management
- [@ohos.batteryInfo ](reference/apis/js-apis-battery-info.md) - [@ohos.batteryInfo ](reference/apis/js-apis-battery-info.md)
...@@ -695,6 +710,7 @@ ...@@ -695,6 +710,7 @@
- [@ohos.power](reference/apis/js-apis-power.md) - [@ohos.power](reference/apis/js-apis-power.md)
- [@ohos.runningLock](reference/apis/js-apis-runninglock.md) - [@ohos.runningLock](reference/apis/js-apis-runninglock.md)
- [@ohos.sensor](reference/apis/js-apis-sensor.md) - [@ohos.sensor](reference/apis/js-apis-sensor.md)
- [@ohos.settings](reference/apis/js-apis-settings.md)
- [@ohos.systemParameter](reference/apis/js-apis-system-parameter.md) - [@ohos.systemParameter](reference/apis/js-apis-system-parameter.md)
- [@ohos.thermal](reference/apis/js-apis-thermal.md) - [@ohos.thermal](reference/apis/js-apis-thermal.md)
- [@ohos.update](reference/apis/js-apis-update.md) - [@ohos.update](reference/apis/js-apis-update.md)
...@@ -751,4 +767,3 @@ ...@@ -751,4 +767,3 @@
- [@system.sensor](reference/apis/js-apis-system-sensor.md) - [@system.sensor](reference/apis/js-apis-system-sensor.md)
- [@system.storage](reference/apis/js-apis-system-storage.md) - [@system.storage](reference/apis/js-apis-system-storage.md)
- [@system.vibrator](reference/apis/js-apis-system-vibrate.md) - [@system.vibrator](reference/apis/js-apis-system-vibrate.md)
- [console](reference/apis/js-apis-logs.md)
\ No newline at end of file
# UART<a name="EN-US_TOPIC_0000001160652800"></a> # UART
## Overview<a name="section833012453535"></a>
The Universal Asynchronous Receiver/Transmitter \(UART\) is a universal serial data bus used for asynchronous communication. It enables bi-directional communication between devices in full-duplex mode. ## Overview
The Universal Asynchronous Receiver/Transmitter (UART) is a universal serial data bus used for asynchronous communication. It enables bi-directional communication between devices in full-duplex mode.
UART is widely used to print information for debugging or to connect to various external modules such as GPS and Bluetooth. UART is widely used to print information for debugging or to connect to various external modules such as GPS and Bluetooth.
A UART is connected to other modules through two wires \(as shown in [Figure 1](#fig68294715408)\) or four wires \(as shown in [Figure 2](#fig179241542163112)\).
- TX: TX pin of the transmitting UART. It is connected to the RX pin of the peer UART. A UART is connected to other modules through two wires (as shown in Figure 1) or four wires (as shown in Figure 2).
- RX: RX pin of the receiving UART. It is connected to the TX pin of the peer UART. - TX: TX pin of the transmitting UART. It is connected to the RX pin of the peer UART.
- RTS: Request to Send signal pin. It is connected to the CTS pin of the peer UART and is used to indicate whether the local UART is ready to receive data. - RX: RX pin of the receiving UART. It is connected to the TX pin of the peer UART.
- CTS: Clear to Send signal pin. It is connected to the RTS pin of the peer UART and is used to indicate whether the local UART is allowed to send data to the peer end. - RTS: Request to Send signal pin. It is connected to the CTS pin of the peer UART and is used to indicate whether the local UART is ready to receive data.
- CTS: Clear to Send signal pin. It is connected to the RTS pin of the peer UART and is used to indicate whether the local UART is allowed to send data to the peer end.
**Figure 1** 2-wire UART communication<a name="fig68294715408"></a>
![](figures/2-wire-uart-communication.png "2-wire-uart-communication") **Figure 1** Two-wire UART communication
**Figure 2** 4-wire UART communication<a name="fig179241542163112"></a> ![](figures/2-wire-uart-communication.png "2-wire-uart-communication")
![](figures/4-wire-uart-communication.png "4-wire-uart-communication")
**Figure 2** Four-wire UART communication
The transmitting and receiving UARTs must ensure that they have the same settings on particular attributes such as the baud rate and data format \(start bit, data bit, parity bit, and stop bit\) before they start to communicate. During data transmission, a UART sends data to the peer end over the TX pin and receives data from the peer end over the RX pin. When the size of the buffer used by a UART for storing received data reaches the preset threshold, the RTS signal of the UART changes to **1** \(data cannot be received\), and the peer UART stops sending data to it because its CTS signal does not allow it to send data. ![](figures/4-wire-uart-communication.png "4-wire-uart-communication")
- The transmitting and receiving UARTs must ensure that they have the same settings on particular attributes such as the baud rate and data format (start bit, data bit, parity bit, and stop bit) before they start to communicate. During data transmission, a UART sends data to the peer end over the TX pin and receives data from the peer end over the RX pin. When the size of the buffer used by a UART for storing received data reaches the preset threshold, the RTS signal of the UART changes to **1** (data cannot be received), and the peer UART stops sending data to it because its CTS signal does not allow it to send data.
## Available APIs<a name="section1928742202715"></a>
- The UART interface defines a set of common functions for operating a UART port, including obtaining and releasing device handles, reading and writing data of a specified length, and obtaining and setting the baud rate, as well as the device attributes.
The UART interface defines a set of common functions for operating a UART port, including obtaining and releasing device handles, reading and writing data of a specified length, and obtaining and setting the baud rate, as well as the device attributes.
**Table 1** APIs for the UART driver ## Available APIs
<a name="table1731550155318"></a> **Table 1** UART driver APIs
<table><thead align="left"><tr id="row1223152681611"><th class="cellrowborder" valign="top" width="26.619999999999997%" id="mcps1.2.4.1.1"><p id="p210413571619"><a name="p210413571619"></a><a name="p210413571619"></a><strong id="b4100105545211"><a name="b4100105545211"></a><a name="b4100105545211"></a>Capability</strong></p>
</th> | API| Description|
<th class="cellrowborder" valign="top" width="31.369999999999997%" id="mcps1.2.4.1.2"><p id="p810403511614"><a name="p810403511614"></a><a name="p810403511614"></a><strong id="b1653121711186"><a name="b1653121711186"></a><a name="b1653121711186"></a>Function</strong></p> | -------- | -------- |
</th> | UartOpen | Obtains a UART device handle.|
<th class="cellrowborder" valign="top" width="42.01%" id="mcps1.2.4.1.3"><p id="p110418354161"><a name="p110418354161"></a><a name="p110418354161"></a><strong id="b69108168153412"><a name="b69108168153412"></a><a name="b69108168153412"></a>Description</strong></p> | UartClose | Releases a UART device handle.|
</th> | UartRead | Reads data of the specified length from a UART device.|
</tr> | UartWrite | Writes data of the specified length to a UART device.|
</thead> | UartGetBaud | Obtains the UART baud rate.|
<tbody><tr id="row1638573613415"><td class="cellrowborder" rowspan="2" valign="top" width="26.619999999999997%" headers="mcps1.2.4.1.1 "><p id="p917154316414"><a name="p917154316414"></a><a name="p917154316414"></a>Obtaining and releasing device handles</p> | UartSetBaud | Sets the UART baud rate.|
<p id="p9596111154212"><a name="p9596111154212"></a><a name="p9596111154212"></a></p> | UartGetAttribute | Obtains UART device attributes.|
</td> | UartSetAttribute | Sets UART device attributes.|
<td class="cellrowborder" valign="top" width="31.369999999999997%" headers="mcps1.2.4.1.2 "><p id="p20385163614412"><a name="p20385163614412"></a><a name="p20385163614412"></a>UartOpen</p> | UartSetTransMode | Sets the UART transmission mode.|
</td>
<td class="cellrowborder" valign="top" width="42.01%" headers="mcps1.2.4.1.3 "><p id="p12101135184213"><a name="p12101135184213"></a><a name="p12101135184213"></a>Obtains the UART device handle.</p> > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br>
</td> > All APIs described in this document can be called only in kernel mode.
</tr>
<tr id="row5950143316415"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p149501733134113"><a name="p149501733134113"></a><a name="p149501733134113"></a>UartClose</p>
</td> ## Usage Guidelines
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p371073520422"><a name="p371073520422"></a><a name="p371073520422"></a>Releases a specified UART device handle.</p>
</td>
</tr> ### How to Use
<tr id="row34145016535"><td class="cellrowborder" rowspan="2" valign="top" width="26.619999999999997%" headers="mcps1.2.4.1.1 "><p id="p229610227124"><a name="p229610227124"></a><a name="p229610227124"></a>Reading and writing data</p>
<p id="p131072201215"><a name="p131072201215"></a><a name="p131072201215"></a></p>
</td>
<td class="cellrowborder" valign="top" width="31.369999999999997%" headers="mcps1.2.4.1.2 "><p id="p8296182221219"><a name="p8296182221219"></a><a name="p8296182221219"></a>UartRead</p>
</td>
<td class="cellrowborder" valign="top" width="42.01%" headers="mcps1.2.4.1.3 "><p id="p16297172213125"><a name="p16297172213125"></a><a name="p16297172213125"></a>Reads data of a specified length from a UART device.</p>
</td>
</tr>
<tr id="row11585016539"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p1095722493616"><a name="p1095722493616"></a><a name="p1095722493616"></a>UartWrite</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p15297162215122"><a name="p15297162215122"></a><a name="p15297162215122"></a>Writes data of a specified length into a UART device.</p>
</td>
</tr>
<tr id="row8687115843715"><td class="cellrowborder" rowspan="2" valign="top" width="26.619999999999997%" headers="mcps1.2.4.1.1 "><p id="p196317143813"><a name="p196317143813"></a><a name="p196317143813"></a>Obtaining and setting the baud rate</p>
</td>
<td class="cellrowborder" valign="top" width="31.369999999999997%" headers="mcps1.2.4.1.2 "><p id="p166885582375"><a name="p166885582375"></a><a name="p166885582375"></a>UartGetBaud</p>
</td>
<td class="cellrowborder" valign="top" width="42.01%" headers="mcps1.2.4.1.3 "><p id="p13688358183716"><a name="p13688358183716"></a><a name="p13688358183716"></a>Obtains the UART baud rate.</p>
</td>
</tr>
<tr id="row18987529382"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p698719214383"><a name="p698719214383"></a><a name="p698719214383"></a>UartSetBaud</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p1398712123810"><a name="p1398712123810"></a><a name="p1398712123810"></a>Sets the UART baud rate.</p>
</td>
</tr>
<tr id="row1551850115317"><td class="cellrowborder" rowspan="2" valign="top" width="26.619999999999997%" headers="mcps1.2.4.1.1 "><p id="p1629782201218"><a name="p1629782201218"></a><a name="p1629782201218"></a>Obtaining and setting device attributes</p>
<p id="p10308192211216"><a name="p10308192211216"></a><a name="p10308192211216"></a></p>
</td>
<td class="cellrowborder" valign="top" width="31.369999999999997%" headers="mcps1.2.4.1.2 "><p id="p32972022151218"><a name="p32972022151218"></a><a name="p32972022151218"></a>UartGetAttribute</p>
</td>
<td class="cellrowborder" valign="top" width="42.01%" headers="mcps1.2.4.1.3 "><p id="p13297122216123"><a name="p13297122216123"></a><a name="p13297122216123"></a>Obtains the UART device attributes.</p>
</td>
</tr>
<tr id="row7545065311"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p102974224120"><a name="p102974224120"></a><a name="p102974224120"></a>UartSetAttribute</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p152971322111219"><a name="p152971322111219"></a><a name="p152971322111219"></a>Sets the UART device attributes.</p>
</td>
</tr>
<tr id="row14614115403"><td class="cellrowborder" valign="top" width="26.619999999999997%" headers="mcps1.2.4.1.1 "><p id="p1746281144010"><a name="p1746281144010"></a><a name="p1746281144010"></a>Setting the transmission mode</p>
</td>
<td class="cellrowborder" valign="top" width="31.369999999999997%" headers="mcps1.2.4.1.2 "><p id="p1146215112405"><a name="p1146215112405"></a><a name="p1146215112405"></a>UartSetTransMode</p>
</td>
<td class="cellrowborder" valign="top" width="42.01%" headers="mcps1.2.4.1.3 "><p id="p11303181216414"><a name="p11303181216414"></a><a name="p11303181216414"></a>Sets the UART transmission mode.</p>
</td>
</tr>
</tbody>
</table>
>![](../public_sys-resources/icon-note.gif) **NOTE**<br>
>All functions provided in this document can be called only in kernel space.
## Usage Guidelines<a name="section12779050105412"></a>
### How to Use<a name="section1858116395510"></a>
The figure below illustrates how to use the APIs. The figure below illustrates how to use the APIs.
**Figure 3** Using UART driver APIs<a name="fig99673244388"></a> **Figure 3** Using UART driver APIs
![](figures/using-uart-process.png "process-of-using-a-uart-device")
![](figures/using-UART-process.png)
### Obtaining a UART Device Handle<a name="section124512065617"></a>
Before performing UART communication, call **UartOpen** to obtain a UART device handle. This function returns the pointer to the UART device handle with a specified port number. ### Opening a UART Device Handle
DevHandle UartOpen\(uint32\_t port\); Before performing UART communication, call **UartOpen** to obtain a UART device handle. This function returns the pointer to the UART device handle with the specified port number.
**Table 2** Description of UartOpen
```
<a name="table14222165114310"></a> DevHandle UartOpen(uint32_t port);
<table><thead align="left"><tr id="row1022175133111"><th class="cellrowborder" valign="top" width="50%" id="mcps1.2.3.1.1"><p id="p13221551153117"><a name="p13221551153117"></a><a name="p13221551153117"></a><strong id="b538194163718"><a name="b538194163718"></a><a name="b538194163718"></a>Parameter</strong></p> ```
</th>
<th class="cellrowborder" valign="top" width="50%" id="mcps1.2.3.1.2"><p id="p122211251103111"><a name="p122211251103111"></a><a name="p122211251103111"></a><strong id="b20924204203714"><a name="b20924204203714"></a><a name="b20924204203714"></a>Description</strong></p> **Table 2** Description of UartOpen
</th>
</tr> | Parameter| Description|
</thead> | -------- | -------- |
<tbody><tr id="row6222451133114"><td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.1 "><p id="p92221518315"><a name="p92221518315"></a><a name="p92221518315"></a>port</p> | port | UART port number.|
</td> | **Return Value**| **Description**|
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.2 "><p id="p1322217518318"><a name="p1322217518318"></a><a name="p1322217518318"></a>UART port number.</p> | NULL | The operation failed.|
</td> | Device handle| The operation is successful. The obtained UART device handle is returned.|
</tr>
<tr id="row1122245153112"><td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.1 "><p id="p102221451123118"><a name="p102221451123118"></a><a name="p102221451123118"></a><strong id="b101754483378"><a name="b101754483378"></a><a name="b101754483378"></a>Return Value</strong></p> Example: Obtain the device handle of UART port 3.
</td>
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.2 "><p id="p1122215143113"><a name="p1122215143113"></a><a name="p1122215143113"></a><strong id="b647184919374"><a name="b647184919374"></a><a name="b647184919374"></a>Description</strong></p> ```
</td> DevHandle handle = NULL; /* UART device handle */
</tr> uint32_t port = 3; /* UART port number */
<tr id="row522275114317"><td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.1 "><p id="p422235114313"><a name="p422235114313"></a><a name="p422235114313"></a>NULL</p>
</td>
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.2 "><p id="p5222351203112"><a name="p5222351203112"></a><a name="p5222351203112"></a>Failed to obtain the UART device handle.</p>
</td>
</tr>
<tr id="row1222212513311"><td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.1 "><p id="p5222125115316"><a name="p5222125115316"></a><a name="p5222125115316"></a>Device handle</p>
</td>
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.2 "><p id="p192228515311"><a name="p192228515311"></a><a name="p192228515311"></a>UART device handle.</p>
</td>
</tr>
</tbody>
</table>
The following example shows how to obtain a UART device handle based on the assumption that the UART port number is **3**:
```
DevHandle handle = NULL; /* The UART device handle */
uint32_t port = 3; /* UART port number */
handle = UartOpen(port); handle = UartOpen(port);
if (handle == NULL) { if (handle == NULL) {
HDF_LOGE("UartOpen: failed!\n"); HDF_LOGE("UartOpen: failed!\n");
...@@ -158,51 +88,29 @@ if (handle == NULL) { ...@@ -158,51 +88,29 @@ if (handle == NULL) {
} }
``` ```
### Setting the UART Baud Rate<a name="section86881004579"></a>
After obtaining the UART device handle, set the UART baud rate by calling the following function:
int32\_t UartSetBaud\(DevHandle handle, uint32\_t baudRate\);
**Table 3** Description of UartSetBaud
<a name="table539135313325"></a>
<table><thead align="left"><tr id="row15391205311323"><th class="cellrowborder" valign="top" width="50%" id="mcps1.2.3.1.1"><p id="p11390453103216"><a name="p11390453103216"></a><a name="p11390453103216"></a><strong id="b0704124143717"><a name="b0704124143717"></a><a name="b0704124143717"></a>Parameter</strong></p>
</th>
<th class="cellrowborder" valign="top" width="50%" id="mcps1.2.3.1.2"><p id="p839065316328"><a name="p839065316328"></a><a name="p839065316328"></a><strong id="b10127164520376"><a name="b10127164520376"></a><a name="b10127164520376"></a>Description</strong></p>
</th>
</tr>
</thead>
<tbody><tr id="row2039115373216"><td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.1 "><p id="p1639165310324"><a name="p1639165310324"></a><a name="p1639165310324"></a>handle</p>
</td>
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.2 "><p id="p539115320328"><a name="p539115320328"></a><a name="p539115320328"></a>UART device handle.</p>
</td>
</tr>
<tr id="row163911753143214"><td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.1 "><p id="p13911653203215"><a name="p13911653203215"></a><a name="p13911653203215"></a>baudRate</p>
</td>
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.2 "><p id="p163919537322"><a name="p163919537322"></a><a name="p163919537322"></a>Baud rate of the UART to set.</p>
</td>
</tr>
<tr id="row539155343218"><td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.1 "><p id="p1039185313321"><a name="p1039185313321"></a><a name="p1039185313321"></a><strong id="b1551834812373"><a name="b1551834812373"></a><a name="b1551834812373"></a>Return Value</strong></p>
</td>
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.2 "><p id="p123911753143213"><a name="p123911753143213"></a><a name="p123911753143213"></a><strong id="b43667492373"><a name="b43667492373"></a><a name="b43667492373"></a>Description</strong></p>
</td>
</tr>
<tr id="row2391853153218"><td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.1 "><p id="p17391185310322"><a name="p17391185310322"></a><a name="p17391185310322"></a>0</p>
</td>
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.2 "><p id="p14391653193210"><a name="p14391653193210"></a><a name="p14391653193210"></a>Succeeded in setting the UART baud rate.</p>
</td>
</tr>
<tr id="row23912053143211"><td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.1 "><p id="p7391165320321"><a name="p7391165320321"></a><a name="p7391165320321"></a>Negative value</p>
</td>
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.2 "><p id="p639185318322"><a name="p639185318322"></a><a name="p639185318322"></a>Failed to set the UART baud rate.</p>
</td>
</tr>
</tbody>
</table>
The following example shows how to set the UART baud rate to **9600**:
### Setting the UART Baud Rate
Call **UartSetBaud()** to set the UART baud rate.
```
int32_t UartSetBaud(DevHandle handle, uint32_t baudRate);
```
**Table 3** Description of UartSetBaud
| Parameter| Description|
| -------- | -------- |
| handle | UART device handle.|
| baudRate | Baud rate to set.|
| **Return Value**| **Description**|
| 0 | The operation is successful.|
| Negative value| The operation failed.|
Example: Set the UART baud rate to **9600**.
``` ```
int32_t ret; int32_t ret;
/* Set the UART baud rate to 9600. */ /* Set the UART baud rate to 9600. */
...@@ -212,51 +120,29 @@ if (ret != 0) { ...@@ -212,51 +120,29 @@ if (ret != 0) {
} }
``` ```
### Obtaining the UART Baud Rate<a name="section897032965712"></a>
After setting the UART baud rate, obtain the current baud rate by calling the following function:
int32\_t UartGetBaud\(DevHandle handle, uint32\_t \*baudRate\);
**Table 4** Description of UartGetBaud
<a name="table20393185311326"></a>
<table><thead align="left"><tr id="row19392653123215"><th class="cellrowborder" valign="top" width="50%" id="mcps1.2.3.1.1"><p id="p6392105315326"><a name="p6392105315326"></a><a name="p6392105315326"></a><strong id="b13706541173716"><a name="b13706541173716"></a><a name="b13706541173716"></a>Parameter</strong></p>
</th>
<th class="cellrowborder" valign="top" width="50%" id="mcps1.2.3.1.2"><p id="p53920531329"><a name="p53920531329"></a><a name="p53920531329"></a><strong id="b15128194510378"><a name="b15128194510378"></a><a name="b15128194510378"></a>Description</strong></p>
</th>
</tr>
</thead>
<tbody><tr id="row103921553103211"><td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.1 "><p id="p1539220536326"><a name="p1539220536326"></a><a name="p1539220536326"></a>handle</p>
</td>
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.2 "><p id="p6392553203217"><a name="p6392553203217"></a><a name="p6392553203217"></a>UART device handle.</p>
</td>
</tr>
<tr id="row1539211532322"><td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.1 "><p id="p93921053123210"><a name="p93921053123210"></a><a name="p93921053123210"></a>baudRate</p>
</td>
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.2 "><p id="p93926536328"><a name="p93926536328"></a><a name="p93926536328"></a>Pointer to the UART baud rate.</p>
</td>
</tr>
<tr id="row1239318531326"><td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.1 "><p id="p17392653123213"><a name="p17392653123213"></a><a name="p17392653123213"></a><strong id="b55191048113716"><a name="b55191048113716"></a><a name="b55191048113716"></a>Return Value</strong></p>
</td>
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.2 "><p id="p1339365316327"><a name="p1339365316327"></a><a name="p1339365316327"></a><strong id="b193671249193713"><a name="b193671249193713"></a><a name="b193671249193713"></a>Description</strong></p>
</td>
</tr>
<tr id="row143939531328"><td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.1 "><p id="p2393953153213"><a name="p2393953153213"></a><a name="p2393953153213"></a>0</p>
</td>
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.2 "><p id="p8393165383218"><a name="p8393165383218"></a><a name="p8393165383218"></a>Succeeded in obtaining the UART baud rate.</p>
</td>
</tr>
<tr id="row5393105363210"><td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.1 "><p id="p17393125363215"><a name="p17393125363215"></a><a name="p17393125363215"></a>Negative value</p>
</td>
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.2 "><p id="p1539325393211"><a name="p1539325393211"></a><a name="p1539325393211"></a>Failed to obtain the UART baud rate.</p>
</td>
</tr>
</tbody>
</table>
The following example shows how to obtain the UART baud rate:
### Obtaining the UART Baud Rate
Call **UartGetBaud()** to obtain the UART baud rate.
```
int32_t UartGetBaud(DevHandle handle, uint32_t *baudRate);
```
**Table 4** Description of UartGetBaud
| Parameter| Description|
| -------- | -------- |
| handle | UART device handle.|
| baudRate | Pointer to the UART baud rate obtained.|
| **Return Value**| **Description**|
| 0 | The operation is successful.|
| Negative value| The operation failed.|
Example: Obtain the UART baud rate.
``` ```
int32_t ret; int32_t ret;
uint32_t baudRate; uint32_t baudRate;
...@@ -267,168 +153,102 @@ if (ret != 0) { ...@@ -267,168 +153,102 @@ if (ret != 0) {
} }
``` ```
### Setting the UART Device Attributes<a name="section129141884588"></a>
Before performing UART communication, set the UART device attributes by calling the following function:
int32\_t UartSetAttribute\(DevHandle handle, struct UartAttribute \*attribute\);
**Table 5** Description of UartSetAttribute
<a name="table1453119335341"></a>
<table><thead align="left"><tr id="row3530433103416"><th class="cellrowborder" valign="top" width="49.980000000000004%" id="mcps1.2.3.1.1"><p id="p1853073310341"><a name="p1853073310341"></a><a name="p1853073310341"></a><strong id="b8706441133719"><a name="b8706441133719"></a><a name="b8706441133719"></a>Parameter</strong></p>
</th>
<th class="cellrowborder" valign="top" width="50.019999999999996%" id="mcps1.2.3.1.2"><p id="p553083393417"><a name="p553083393417"></a><a name="p553083393417"></a><strong id="b16129154519371"><a name="b16129154519371"></a><a name="b16129154519371"></a>Description</strong></p>
</th>
</tr>
</thead>
<tbody><tr id="row55303331347"><td class="cellrowborder" valign="top" width="49.980000000000004%" headers="mcps1.2.3.1.1 "><p id="p1530113313341"><a name="p1530113313341"></a><a name="p1530113313341"></a>handle</p>
</td>
<td class="cellrowborder" valign="top" width="50.019999999999996%" headers="mcps1.2.3.1.2 "><p id="p3530173313346"><a name="p3530173313346"></a><a name="p3530173313346"></a>UART device handle.</p>
</td>
</tr>
<tr id="row45309337342"><td class="cellrowborder" valign="top" width="49.980000000000004%" headers="mcps1.2.3.1.1 "><p id="p553083319348"><a name="p553083319348"></a><a name="p553083319348"></a>attribute</p>
</td>
<td class="cellrowborder" valign="top" width="50.019999999999996%" headers="mcps1.2.3.1.2 "><p id="p5530133314343"><a name="p5530133314343"></a><a name="p5530133314343"></a>Pointer to the UART device attributes to set.</p>
</td>
</tr>
<tr id="row12530833103415"><td class="cellrowborder" valign="top" width="49.980000000000004%" headers="mcps1.2.3.1.1 "><p id="p185309331345"><a name="p185309331345"></a><a name="p185309331345"></a><strong id="b18520248203717"><a name="b18520248203717"></a><a name="b18520248203717"></a>Return Value</strong></p>
</td>
<td class="cellrowborder" valign="top" width="50.019999999999996%" headers="mcps1.2.3.1.2 "><p id="p145309332344"><a name="p145309332344"></a><a name="p145309332344"></a><strong id="b5367174913370"><a name="b5367174913370"></a><a name="b5367174913370"></a>Description</strong></p>
</td>
</tr>
<tr id="row14530203310348"><td class="cellrowborder" valign="top" width="49.980000000000004%" headers="mcps1.2.3.1.1 "><p id="p1653014339343"><a name="p1653014339343"></a><a name="p1653014339343"></a>0</p>
</td>
<td class="cellrowborder" valign="top" width="50.019999999999996%" headers="mcps1.2.3.1.2 "><p id="p1453023323419"><a name="p1453023323419"></a><a name="p1453023323419"></a>Succeeded in setting the UART device attributes.</p>
</td>
</tr>
<tr id="row6531163373412"><td class="cellrowborder" valign="top" width="49.980000000000004%" headers="mcps1.2.3.1.1 "><p id="p16530123310345"><a name="p16530123310345"></a><a name="p16530123310345"></a>Negative value</p>
</td>
<td class="cellrowborder" valign="top" width="50.019999999999996%" headers="mcps1.2.3.1.2 "><p id="p1953118334347"><a name="p1953118334347"></a><a name="p1953118334347"></a>Failed to set the UART device attributes.</p>
</td>
</tr>
</tbody>
</table>
The following example shows how to set the UART device attributes:
### Setting UART Device Attributes
Call **UartSetAttribute()** to set UART device attributes.
```
int32_t UartSetAttribute(DevHandle handle, struct UartAttribute *attribute);
```
**Table 5** Description of UartSetAttribute
| Parameter| Description|
| -------- | -------- |
| handle | UART device handle.|
| attribute | Pointer to the UART device attributes to set.|
| **Return Value**| **Description**|
| 0 | The operation is successful.|
| Negative value| The operation failed.|
Example: Set UART device attributes.
``` ```
int32_t ret; int32_t ret;
struct UartAttribute attribute; struct UartAttribute attribute;
attribute.dataBits = UART_ATTR_DATABIT_7; /* Set the number of data bits to 7. */ attribute.dataBits = UART_ATTR_DATABIT_7; /* Enable 7 bits to be transferred each time. */
attribute.parity = UART_ATTR_PARITY_NONE; /* Set the parity bit to no parity. */ attribute.parity = UART_ATTR_PARITY_NONE; /* Disable parity check. */
attribute.stopBits = UART_ATTR_STOPBIT_1; /* Set the stop bit to 1. */ attribute.stopBits = UART_ATTR_STOPBIT_1; /* Set the stop bit to 1. */
attribute.rts = UART_ATTR_RTS_DIS; /* Disable the RTS signal. */ attribute.rts = UART_ATTR_RTS_DIS; /* Disable the RTS signal. */
attribute.cts = UART_ATTR_CTS_DIS; /* Disable the CTS signal. */ attribute.cts = UART_ATTR_CTS_DIS; /* Disable the CTS signal. */
attribute.fifoRxEn = UART_ATTR_RX_FIFO_EN; /* Enable RX FIFO. */ attribute.fifoRxEn = UART_ATTR_RX_FIFO_EN; /* Enable RX FIFO. */
attribute.fifoTxEn = UART_ATTR_TX_FIFO_EN; /* Enable TX FIFO. */ attribute.fifoTxEn = UART_ATTR_TX_FIFO_EN; /* Enable TX FIFO. */
/* Set the UART device attributes. */ /* Set UART device attributes. */
ret = UartSetAttribute(handle, &attribute); ret = UartSetAttribute(handle, &attribute);
if (ret != 0) { if (ret != 0) {
HDF_LOGE("UartSetAttribute: failed, ret %d\n", ret); HDF_LOGE("UartSetAttribute: failed, ret %d\n", ret);
} }
``` ```
### Obtaining UART Device Attributes<a name="section18689637165812"></a>
After setting the UART device attributes, obtain the current device attributes by calling the following function:
int32\_t UartGetAttribute\(DevHandle handle, struct UartAttribute \*attribute\);
**Table 6** Description of UartGetAttribute
<a name="table17532123316342"></a>
<table><thead align="left"><tr id="row18531193383420"><th class="cellrowborder" valign="top" width="50%" id="mcps1.2.3.1.1"><p id="p85311833143420"><a name="p85311833143420"></a><a name="p85311833143420"></a><strong id="b1770784123715"><a name="b1770784123715"></a><a name="b1770784123715"></a>Parameter</strong></p>
</th>
<th class="cellrowborder" valign="top" width="50%" id="mcps1.2.3.1.2"><p id="p17531103319348"><a name="p17531103319348"></a><a name="p17531103319348"></a><strong id="b0130114519373"><a name="b0130114519373"></a><a name="b0130114519373"></a>Description</strong></p>
</th>
</tr>
</thead>
<tbody><tr id="row35311533153413"><td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.1 "><p id="p453133333418"><a name="p453133333418"></a><a name="p453133333418"></a>handle</p>
</td>
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.2 "><p id="p753193323420"><a name="p753193323420"></a><a name="p753193323420"></a>UART device handle.</p>
</td>
</tr>
<tr id="row1953103315344"><td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.1 "><p id="p35315333346"><a name="p35315333346"></a><a name="p35315333346"></a>attribute</p>
</td>
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.2 "><p id="p14531633133416"><a name="p14531633133416"></a><a name="p14531633133416"></a>Pointer to the UART device attributes.</p>
</td>
</tr>
<tr id="row45321433143415"><td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.1 "><p id="p653273363417"><a name="p653273363417"></a><a name="p653273363417"></a><strong id="b15211548193719"><a name="b15211548193719"></a><a name="b15211548193719"></a>Return Value</strong></p>
</td>
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.2 "><p id="p1653203312347"><a name="p1653203312347"></a><a name="p1653203312347"></a><strong id="b836815498379"><a name="b836815498379"></a><a name="b836815498379"></a>Description</strong></p>
</td>
</tr>
<tr id="row175320339342"><td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.1 "><p id="p10532163383412"><a name="p10532163383412"></a><a name="p10532163383412"></a>0</p>
</td>
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.2 "><p id="p5532143319341"><a name="p5532143319341"></a><a name="p5532143319341"></a>Succeeded in obtaining the UART device attributes.</p>
</td>
</tr>
<tr id="row125327337340"><td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.1 "><p id="p19532153317345"><a name="p19532153317345"></a><a name="p19532153317345"></a>Negative value</p>
</td>
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.2 "><p id="p175321933163410"><a name="p175321933163410"></a><a name="p175321933163410"></a>Failed to obtain the UART device attributes.</p>
</td>
</tr>
</tbody>
</table>
The following example shows how to obtain the UART device attributes:
### Obtaining UART Device Attributes
Call **UartGetAttribute()** to obtain the current UART device attributes.
```
int32_t UartGetAttribute(DevHandle handle, struct UartAttribute *attribute);
```
**Table 6** Description of UartGetAttribute
| Parameter| Description|
| -------- | -------- |
| handle | UART device handle.|
| attribute | Pointer to the UART device attributes obtained.|
| **Return Value**| **Description**|
| 0 | The operation is successful.|
| Negative value| The operation failed.|
Example: Obtain UART device attributes.
``` ```
int32_t ret; int32_t ret;
struct UartAttribute attribute; struct UartAttribute attribute;
/* Obtain the UART attributes. */ /* Obtain UART device attributes. */
ret = UartGetAttribute(handle, &attribute); ret = UartGetAttribute(handle, &attribute);
if (ret != 0) { if (ret != 0) {
HDF_LOGE("UartGetAttribute: failed, ret %d\n", ret); HDF_LOGE("UartGetAttribute: failed, ret %d\n", ret);
} }
``` ```
### Setting the UART Transmission Mode<a name="section72713435918"></a>
Before performing UART communication, set the UART transmission mode by calling the following function:
int32\_t UartSetTransMode\(DevHandle handle, enum UartTransMode mode\);
**Table 7** Description of UartSetTransMode
<a name="table131892266313"></a>
<table><thead align="left"><tr id="row018922615318"><th class="cellrowborder" valign="top" width="49.980000000000004%" id="mcps1.2.3.1.1"><p id="p131891826835"><a name="p131891826835"></a><a name="p131891826835"></a><strong id="b197086411379"><a name="b197086411379"></a><a name="b197086411379"></a>Parameter</strong></p>
</th>
<th class="cellrowborder" valign="top" width="50.019999999999996%" id="mcps1.2.3.1.2"><p id="p101894269314"><a name="p101894269314"></a><a name="p101894269314"></a><strong id="b813014510375"><a name="b813014510375"></a><a name="b813014510375"></a>Description</strong></p>
</th>
</tr>
</thead>
<tbody><tr id="row11893261734"><td class="cellrowborder" valign="top" width="49.980000000000004%" headers="mcps1.2.3.1.1 "><p id="p81897261333"><a name="p81897261333"></a><a name="p81897261333"></a>handle</p>
</td>
<td class="cellrowborder" valign="top" width="50.019999999999996%" headers="mcps1.2.3.1.2 "><p id="p5190142618310"><a name="p5190142618310"></a><a name="p5190142618310"></a>UART device handle.</p>
</td>
</tr>
<tr id="row1119082615317"><td class="cellrowborder" valign="top" width="49.980000000000004%" headers="mcps1.2.3.1.1 "><p id="p1519012261314"><a name="p1519012261314"></a><a name="p1519012261314"></a>mode</p>
</td>
<td class="cellrowborder" valign="top" width="50.019999999999996%" headers="mcps1.2.3.1.2 "><p id="p121901026632"><a name="p121901026632"></a><a name="p121901026632"></a>UART transmission mode to set.</p>
</td>
</tr>
<tr id="row19190152612317"><td class="cellrowborder" valign="top" width="49.980000000000004%" headers="mcps1.2.3.1.1 "><p id="p131900266316"><a name="p131900266316"></a><a name="p131900266316"></a><strong id="b1352194823717"><a name="b1352194823717"></a><a name="b1352194823717"></a>Return Value</strong></p>
</td>
<td class="cellrowborder" valign="top" width="50.019999999999996%" headers="mcps1.2.3.1.2 "><p id="p1519022616315"><a name="p1519022616315"></a><a name="p1519022616315"></a><strong id="b1836924917371"><a name="b1836924917371"></a><a name="b1836924917371"></a>Description</strong></p>
</td>
</tr>
<tr id="row919016261932"><td class="cellrowborder" valign="top" width="49.980000000000004%" headers="mcps1.2.3.1.1 "><p id="p10190526334"><a name="p10190526334"></a><a name="p10190526334"></a>0</p>
</td>
<td class="cellrowborder" valign="top" width="50.019999999999996%" headers="mcps1.2.3.1.2 "><p id="p1219012264318"><a name="p1219012264318"></a><a name="p1219012264318"></a>Succeeded in setting the UART transmission mode.</p>
</td>
</tr>
<tr id="row1219017262313"><td class="cellrowborder" valign="top" width="49.980000000000004%" headers="mcps1.2.3.1.1 "><p id="p15190162616316"><a name="p15190162616316"></a><a name="p15190162616316"></a>Negative value</p>
</td>
<td class="cellrowborder" valign="top" width="50.019999999999996%" headers="mcps1.2.3.1.2 "><p id="p131906262311"><a name="p131906262311"></a><a name="p131906262311"></a>Failed to set the UART transmission mode.</p>
</td>
</tr>
</tbody>
</table>
The following example shows how to set the transmission mode to **UART\_MODE\_RD\_BLOCK**:
### Setting the UART Transmission Mode
Call **UartSetTransMode()** to set the UART transmission mode.
```
int32_t UartSetTransMode(DevHandle handle, enum UartTransMode mode);
```
**Table 7** Description of UartSetTransMode
| Parameter| Description|
| -------- | -------- |
| handle | UART device handle.|
| mode | UART transmission mode to set.|
| **Return Value**| **Description**|
| 0 | The operation is successful.|
| Negative value| The operation failed.|
Example: Set the UART transmission mode to **UART_MODE_RD_BLOCK**.
``` ```
int32_t ret; int32_t ret;
/* Set the UART transmission mode. */ /* Set the UART transmission mode. */
...@@ -438,116 +258,64 @@ if (ret != 0) { ...@@ -438,116 +258,64 @@ if (ret != 0) {
} }
``` ```
### Writing Data of a Specified Length into a UART Device<a name="section128001736155919"></a>
To write data into a UART device, call the following function:
int32\_t UartWrite\(DevHandle handle, uint8\_t \*data, uint32\_t size\);
**Table 8** Description of UartWrite
<a name="table27825111368"></a>
<table><thead align="left"><tr id="row1578171123619"><th class="cellrowborder" valign="top" width="50%" id="mcps1.2.3.1.1"><p id="p078112115360"><a name="p078112115360"></a><a name="p078112115360"></a><strong id="b14708841203711"><a name="b14708841203711"></a><a name="b14708841203711"></a>Parameter</strong></p>
</th>
<th class="cellrowborder" valign="top" width="50%" id="mcps1.2.3.1.2"><p id="p37811711163612"><a name="p37811711163612"></a><a name="p37811711163612"></a><strong id="b2131174553712"><a name="b2131174553712"></a><a name="b2131174553712"></a>Description</strong></p>
</th>
</tr>
</thead>
<tbody><tr id="row1878291143611"><td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.1 "><p id="p07818112360"><a name="p07818112360"></a><a name="p07818112360"></a>handle</p>
</td>
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.2 "><p id="p178281113369"><a name="p178281113369"></a><a name="p178281113369"></a>UART device handle.</p>
</td>
</tr>
<tr id="row7782811123614"><td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.1 "><p id="p8782911173610"><a name="p8782911173610"></a><a name="p8782911173610"></a>data</p>
</td>
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.2 "><p id="p17782171120366"><a name="p17782171120366"></a><a name="p17782171120366"></a>Pointer to the data to write.</p>
</td>
</tr>
<tr id="row1578251112367"><td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.1 "><p id="p3782911183612"><a name="p3782911183612"></a><a name="p3782911183612"></a>size</p>
</td>
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.2 "><p id="p17782161110366"><a name="p17782161110366"></a><a name="p17782161110366"></a>Length of the data to write.</p>
</td>
</tr>
<tr id="row1378281113363"><td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.1 "><p id="p87821411183616"><a name="p87821411183616"></a><a name="p87821411183616"></a><strong id="b2052274863718"><a name="b2052274863718"></a><a name="b2052274863718"></a>Return Value</strong></p>
</td>
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.2 "><p id="p13782111116361"><a name="p13782111116361"></a><a name="p13782111116361"></a><strong id="b73704492377"><a name="b73704492377"></a><a name="b73704492377"></a>Description</strong></p>
</td>
</tr>
<tr id="row47822112365"><td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.1 "><p id="p107821011103613"><a name="p107821011103613"></a><a name="p107821011103613"></a>0</p>
</td>
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.2 "><p id="p11782191103610"><a name="p11782191103610"></a><a name="p11782191103610"></a>Succeeded in writing data into the UART device.</p>
</td>
</tr>
<tr id="row11782911113611"><td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.1 "><p id="p1578221111367"><a name="p1578221111367"></a><a name="p1578221111367"></a>Negative value</p>
</td>
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.2 "><p id="p9782151110366"><a name="p9782151110366"></a><a name="p9782151110366"></a>Failed to write data into the UART device.</p>
</td>
</tr>
</tbody>
</table>
The following example shows how to write data of a specified length into the UART device:
### Writing Data to a UART Device
Call **UartWrite()** to write data of the specified length to a UART device.
```
int32_t UartWrite(DevHandle handle, uint8_t *data, uint32_t size);
```
**Table 8** Description of UartWrite
| Parameter| Description|
| -------- | -------- |
| handle | UART device handle.|
| data | Pointer to the data to write.|
| size | Length of the data to write.|
| **Return Value**| **Description**|
| 0 | The operation is successful.|
| Negative value| The operation failed.|
Example: Write data to a UART device.
``` ```
int32_t ret; int32_t ret;
uint8_t wbuff[5] = {1, 2, 3, 4, 5}; uint8_t wbuff[5] = {1, 2, 3, 4, 5};
/* Write 5-byte data into the UART device. */ /* Write 5-byte data to the UART device. */
ret = UartWrite(handle, wbuff, 5); ret = UartWrite(handle, wbuff, 5);
if (ret != 0) { if (ret != 0) {
HDF_LOGE("UartWrite: failed, ret %d\n", ret); HDF_LOGE("UartWrite: failed, ret %d\n", ret);
} }
``` ```
### Reading Data of a Specified Length from a UART Device<a name="section92851601604"></a>
To write data into a UART device, call the following function:
int32\_t UartRead\(DevHandle handle, uint8\_t \*data, uint32\_t size\);
**Table 9** Description of UartRead
<a name="table162341717123713"></a>
<table><thead align="left"><tr id="row023313171377"><th class="cellrowborder" valign="top" width="50%" id="mcps1.2.3.1.1"><p id="p1123331710376"><a name="p1123331710376"></a><a name="p1123331710376"></a><strong id="b970911411374"><a name="b970911411374"></a><a name="b970911411374"></a>Parameter</strong></p>
</th>
<th class="cellrowborder" valign="top" width="50%" id="mcps1.2.3.1.2"><p id="p523321783715"><a name="p523321783715"></a><a name="p523321783715"></a><strong id="b16132114553713"><a name="b16132114553713"></a><a name="b16132114553713"></a>Description</strong></p>
</th>
</tr>
</thead>
<tbody><tr id="row6234417133712"><td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.1 "><p id="p7233121716379"><a name="p7233121716379"></a><a name="p7233121716379"></a>handle</p>
</td>
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.2 "><p id="p17234101753712"><a name="p17234101753712"></a><a name="p17234101753712"></a>UART device handle.</p>
</td>
</tr>
<tr id="row18234151718372"><td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.1 "><p id="p16234191783711"><a name="p16234191783711"></a><a name="p16234191783711"></a>data</p>
</td>
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.2 "><p id="p923417175378"><a name="p923417175378"></a><a name="p923417175378"></a>Pointer to the buffer for receiving the data.</p>
</td>
</tr>
<tr id="row82341017193711"><td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.1 "><p id="p13234917103717"><a name="p13234917103717"></a><a name="p13234917103717"></a>size</p>
</td>
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.2 "><p id="p182341817153717"><a name="p182341817153717"></a><a name="p182341817153717"></a>Length of the data to read.</p>
</td>
</tr>
<tr id="row102341617123717"><td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.1 "><p id="p172341617163712"><a name="p172341617163712"></a><a name="p172341617163712"></a><strong id="b1352319486376"><a name="b1352319486376"></a><a name="b1352319486376"></a>Return Value</strong></p>
</td>
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.2 "><p id="p1623431763718"><a name="p1623431763718"></a><a name="p1623431763718"></a><strong id="b73711949113718"><a name="b73711949113718"></a><a name="b73711949113718"></a>Description</strong></p>
</td>
</tr>
<tr id="row4234151719372"><td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.1 "><p id="p3234131716375"><a name="p3234131716375"></a><a name="p3234131716375"></a>Non-negative value</p>
</td>
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.2 "><p id="p7234171783718"><a name="p7234171783718"></a><a name="p7234171783718"></a>Length of the data read from the UART device.</p>
</td>
</tr>
<tr id="row112340173378"><td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.1 "><p id="p1423431743714"><a name="p1423431743714"></a><a name="p1423431743714"></a>Negative value</p>
</td>
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.2 "><p id="p32349178378"><a name="p32349178378"></a><a name="p32349178378"></a>Failed to read data from the UART device.</p>
</td>
</tr>
</tbody>
</table>
The following example shows how to read data of a specified length from the UART device:
### Reading Data from a UART Device
Call **UartRead()** to read data of the specified length from a UART device.
```
int32_t UartRead(DevHandle handle, uint8_t *data, uint32_t size);
```
**Table 9** Description of UartRead
| Parameter| Description|
| -------- | -------- |
| handle | UART device handle.|
| data | Pointer to the buffer for receiving the data.|
| size | Length of the data to read.|
| **Return Value**| **Description**|
| Non-negative value| The operation is successful. The length of the data read is returned.|
| Negative value| The operation failed.|
Example: Read data of the specified length from a UART device.
``` ```
int32_t ret; int32_t ret;
uint8_t rbuff[5] = {0}; uint8_t rbuff[5] = {0};
...@@ -558,44 +326,39 @@ if (ret < 0) { ...@@ -558,44 +326,39 @@ if (ret < 0) {
} }
``` ```
>![](../public_sys-resources/icon-caution.gif) **CAUTION:** > ![icon-caution.gif](../public_sys-resources/icon-caution.gif) **CAUTION**<br/>
>Data is successfully read from the UART device if a non-negative value is returned. If the return value is **0**, no valid data can be read from the UART device. If the return value is greater than **0**, the return value is the length of the data actually read from the UART device. The length is less than or equal to the value of **size** and does not exceed the maximum length of data to read at a time specified by the UART controller in use. > Data is successfully read from the UART device if a non-negative value is returned. If **0** is returned, no valid data can be read from the UART device. A value greater than **0** indicates the length of the data read from the UART device. The data length must be less than or equal to the value of **size** and cannot exceed the maximum length of the data to read at a time specified by the UART controller in use.
### Destroying the UART Device Handle<a name="section1477410521406"></a>
After the UART communication, destroy the UART device handle by calling the following function: ### Closing a UART Device Handle
void UartClose\(DevHandle handle\); Call **UartClose()** to close a UART device handle.
This function will release the resources previously obtained.
```
void UartClose(DevHandle handle);
```
**Table 10** Description of UartClose This function releases the resources requested by **UartOpen**.
<a name="table03348317351"></a> **Table 10** Description of UartClose
<table><thead align="left"><tr id="row15334837351"><th class="cellrowborder" valign="top" width="50%" id="mcps1.2.3.1.1"><p id="p933411316354"><a name="p933411316354"></a><a name="p933411316354"></a><strong id="b1710184115375"><a name="b1710184115375"></a><a name="b1710184115375"></a>Parameter</strong></p>
</th>
<th class="cellrowborder" valign="top" width="50%" id="mcps1.2.3.1.2"><p id="p16334103143517"><a name="p16334103143517"></a><a name="p16334103143517"></a><strong id="b2013254513370"><a name="b2013254513370"></a><a name="b2013254513370"></a>Description</strong></p>
</th>
</tr>
</thead>
<tbody><tr id="row733483103513"><td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.1 "><p id="p7334530358"><a name="p7334530358"></a><a name="p7334530358"></a>handle</p>
</td>
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.2.3.1.2 "><p id="p133341331356"><a name="p133341331356"></a><a name="p133341331356"></a>UART device handle.</p>
</td>
</tr>
</tbody>
</table>
The following example shows how to destroy the UART device handle: | Parameter| Description|
| -------- | -------- |
| handle | UART device handle to close.|
Example: Close a UART device handle.
``` ```
UartClose(handle); /* Destroy the UART device handle. */ UartClose(handle); /* Close the UART device handle. */
``` ```
## Usage Example<a name="section35404241311"></a>
The following is a usage example of a UART device, including how to obtain the UART device handle, set the baud rate, device attributes, and transmission mode, read data from or write data into the UART device, and then destroy the UART device handle. ## Example
The following example shows how to open a UART device handle, set the baud rate, device attributes, and transmission mode, read data from or write data into the UART device, and then close the UART device handle.
``` ```
#include "hdf_log.h" #include "hdf_log.h"
#include "uart_if.h" #include "uart_if.h"
...@@ -608,16 +371,16 @@ void UartTestSample(void) ...@@ -608,16 +371,16 @@ void UartTestSample(void)
uint8_t wbuff[5] = { 1, 2, 3, 4, 5 }; uint8_t wbuff[5] = { 1, 2, 3, 4, 5 };
uint8_t rbuff[5] = { 0 }; uint8_t rbuff[5] = { 0 };
struct UartAttribute attribute; struct UartAttribute attribute;
attribute.dataBits = UART_ATTR_DATABIT_7; /* Set the number of data bits to 7. */ attribute.dataBits = UART_ATTR_DATABIT_7; /* Enable 7 bits to be transferred each time. */
attribute.parity = UART_ATTR_PARITY_NONE; /* Set the parity bit to no parity. */ attribute.parity = UART_ATTR_PARITY_NONE; /* Disable parity check. */
attribute.stopBits = UART_ATTR_STOPBIT_1; /* Set the stop bit to 1. */ attribute.stopBits = UART_ATTR_STOPBIT_1; /* Set the stop bit to 1. */
attribute.rts = UART_ATTR_RTS_DIS; /* Disable the RTS signal. */ attribute.rts = UART_ATTR_RTS_DIS; /* Disable the RTS signal. */
attribute.cts = UART_ATTR_CTS_DIS; /* Disable the CTS signal. */ attribute.cts = UART_ATTR_CTS_DIS; /* Disable the CTS signal. */
attribute.fifoRxEn = UART_ATTR_RX_FIFO_EN; /* Enable RX FIFO. */ attribute.fifoRxEn = UART_ATTR_RX_FIFO_EN; /* Enable RX FIFO. */
attribute.fifoTxEn = UART_ATTR_TX_FIFO_EN; /* Enable TX FIFO. */ attribute.fifoTxEn = UART_ATTR_TX_FIFO_EN; /* Enable TX FIFO. */
/* Set the UART port number actually used. */ /* Enter the UART port number. */
port = 1; port = 1;
/* Obtain the UART device handle. */ /* Open the UART device handle based on the port number. */
handle = UartOpen(port); handle = UartOpen(port);
if (handle == NULL) { if (handle == NULL) {
HDF_LOGE("UartOpen: failed!\n"); HDF_LOGE("UartOpen: failed!\n");
...@@ -629,7 +392,7 @@ void UartTestSample(void) ...@@ -629,7 +392,7 @@ void UartTestSample(void)
HDF_LOGE("UartSetBaud: failed, ret %d\n", ret); HDF_LOGE("UartSetBaud: failed, ret %d\n", ret);
goto _ERR; goto _ERR;
} }
/* Set the UART device attributes. */ /* Set UART device attributes. */
ret = UartSetAttribute(handle, &attribute); ret = UartSetAttribute(handle, &attribute);
if (ret != 0) { if (ret != 0) {
HDF_LOGE("UartSetAttribute: failed, ret %d\n", ret); HDF_LOGE("UartSetAttribute: failed, ret %d\n", ret);
...@@ -641,7 +404,7 @@ void UartTestSample(void) ...@@ -641,7 +404,7 @@ void UartTestSample(void)
HDF_LOGE("UartSetTransMode: failed, ret %d\n", ret); HDF_LOGE("UartSetTransMode: failed, ret %d\n", ret);
goto _ERR; goto _ERR;
} }
/* Write 5-byte data into the UART device. */ /* Write 5-byte data to the UART device. */
ret = UartWrite(handle, wbuff, 5); ret = UartWrite(handle, wbuff, 5);
if (ret != 0) { if (ret != 0) {
HDF_LOGE("UartWrite: failed, ret %d\n", ret); HDF_LOGE("UartWrite: failed, ret %d\n", ret);
...@@ -654,7 +417,7 @@ void UartTestSample(void) ...@@ -654,7 +417,7 @@ void UartTestSample(void)
goto _ERR; goto _ERR;
} }
_ERR: _ERR:
/* Destroy the UART device handle. */ /* Close the UART device handle. */
UartClose(handle); UartClose(handle);
} }
``` ```
\ No newline at end of file
...@@ -14,7 +14,7 @@ In the Hardware Driver Foundation (HDF), the Universal Asynchronous Receiver/Tra ...@@ -14,7 +14,7 @@ In the Hardware Driver Foundation (HDF), the Universal Asynchronous Receiver/Tra
**UartHostMethod**: **UartHostMethod**:
``` ```
struct UartHostMethod { struct UartHostMethod {
int32_t (*Init)(struct UartHost *host); int32_t (*Init)(struct UartHost *host);
...@@ -32,18 +32,18 @@ struct UartHostMethod { ...@@ -32,18 +32,18 @@ struct UartHostMethod {
**Table 1** Description of the callback functions in UartHostMethod **Table 1** Description of the callback functions in UartHostMethod
| Function| Input Parameter| Output Parameter| Return Value| Description| | Function| Input Parameter| Output Parameter| Return Value| Description|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| Init | **host**: structure pointer to the UART controller at the core layer.| –| HDF_STATUS| Initializes a UART device.| | Init | **host**: structure pointer to the UART controller at the core layer.| –| HDF_STATUS| Initializes a UART device.|
| Deinit | **host**: structure pointer to the UART controller at the core layer.| –| HDF_STATUS| Deinitializes a UART device.| | Deinit | **host**: structure pointer to the UART controller at the core layer.| –| HDF_STATUS| Deinitializes a UART device.|
| Read | **host**: structure pointer to the UART controller at the core layer.<br>**size**: data size, which is of the uint32_t type.| **data**: pointer to the output data. The value is of the uint8_t type.| HDF_STATUS| Reads data.| | Read | **host**: structure pointer to the UART controller at the core layer.<br>**size**: data size, which is of the uint32_t type.| **data**: pointer to the data read. The value is of the uint8_t type. | HDF_STATUS| Reads data.|
| Write | **host**: structure pointer to the UART controller at the core layer.<br>**data**: pointer to the input data. The value is of the uint8_t type.<br>**size**: data size, which is of the uint32_t type.| –| HDF_STATUS| Writes data.| | Write | **host**: structure pointer to the UART controller at the core layer.<br>**data**: pointer to the data to write. The value is of the uint8_t type.<br>**size**: data size, which is of the uint32_t type. | –| HDF_STATUS| Writes data.|
| SetBaud | **host**: structure pointer to the UART controller at the core layer.<br>**baudRate**: pointer to the input baud rate. The value is of the uint32_t type. | –| HDF_STATUS| Sets the baud rate.| | SetBaud | **host**: structure pointer to the UART controller at the core layer.<br>**baudRate**: pointer to the baud rate to set. The value is of the uint32_t type. | –| HDF_STATUS| Sets the baud rate.|
| GetBaud | **host**: structure pointer to the UART controller at the core layer.| **baudRate**: pointer to the output baud rate. The value is of the uint32_t type.| HDF_STATUS| Obtains the current baud rate.| | GetBaud | **host**: structure pointer to the UART controller at the core layer.| **baudRate**: pointer to the baud rate obtained. The value is of the uint32_t type. | HDF_STATUS| Obtains the current baud rate.|
| GetAttribute | **host**: structure pointer to the UART controller at the core layer.| **attribute**: structure pointer to the UART attributes. For details, see **UartAttribute** in **uart_if.h**.| HDF_STATUS| Obtains UART attributes.| | GetAttribute | **host**: structure pointer to the UART controller at the core layer.| **attribute**: structure pointer to the attribute obtained. For details, see **UartAttribute** in **uart_if.h**. | HDF_STATUS| Obtains UART attributes.|
| SetAttribute | **host**: structure pointer to the UART controller at the core layer.<br>**attribute**: structure pointer to the UART attributes to set.| –| HDF_STATUS| Sets UART attributes.| | SetAttribute | **host**: structure pointer to the UART controller at the core layer.<br>**attribute**: structure pointer to the attribute to set. | –| HDF_STATUS| Sets UART attributes.|
| SetTransMode | **host**: structure pointer to the UART controller at the core layer.<br>**mode**: transfer mode to set. For details, see **UartTransMode** in **uart_if.h**.| –| HDF_STATUS| Sets the UART transfer mode.| | SetTransMode | **host**: structure pointer to the UART controller at the core layer.<br>**mode**: transfer mode to set. For details, see **UartTransMode** in **uart_if.h**.| –| HDF_STATUS| Sets the UART transfer mode.|
| PollEvent | **host**: structure pointer to the UART controller at the core layer.<br>**filep**: void pointer to a file.<br>**table**: void pointer to poll_table.| –| HDF_STATUS| Polls for pending events.| | PollEvent | **host**: structure pointer to the UART controller at the core layer.<br>**filep**: void pointer to a file.<br>**table**: void pointer to poll_table.| –| HDF_STATUS| Polls for pending events.|
## How to Develop ## How to Develop
...@@ -61,10 +61,11 @@ The UART module adaptation involves the following steps: ...@@ -61,10 +61,11 @@ The UART module adaptation involves the following steps:
3. Instantiate the UART controller object. 3. Instantiate the UART controller object.
- Initialize **UartHost**. - Initialize **UartHost**.
- Instantiate **UartHostMethod** in the **UartHost** object. - Instantiate **UartHostMethod** in the **UartHost** object.
> ![icon-note.gif](../public_sys-resources/icon-note.gif) **NOTE**<br> > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br>
> For details about the functions in **UartHostMethod**, see [Available APIs](#available-apis). > For details about the functions in **UartHostMethod**, see [Available APIs](#available-apis).
4. Debug the driver.<br> 4. Debug the driver.
(Optional) For new drivers, verify the basic functions, such as the UART status control and response to interrupts. (Optional) For new drivers, verify the basic functions, such as the UART status control and response to interrupts.
...@@ -72,11 +73,16 @@ The UART module adaptation involves the following steps: ...@@ -72,11 +73,16 @@ The UART module adaptation involves the following steps:
The following uses **uart_hi35xx.c** as an example to present the information required for implementing device functions. The following uses **uart_hi35xx.c** as an example to present the information required for implementing device functions.
1. Instantiate the driver entry.<br/>The driver entry must be a global variable of the **HdfDriverEntry** type (defined in **hdf_device_desc.h**), and the value of **moduleName** must be the same as that in **device_info.hcs**. In the HDF, the start address of each **HdfDriverEntry** object of all loaded drivers is collected to form a segment address space similar to an array for the upper layer to invoke. 1. Instantiate the driver entry.
The driver entry must be a global variable of the **HdfDriverEntry** type (defined in **hdf_device_desc.h**), and the value of **moduleName** must be the same as that in **device_info.hcs**.
In the HDF, the start address of each **HdfDriverEntry** object of all loaded drivers is collected to form a segment address space similar to an array for the upper layer to invoke.
Generally, the HDF calls the **Bind** function and then the **Init** function to load a driver. If **Init** fails to be called, the HDF calls **Release** to release driver resources and exit. Generally, the HDF calls the **Bind** function and then the **Init** function to load a driver. If **Init** fails to be called, the HDF calls **Release** to release driver resources and exit.
UART driver entry example: UART driver entry example:
``` ```
struct HdfDriverEntry g_hdfUartDevice = { struct HdfDriverEntry g_hdfUartDevice = {
.moduleVersion = 1, .moduleVersion = 1,
...@@ -89,11 +95,15 @@ The following uses **uart_hi35xx.c** as an example to present the information re ...@@ -89,11 +95,15 @@ The following uses **uart_hi35xx.c** as an example to present the information re
HDF_INIT(g_hdfUartDevice); HDF_INIT(g_hdfUartDevice);
``` ```
2. Add the **deviceNode** information to the **device_info.hcs** file and configure the device attributes in the **uart_config.hcs** file.<br> The **deviceNode** information is related to registration of the driver entry. The device attribute values are closely related to the default values or value ranges of the **UartHost** members at the core layer. 2. Add the **deviceNode** information to the **device_info.hcs** file and configure the device attributes in the **uart_config.hcs** file.
In this example, there is only one UART controller. If there are multiple UART controllers, you need to add the **deviceNode** information to the **device_info** file and add the corresponding device attributes to the **uart_config** file for each controller.
- **device_info.hcs** configuration example The **deviceNode** information is related to registration of the driver entry. The device attribute values are closely related to the default values or value ranges of the **UartHost** members at the core layer.
In this example, there is only one UART controller. If there are multiple UART controllers, you need to add the **deviceNode** information to the **device_info** file and add the corresponding device attributes to the **uart_config** file for each controller.
- **device_info.hcs** configuration example:
``` ```
root { root {
device_info { device_info {
...@@ -103,11 +113,11 @@ The following uses **uart_hi35xx.c** as an example to present the information re ...@@ -103,11 +113,11 @@ The following uses **uart_hi35xx.c** as an example to present the information re
priority = 50; priority = 50;
device_uart :: device { device_uart :: device {
device0 :: deviceNode { device0 :: deviceNode {
policy = 1; // The driver publishes services only for kernel-mode processes. policy = 1; // The driver publishes services only for kernel-mode processes.
priority = 40; // Driver startup priority. priority = 40; // Driver startup priority.
permission = 0644; // Permission for the driver to create a device node. permission = 0644; // Permission for the driver to create a device node.
moduleName = "HDF_PLATFORM_UART"; // Driver name, which must be the same as moduleName in the HdfDriverEntry structure. moduleName = "HDF_PLATFORM_UART"; // Driver name, which must be the same as moduleName in the HdfDriverEntry structure.
serviceName = "HDF_PLATFORM_UART_0";// Unique name of the service published by the driver. The name is in the HDF_PLATFORM_UART_X format. X indicates the UART controller number. serviceName = "HDF_PLATFORM_UART_0"; // Unique name of the service published by the driver. The name is in the HDF_PLATFORM_UART_X format. X indicates the UART controller number.
deviceMatchAttr = "hisilicon_hi35xx_uart_0"; // Keyword for matching the private data of the driver. The value must be the same as that of match_attr in the private data configuration table of the driver. deviceMatchAttr = "hisilicon_hi35xx_uart_0"; // Keyword for matching the private data of the driver. The value must be the same as that of match_attr in the private data configuration table of the driver.
} }
device1 :: deviceNode { device1 :: deviceNode {
...@@ -127,20 +137,20 @@ The following uses **uart_hi35xx.c** as an example to present the information re ...@@ -127,20 +137,20 @@ The following uses **uart_hi35xx.c** as an example to present the information re
- **uart_config.hcs** configuration example - **uart_config.hcs** configuration example
``` ```
root { root {
platform { platform {
template uart_controller { // Template configuration. In the template, you can configure the common parameters shared by device nodes. template uart_controller { // Template configuration. In the template, you can configure the common parameters shared by device nodes.
match_attr = ""; match_attr = "";
num = 0; // (Mandatory) Device number num = 0; // (Mandatory) Device number.
baudrate = 115200; // (Mandatory) Baud rate. Set the value based on service requirements. baudrate = 115200; // (Mandatory) Baud rate. Set the value based on service requirements.
fifoRxEn = 1; // (Mandatory) Enable FIFOs to be received. fifoRxEn = 1; // (Mandatory) Enable FIFOs to be received.
fifoTxEn = 1; // (Mandatory) Enable FIFOs to be transferred. fifoTxEn = 1; // (Mandatory) Enable FIFOs to be transferred.
flags = 4; // (Mandatory) Flag signal. flags = 4; // (Mandatory) Flag signal.
regPbase = 0x120a0000; // (Mandatory) Used for address mapping. regPbase = 0x120a0000; // (Mandatory) Used for address mapping.
interrupt = 38; // (Mandatory) Interrupt number. interrupt = 38; // (Mandatory) Interrupt number.
iomemCount = 0x48; // (Mandatory) Used for address mapping. iomemCount = 0x48; // (Mandatory) Used for address mapping.
} }
controller_0x120a0000 :: uart_controller { controller_0x120a0000 :: uart_controller {
match_attr = "hisilicon_hi35xx_uart_0";// (Mandatory) The value must be the same as that of deviceMatchAttr of the corresponding device in device_info.hcs. match_attr = "hisilicon_hi35xx_uart_0";// (Mandatory) The value must be the same as that of deviceMatchAttr of the corresponding device in device_info.hcs.
...@@ -159,43 +169,44 @@ The following uses **uart_hi35xx.c** as an example to present the information re ...@@ -159,43 +169,44 @@ The following uses **uart_hi35xx.c** as an example to present the information re
``` ```
3. Initialize the **UartHost** object at the core layer, including defining a custom structure (to pass parameters and data) and implementing the **HdfDriverEntry** member functions (**Bind**, **Init**, and **Release**) to instantiate **UartHostMethod** in **UartHost** (so that the underlying driver functions can be called). 3. Initialize the **UartHost** object at the core layer, including defining a custom structure (to pass parameters and data) and implementing the **HdfDriverEntry** member functions (**Bind**, **Init**, and **Release**) to instantiate **UartHostMethod** in **UartHost** (so that the underlying driver functions can be called).
- Defining a custom structure - Defining a custom structure
To the driver, the custom structure holds parameters and data. The **DeviceResourceIface** method provided by the HDF reads the values in the **uart_config.hcs** file to initialize the members in the custom structure and passes important parameters, such as the device number, to the **UartHost** object at the core layer. To the driver, the custom structure holds parameters and data. The **DeviceResourceIface** method provided by the HDF reads the values in the **uart_config.hcs** file to initialize the members in the custom structure and passes important parameters, such as the device number, to the **UartHost** object at the core layer.
``` ```
struct UartPl011Port { // Interface structure struct UartPl011Port { // Interface structure
int32_t enable; int32_t enable;
unsigned long physBase; // Physical address unsigned long physBase; // Physical address
uint32_t irqNum; // Interrupt number uint32_t irqNum; // Interrupt number
uint32_t defaultBaudrate;// Default baud rate uint32_t defaultBaudrate; // Default baud rate
uint32_t flags; // Flags related to the following three macros. uint32_t flags; // Flags related to the following three macros
#define PL011_FLG_IRQ_REQUESTED (1 << 0) #define PL011_FLG_IRQ_REQUESTED (1 << 0)
#define PL011_FLG_DMA_RX_REQUESTED (1 << 1) #define PL011_FLG_DMA_RX_REQUESTED (1 << 1)
#define PL011_FLG_DMA_TX_REQUESTED (1 << 2) #define PL011_FLG_DMA_TX_REQUESTED (1 << 2)
struct UartDmaTransfer *rxUdt; // DMA transfer struct UartDmaTransfer *rxUdt; // DMA transfer
struct UartDriverData *udd; // The data structure is defined as follows: struct UartDriverData *udd; // The data structure is defined as follows:
}; };
struct UartDriverData { // Structure related to data transfer struct UartDriverData { // Structure related to data transfer
uint32_t num; uint32_t num;
uint32_t baudrate; // Baud rate (configurable) uint32_t baudrate; // Baud rate (configurable)
struct UartAttribute attr; // Attributes, such as the data bit and stop bit, related to data transfer struct UartAttribute attr; // Attributes, such as the data bit and stop bit, related to data transfer.
struct UartTransfer *rxTransfer; // Buffer (FIFO structure) struct UartTransfer *rxTransfer; // Buffer (FIFO structure)
wait_queue_head_t wait; // Queuing signal related to conditional variables wait_queue_head_t wait; // Queuing signal related to conditional variables
int32_t count; // Data count int32_t count; // Data count
int32_t state; // UART controller state int32_t state; // UART controller state
#define UART_STATE_NOT_OPENED 0 #define UART_STATE_NOT_OPENED 0
#define UART_STATE_OPENING 1 #define UART_STATE_OPENING 1
#define UART_STATE_USEABLE 2 #define UART_STATE_USEABLE 2
#define UART_STATE_SUSPENDED 3 #define UART_STATE_SUSPENDED 3
uint32_t flags; // Status flags uint32_t flags; // Status flags
#define UART_FLG_DMA_RX (1 << 0) #define UART_FLG_DMA_RX (1 << 0)
#define UART_FLG_DMA_TX (1 << 1) #define UART_FLG_DMA_TX (1 << 1)
#define UART_FLG_RD_BLOCK (1 << 2) #define UART_FLG_RD_BLOCK (1 << 2)
RecvNotify recv; // Pointer to the function that receives serial port data RecvNotify recv; // Pointer to the function that receives serial port data.
struct UartOps *ops; // Custom function pointer structure. For details, see device/hisilicon/drivers/uart/uart_pl011.c. struct UartOps *ops; // Custom function pointer structure. For details, see device/hisilicon/drivers/uart/uart_pl011.c.
void *private; // It stores the pointer to the start address of UartPl011Port for easy invocation. void *private; // It stores the pointer to the start address of UartPl011Port for easy invocation.
}; };
// UartHost is the controller structure at the core layer. The Init function assigns values to the members of UartHost. // UartHost is the controller structure at the core layer. The Init function assigns values to the members of UartHost.
...@@ -205,12 +216,13 @@ The following uses **uart_hi35xx.c** as an example to present the information re ...@@ -205,12 +216,13 @@ The following uses **uart_hi35xx.c** as an example to present the information re
uint32_t num; uint32_t num;
OsalAtomic atom; OsalAtomic atom;
void *priv; // It stores the pointer to the start address of the vendor's custom structure for easy invocation. void *priv; // It stores the pointer to the start address of the vendor's custom structure for easy invocation.
struct UartHostMethod *method; // Hook at the core layer. You need to implement and instantiate its member functions. struct UartHostMethod *method; // Hook at the core layer. You need to implement and instantiate its member functions.
}; };
``` ```
- Instantiating **UartHostMethod** in **UartHost** (other members are initialized by **Bind**) - Instantiating **UartHostMethod** in **UartHost** (other members are initialized by **Bind**)
``` ```
// Example in uart_hi35xx.c: instantiate the hook. // Example in uart_hi35xx.c: instantiate the hook.
struct UartHostMethod g_uartHostMethod = { struct UartHostMethod g_uartHostMethod = {
...@@ -229,30 +241,30 @@ The following uses **uart_hi35xx.c** as an example to present the information re ...@@ -229,30 +241,30 @@ The following uses **uart_hi35xx.c** as an example to present the information re
- **Bind** function - **Bind** function
Input parameter: **Input parameter**:
**HdfDeviceObject**, an interface parameter exposed by the driver, contains the .hcs information. **HdfDeviceObject**, an interface parameter exposed by the driver, contains the .hcs information.
Return value: **Return value**:
HDF_STATUS<br/>The table below describes some status. For more information, see **HDF_STATUS** in the **/drivers/framework/include/utils/hdf_base.h** file. **HDF_STATUS**<br/>The table below describes some status. For more information, see **HDF_STATUS** in the **/drivers/framework/include/utils/hdf_base.h** file.
**Table 2** HDF_STATUS **Table 2** Description of HDF_STATUS
| Status| Description| | Status| Description|
| -------- | -------- | | -------- | -------- |
| HDF_ERR_INVALID_OBJECT | Invalid controller object.| | HDF_ERR_INVALID_OBJECT | Invalid controller object.|
| HDF_ERR_MALLOC_FAIL | Failed to allocate memory.| | HDF_ERR_MALLOC_FAIL | Failed to allocate memory.|
| HDF_ERR_INVALID_PARAM | Invalid parameter.| | HDF_ERR_INVALID_PARAM | Invalid parameter.|
| HDF_ERR_IO | I/O error.| | HDF_ERR_IO | I/O error.|
| HDF_SUCCESS | Initialization successful.| | HDF_SUCCESS | Initialization successful.|
| HDF_FAILURE | Initialization failed.| | HDF_FAILURE | Initialization failed.|
Function description: **Function description**:
Initializes the custom structure object and **UartHost**. Initializes the custom structure object and **UartHost**.
``` ```
//uart_hi35xx.c //uart_hi35xx.c
static int32_t HdfUartDeviceBind(struct HdfDeviceObject *device) static int32_t HdfUartDeviceBind(struct HdfDeviceObject *device)
...@@ -267,10 +279,10 @@ The following uses **uart_hi35xx.c** as an example to present the information re ...@@ -267,10 +279,10 @@ The following uses **uart_hi35xx.c** as an example to present the information re
... ...
host = (struct UartHost *)OsalMemCalloc(sizeof(*host));// Allocate memory. host = (struct UartHost *)OsalMemCalloc(sizeof(*host));// Allocate memory.
... ...
host->device = device; // (Mandatory) Prerequisites for conversion between HdfDeviceObject and UartHost host->device = device; // (Mandatory) Prerequisites for conversion between HdfDeviceObject and UartHost.
device->service = &(host->service; // (Mandatory) Prerequisites for conversion between HdfDeviceObject and UartHost device->service = &(host->service; // (Mandatory) Prerequisites for conversion between HdfDeviceObject and UartHost.
host->device->service->Dispatch = UartIoDispatch;// Assign values to Dispatch of service. host->device->service->Dispatch = UartIoDispatch; // Assign values to Dispatch of service.
OsalAtomicSet(&host->atom, 0); // Initialize or set the atomic services. OsalAtomicSet(&host->atom, 0); // Initialize or set the atomic services.
host->priv = NULL; host->priv = NULL;
host->method = NULL; host->method = NULL;
return host; return host;
...@@ -279,19 +291,19 @@ The following uses **uart_hi35xx.c** as an example to present the information re ...@@ -279,19 +291,19 @@ The following uses **uart_hi35xx.c** as an example to present the information re
- **Init** function - **Init** function
Input parameter: **Input parameter**:
**HdfDeviceObject**, an interface parameter exposed by the driver, contains the .hcs information. **HdfDeviceObject**, an interface parameter exposed by the driver, contains the .hcs information.
Return value: **Return value**:
HDF_STATUS **HDF_STATUS**
Function description: **Function description**:
Initializes the custom structure object and **UartHost**, calls the **artAddDev** function at the core layer, and connects to the VFS. Initializes the custom structure object and **UartHost**, calls the **artAddDev** function at the core layer, and connects to the VFS.
``` ```
int32_t HdfUartDeviceInit(struct HdfDeviceObject *device) int32_t HdfUartDeviceInit(struct HdfDeviceObject *device)
{ {
...@@ -303,7 +315,7 @@ The following uses **uart_hi35xx.c** as an example to present the information re ...@@ -303,7 +315,7 @@ The following uses **uart_hi35xx.c** as an example to present the information re
... ...
ret = Hi35xxAttach(host, device); // Initialize the UartHost object. ret = Hi35xxAttach(host, device); // Initialize the UartHost object.
... ...
host->method = &g_uartHostMethod; // Hook the UartHostMethod instance. host->method = &g_uartHostMethod; // Attach the UartHostMethod instance.
return ret; return ret;
} }
// Initialize UartHost. // Initialize UartHost.
...@@ -351,30 +363,34 @@ The following uses **uart_hi35xx.c** as an example to present the information re ...@@ -351,30 +363,34 @@ The following uses **uart_hi35xx.c** as an example to present the information re
``` ```
- **Release** function - **Release** function
Input parameter: **Input parameter**:
**HdfDeviceObject**, an interface parameter exposed by the driver, contains the .hcs information. **HdfDeviceObject**, an interface parameter exposed by the driver, contains the .hcs information.
Return value: **Return value**:
No value is returned. No value is returned.
Function description: **Function description**:
Releases the memory and deletes the controller. This function assigns values to the **Release** API in the driver entry structure. When the HDF fails to call the **Init** function to initialize the driver, the **Release** function can be called to release driver resources. All forced conversion operations for obtaining the corresponding object can be successful only when **Init()** has the corresponding value assignment operations. Releases the memory and deletes the controller. This function assigns values to the **Release** API in the driver entry structure. When the HDF fails to call the **Init** function to initialize the driver, the **Release** function can be called to release driver resources.
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
>
> All forced conversion operations for obtaining the corresponding object can be successful only when **Init()** has the corresponding value assignment operations.
``` ```
void HdfUartDeviceRelease(struct HdfDeviceObject *device) void HdfUartDeviceRelease(struct HdfDeviceObject *device)
{ {
struct UartHost *host = NULL; struct UartHost *host = NULL;
... ...
host = UartHostFromDevice(device);// Forcibly convert HdfDeviceObject to UartHost by using service. For details about the value assignment, see the Bind function. host = UartHostFromDevice(device); // Forcibly convert HdfDeviceObject to UartHost by using service. For details about the value assignment, see the Bind function.
... ...
if (host->priv != NULL) { if (host->priv != NULL) {
Hi35xxDetach(host); // Customized memory release function. Hi35xxDetach(host); // Customized memory release function.
} }
UartHostDestroy(host); // Call the function of the core layer to release the host. UartHostDestroy(host); // Call the function of the core layer to release the host.
} }
static void Hi35xxDetach(struct UartHost *host) static void Hi35xxDetach(struct UartHost *host)
...@@ -382,10 +398,10 @@ The following uses **uart_hi35xx.c** as an example to present the information re ...@@ -382,10 +398,10 @@ The following uses **uart_hi35xx.c** as an example to present the information re
struct UartDriverData *udd = NULL; struct UartDriverData *udd = NULL;
struct UartPl011Port *port = NULL; struct UartPl011Port *port = NULL;
... ...
udd = host->priv; // Convert UartHost to UartDriverData. udd = host->priv; // The conversion from UartHost to UartDriverData is involved.
... ...
UartRemoveDev(host);// Remove the VFS. UartRemoveDev (host); // Remove the VFS.
port = udd->private;// Convert UartDriverData to UartPl011Port. port = udd->private; // The conversion from UartDriverData to UartPl011Port is involved.
if (port != NULL) { if (port != NULL) {
if (port->physBase != 0) { if (port->physBase != 0) {
OsalIoUnmap((void *)port->physBase);// Unmap addresses. OsalIoUnmap((void *)port->physBase);// Unmap addresses.
...@@ -393,7 +409,7 @@ The following uses **uart_hi35xx.c** as an example to present the information re ...@@ -393,7 +409,7 @@ The following uses **uart_hi35xx.c** as an example to present the information re
OsalMemFree(port); OsalMemFree(port);
udd->private = NULL; udd->private = NULL;
} }
OsalMemFree(udd);//Release UartDriverData. OsalMemFree (udd); // Release UartDriverData.
host->priv = NULL; host->priv = NULL;
} }
``` ```
...@@ -19,13 +19,13 @@ ...@@ -19,13 +19,13 @@
- [Software Timer](kernel-mini-basic-soft.md) - [Software Timer](kernel-mini-basic-soft.md)
- Extended Components - Extended Components
- [C++ Support](kernel-mini-extend-support.md) - [C++ Support](kernel-mini-extend-support.md)
- [PUP](kernel-mini-extend-cpup.md) - [CPUP](kernel-mini-extend-cpup.md)
- [Dynamic Loading](kernel-mini-extend-dynamic-loading.md) - [Dynamic Loading](kernel-mini-extend-dynamic-loading.md)
- [File System](kernel-mini-extend-file.md) - File System
- [FAT](kernel-mini-extend-file-fat.md) - [FAT](kernel-mini-extend-file-fat.md)
- [LittleFS](kernel-mini-extend-file-lit.md) - [LittleFS](kernel-mini-extend-file-lit.md)
- Kernel Debugging - Kernel Debugging
- [Memory Debugging](kernel-mini-memory-debug.md) - Memory Debugging
- [Memory Information Statistics](kernel-mini-memory-debug-mes.md) - [Memory Information Statistics](kernel-mini-memory-debug-mes.md)
- [Memory Leak Check](kernel-mini-memory-debug-det.md) - [Memory Leak Check](kernel-mini-memory-debug-det.md)
- [Memory Corruption Check](kernel-mini-memory-debug-cet.md) - [Memory Corruption Check](kernel-mini-memory-debug-cet.md)
...@@ -52,25 +52,25 @@ ...@@ -52,25 +52,25 @@
- Memory Management - Memory Management
- [Heap Memory Management](kernel-small-basic-memory-heap.md) - [Heap Memory Management](kernel-small-basic-memory-heap.md)
- [Physical Memory Management](kernel-small-basic-memory-physical.md) - [Physical Memory Management](kernel-small-basic-memory-physical.md)
- [Virtual Memory Management](kernel-small-basic-memory-virtual.md) - [Virtual Memory Management](kernel-small-basic-memory-virtual.md)
- [Virtual-to-Physical Mapping](kernel-small-basic-inner-reflect.md) - [Virtual-to-Physical Mapping](kernel-small-basic-inner-reflect.md)
- Kernel Communication Mechanisms - Kernel Communication Mechanisms
- [Event](kernel-small-basic-trans-event.md) - [Event](kernel-small-basic-trans-event.md)
- [Semaphore](kernel-small-basic-trans-semaphore.md) - [Semaphore](kernel-small-basic-trans-semaphore.md)
- [Mutex](kernel-small-basic-trans-mutex.md) - [Mutex](kernel-small-basic-trans-mutex.md)
- [Queue](kernel-small-basic-trans-queue.md) - [Queue](kernel-small-basic-trans-queue.md)
- [RW Lock](kernel-small-basic-trans-rwlock.md) - [RW Lock](kernel-small-basic-trans-rwlock.md)
- [Futex](kernel-small-basic-trans-user-mutex.md) - [Futex](kernel-small-basic-trans-user-mutex.md)
- [Signal](kernel-small-basic-trans-user-signal.md) - [Signal](kernel-small-basic-trans-user-signal.md)
- [Time Management](kernel-small-basic-time.md) - [Time Management](kernel-small-basic-time.md)
- [Software Timer](kernel-small-basic-softtimer.md) - [Software Timer](kernel-small-basic-softtimer.md)
- [Atomic Operation](kernel-small-basic-atomic.md) - [Atomic Operation](kernel-small-basic-atomic.md)
- Extension Components - Extension Components
- [System Call](kernel-small-bundles-system.md) - [System Call](kernel-small-bundles-system.md)
- [Dynamic Loading and Linking](kernel-small-bundles-linking.md) - [Dynamic Loading and Linking](kernel-small-bundles-linking.md)
- [Virtual Dynamic Shared Object](kernel-small-bundles-share.md) - [Virtual Dynamic Shared Object](kernel-small-bundles-share.md)
- [LiteIPC](kernel-small-bundles-ipc.md) - [LiteIPC](kernel-small-bundles-ipc.md)
- [File Systems](kernel-small-bundles-fs.md) - File Systems
- [Virtual File System](kernel-small-bundles-fs-virtual.md) - [Virtual File System](kernel-small-bundles-fs-virtual.md)
- Supported File Systems - Supported File Systems
- [FAT](kernel-small-bundles-fs-support-fat.md) - [FAT](kernel-small-bundles-fs-support-fat.md)
...@@ -160,7 +160,7 @@ ...@@ -160,7 +160,7 @@
- [Working Principles](kernel-small-debug-user-function.md) - [Working Principles](kernel-small-debug-user-function.md)
- Usage - Usage
- [Available APIs](kernel-small-debug-user-guide-api.md) - [Available APIs](kernel-small-debug-user-guide-api.md)
- [How to Use](kernel-small-debug-user-guide-use.md) - How to Use
- [Calling APIs](kernel-small-debug-user-guide-use-api.md) - [Calling APIs](kernel-small-debug-user-guide-use-api.md)
- [Using the CLI](kernel-small-debug-user-guide-use-cli.md) - [Using the CLI](kernel-small-debug-user-guide-use-cli.md)
- [Typical Memory Problems](kernel-small-debug-user-faqs.md) - [Typical Memory Problems](kernel-small-debug-user-faqs.md)
......
...@@ -19,9 +19,8 @@ ...@@ -19,9 +19,8 @@
- [Burning](quickstart-ide-lite-steps-hi3516-burn.md) - [Burning](quickstart-ide-lite-steps-hi3516-burn.md)
- [Running](quickstart-ide-lite-steps-hi3516-running.md) - [Running](quickstart-ide-lite-steps-hi3516-running.md)
- Appendix - Appendix
- Introduction to Development Boards - [Introduction to the Hi3861 Development Board](quickstart-ide-lite-introduction-hi3861.md)
- [Introduction to the Hi3861 Development Board](quickstart-ide-lite-introduction-hi3861.md) - [Introduction to the Hi3516 Development Board](quickstart-ide-lite-introduction-hi3516.md)
- [Introduction to the Hi3516 Development Board](quickstart-ide-lite-introduction-hi3516.md)
- Getting Started with Mini and Small Systems (Installation Package Mode) - Getting Started with Mini and Small Systems (Installation Package Mode)
- [Mini and Small System Overview](quickstart-lite-overview.md) - [Mini and Small System Overview](quickstart-lite-overview.md)
- [Environment Preparation](quickstart-lite-env-setup.md) - [Environment Preparation](quickstart-lite-env-setup.md)
...@@ -67,9 +66,8 @@ ...@@ -67,9 +66,8 @@
- [Burning](quickstart-ide-standard-running-rk3568-burning.md) - [Burning](quickstart-ide-standard-running-rk3568-burning.md)
- [Running](quickstart-ide-standard-running-rk3568-running.md) - [Running](quickstart-ide-standard-running-rk3568-running.md)
- Appendix - Appendix
- Introduction to Development Boards - [Introduction to the Hi3516 Development Board](quickstart-ide-standard-board-introduction-hi3516.md)
- [Introduction to the Hi3516 Development Board](quickstart-ide-standard-board-introduction-hi3516.md) - [Introduction to the RK3568 Development Board](quickstart-ide-standard-board-introduction-rk3568.md)
- [Introduction to the RK3568 Development Board](quickstart-ide-standard-board-introduction-rk3568.md)
- Getting Started with Standard System (Installation Package Mode) - Getting Started with Standard System (Installation Package Mode)
- [Standard System Overview](quickstart-standard-overview.md) - [Standard System Overview](quickstart-standard-overview.md)
- [Setting Up Environments for Standard System](quickstart-standard-env-setup.md) - [Setting Up Environments for Standard System](quickstart-standard-env-setup.md)
......
...@@ -9,65 +9,69 @@ ...@@ -9,65 +9,69 @@
## 基本概念 ## 基本概念
- **KV数据模型** ### KV数据模型
“KV数据模型”是“Key-Value数据模型”的简称,“Key-Value”即“键-值”;其数据以键值对的形式进行组织、索引和存储。
KV数据模型适合不涉及过多数据关系和业务关系的业务数据存储,比SQL数据库存储拥有更好的读写性能,同时因其在分布式场景中降低了解决数据库版本兼容问题的复杂度,和数据同步过程中冲突解决的复杂度而被广泛使用。分布式数据库也是基于KV数据模型,对外提供KV类型的访问接口 “KV数据模型”是“Key-Value数据模型”的简称,“Key-Value”即“键-值”;其数据以键值对的形式进行组织、索引和存储
- **分布式数据库事务性** KV数据模型适合不涉及过多数据关系和业务关系的业务数据存储,比SQL数据库存储拥有更好的读写性能,同时因其在分布式场景中降低了解决数据库版本兼容问题的复杂度,和数据同步过程中冲突解决的复杂度而被广泛使用。分布式数据库也是基于KV数据模型,对外提供KV类型的访问接口。
分布式数据库事务支持本地事务(和传统数据库的事务概念一致)和同步事务。同步事务是指在设备之间同步数据时,以本地事务为单位进行同步,一次本地事务的修改要么都同步成功,要么都同步失败。
- **分布式数据库一致性** ### 分布式数据库事务性
在分布式场景中一般会涉及多个设备,组网内设备之间看到的数据是否一致称为分布式数据库的一致性。分布式数据库一致性可以分为**强一致性****弱一致性****最终一致性**
- **强一致性**:是指某一设备成功增、删、改数据后,组网内设备对该数据的读取操作都将得到更新后的值。 分布式数据库事务支持本地事务(和传统数据库的事务概念一致)和同步事务。同步事务是指在设备之间同步数据时,以本地事务为单位进行同步,一次本地事务的修改要么都同步成功,要么都同步失败。
- **弱一致性**:是指某一设备成功增、删、改数据后,组网内设备可能读取到本次更新数据,也可能读取不到,不能保证在多长时间后每个设备的数据一定是一致的。
- **最终一致性**:是指某一设备成功增、删、改数据后,组网内设备可能读取不到本次更新数据,但在某个时间窗口之后组网内设备的数据能够达到一致状态。
强一致性对分布式数据的管理要求非常高,在服务器的分布式场景可能会遇到。因为移动终端设备的不常在线、以及无中心的特性,分布式数据服务不支持强一致性,只支持最终一致性。 ### 分布式数据库一致性
- **分布式数据库同步** 在分布式场景中一般会涉及多个设备,组网内设备之间看到的数据是否一致称为分布式数据库的一致性。分布式数据库一致性可以分为**强一致性****弱一致性****最终一致性**
底层通信组件完成设备发现和认证,会通知上层应用程序(包括分布式数据服务)设备上线。收到设备上线的消息后分布式数据服务可以在两个设备之间建立加密的数据传输通道,利用该通道在两个设备之间进行数据同步。
分布式数据服务提供了两种同步方式:**手动同步****自动同步** - **强一致性**:是指某一设备成功增、删、改数据后,组网内设备对该数据的读取操作都将得到更新后的值。
- **弱一致性**:是指某一设备成功增、删、改数据后,组网内设备可能读取到本次更新数据,也可能读取不到,不能保证在多长时间后每个设备的数据一定是一致的。
- **最终一致性**:是指某一设备成功增、删、改数据后,组网内设备可能读取不到本次更新数据,但在某个时间窗口之后组网内设备的数据能够达到一致状态。
- **手动同步**:由应用程序调用sync接口来触发,需要指定同步的设备列表和同步模式。同步模式分为PULL_ONLY(将远端数据拉到本端)、PUSH_ONLY(将本端数据推送到远端)和PUSH_PULL(将本端数据推送到远端同时也将远端数据拉取到本端)。内部接口支持按条件过滤同步,将符合条件的数据同步到远端。 强一致性对分布式数据的管理要求非常高,在服务器的分布式场景可能会遇到。因为移动终端设备的不常在线、以及无中心的特性,分布式数据服务不支持强一致性,只支持最终一致性。
- **自动同步**:包括全量同步和按条件订阅同步。全量同步由分布式数据库自动将本端数据推送到远端,同时也将远端数据拉取到本端来完成数据同步,同步时机包括设备上线、应用程序更新数据等,应用不需要主动调用sync接口;内部接口支持按条件订阅同步,将远端符合订阅条件的数据自动同步到本端。
- **单版本分布式数据库** ### 分布式数据库同步
单版本是指数据在本地保存是以单个KV条目为单位的方式保存,对每个Key最多只保存一个条目项,当数据在本地被用户修改时,不管它是否已经被同步出去,均直接在这个条目上进行修改。同步也以此为基础,按照它在本地被写入或更改的顺序将当前最新一次修改逐条同步至远端设备。
- **设备协同分布式数据库** 底层通信组件完成设备发现和认证,会通知上层应用程序(包括分布式数据服务)设备上线。收到设备上线的消息后分布式数据服务可以在两个设备之间建立加密的数据传输通道,利用该通道在两个设备之间进行数据同步。
设备协同分布式数据库建立在单版本分布式数据库之上,对应用程序存入的KV数据中的Key前面拼接了本设备的DeviceID标识符,这样能保证每个设备产生的数据严格隔离,底层按照设备的维度管理这些数据,设备协同分布式数据库支持以设备的维度查询分布式数据,但是不支持修改远端设备同步过来的数据。
- **分布式数据库冲突解决策略** 分布式数据服务提供了两种同步方式:**手动同步****自动同步**
分布式数据库多设备提交冲突场景,在给提交冲突做合并的过程中,如果多个设备同时修改了同一数据,则称这种场景为数据冲突。数据冲突采用默认冲突解决策略(Last-write-wins),基于提交时间戳,取时间戳较大的提交数据,当前不支持定制冲突解决策略。
- **数据库Schema化管理与谓词查询** - **手动同步**:由应用程序调用sync接口来触发,需要指定同步的设备列表和同步模式。同步模式分为PULL_ONLY(将远端数据拉到本端)、PUSH_ONLY(将本端数据推送到远端)和PUSH_PULL(将本端数据推送到远端同时也将远端数据拉取到本端)。内部接口支持按条件过滤同步,将符合条件的数据同步到远端。
单版本数据库支持在创建和打开数据库时指定Schema,数据库根据Schema定义感知KV记录的Value格式,以实现对Value值结构的检查,并基于Value中的字段实现索引建立和谓词查询 - **自动同步**:包括全量同步和按条件订阅同步。全量同步由分布式数据库自动将本端数据推送到远端,同时也将远端数据拉取到本端来完成数据同步,同步时机包括设备上线、应用程序更新数据等,应用不需要主动调用sync接口;内部接口支持按条件订阅同步,将远端符合订阅条件的数据自动同步到本端
- **分布式数据库备份能力** ### 单版本分布式数据库
提供分布式数据库备份能力,业务通过设置backup属性为true,可以触发分布式数据服务每日备份。当分布式数据库发生损坏,分布式数据服务会删除损坏数据库,并且从备份数据库中恢复上次备份的数据。如果不存在备份数据库,则创建一个新的数据库。同时支持加密数据库的备份能力。
单版本是指数据在本地保存是以单个KV条目为单位的方式保存,对每个Key最多只保存一个条目项,当数据在本地被用户修改时,不管它是否已经被同步出去,均直接在这个条目上进行修改。同步也以此为基础,按照它在本地被写入或更改的顺序将当前最新一次修改逐条同步至远端设备。
### 设备协同分布式数据库
设备协同分布式数据库建立在单版本分布式数据库之上,对应用程序存入的KV数据中的Key前面拼接了本设备的DeviceID标识符,这样能保证每个设备产生的数据严格隔离,底层按照设备的维度管理这些数据,设备协同分布式数据库支持以设备的维度查询分布式数据,但是不支持修改远端设备同步过来的数据。
### 分布式数据库冲突解决策略
分布式数据库多设备提交冲突场景,在给提交冲突做合并的过程中,如果多个设备同时修改了同一数据,则称这种场景为数据冲突。数据冲突采用默认冲突解决策略(Last-write-wins),基于提交时间戳,取时间戳较大的提交数据,当前不支持定制冲突解决策略。
### 数据库Schema化管理与谓词查询
单版本数据库支持在创建和打开数据库时指定Schema,数据库根据Schema定义感知KV记录的Value格式,以实现对Value值结构的检查,并基于Value中的字段实现索引建立和谓词查询。
### 分布式数据库备份能力
提供分布式数据库备份能力,业务通过设置backup属性为true,可以触发分布式数据服务每日备份。当分布式数据库发生损坏,分布式数据服务会删除损坏数据库,并且从备份数据库中恢复上次备份的数据。如果不存在备份数据库,则创建一个新的数据库。同时支持加密数据库的备份能力。
## 运作机制 ## 运作机制
分布式数据服务支撑OpenHarmony系统上应用程序数据库数据分布式管理,支持数据在相同帐号的多端设备之间相互同步,为用户在多端设备上提供一致的用户体验,分布式数据服务包含五部分: 分布式数据服务支撑OpenHarmony系统上应用程序数据库数据分布式管理,支持数据在相同帐号的多端设备之间相互同步,为用户在多端设备上提供一致的用户体验,分布式数据服务包含五部分:
- **服务接口** - **服务接口:** 分布式数据服务提供专门的数据库创建、数据访问、数据订阅等接口给应用程序调用,接口支持KV数据模型,支持常用的数据类型,同时确保接口的兼容性、易用性和可发布性。
分布式数据服务提供专门的数据库创建、数据访问、数据订阅等接口给应用程序调用,接口支持KV数据模型,支持常用的数据类型,同时确保接口的兼容性、易用性和可发布性。
- **服务组件** - **服务组件:** 服务组件负责服务内元数据管理、权限管理、加密管理、备份和恢复管理以及多用户管理等、同时负责初始化底层分布式DB的存储组件、同步组件和通信适配层。
服务组件负责服务内元数据管理、权限管理、加密管理、备份和恢复管理以及多用户管理等、同时负责初始化底层分布式DB的存储组件、同步组件和通信适配层。
- **存储组件** - **存储组件:** 存储组件负责数据的访问、数据的缩减、事务、快照、数据库加密,以及数据合并和冲突解决等特性。
存储组件负责数据的访问、数据的缩减、事务、快照、数据库加密,以及数据合并和冲突解决等特性。
- **同步组件** - **同步组件:** 同步组件连结了存储组件与通信组件,其目标是保持在线设备间的数据库数据一致性,包括将本地产生的未同步数据同步给其他设备,接收来自其他设备发送过来的数据,并合并到本地设备中。
同步组件连结了存储组件与通信组件,其目标是保持在线设备间的数据库数据一致性,包括将本地产生的未同步数据同步给其他设备,接收来自其他设备发送过来的数据,并合并到本地设备中。
- **通信适配层** - **通信适配层:** 通信适配层负责调用底层公共通信层的接口完成通信管道的创建、连接,接收设备上下线消息,维护已连接和断开设备列表的元数据,同时将设备上下线信息发送给上层同步组件,同步组件维护连接的设备列表,同步数据时根据该列表,调用通信适配层的接口将数据封装并发送给连接的设备。
通信适配层负责调用底层公共通信层的接口完成通信管道的创建、连接,接收设备上下线消息,维护已连接和断开设备列表的元数据,同时将设备上下线信息发送给上层同步组件,同步组件维护连接的设备列表,同步数据时根据该列表,调用通信适配层的接口将数据封装并发送给连接的设备。
应用程序通过调用分布式数据服务接口实现分布式数据库创建、访问、订阅功能,服务接口通过操作服务组件提供的能力,将数据存储至存储组件,存储组件调用同步组件实现将数据同步,同步组件使用通信适配层将数据同步至远端设备,远端设备通过同步组件接收数据,并更新至本端存储组件,通过服务接口提供给应用程序使用。 应用程序通过调用分布式数据服务接口实现分布式数据库创建、访问、订阅功能,服务接口通过操作服务组件提供的能力,将数据存储至存储组件,存储组件调用同步组件实现将数据同步,同步组件使用通信适配层将数据同步至远端设备,远端设备通过同步组件接收数据,并更新至本端存储组件,通过服务接口提供给应用程序使用。
...@@ -83,6 +87,7 @@ ...@@ -83,6 +87,7 @@
- 分布式数据服务的数据模型仅支持KV数据模型,不支持外键、触发器等关系型数据库中的功能。 - 分布式数据服务的数据模型仅支持KV数据模型,不支持外键、触发器等关系型数据库中的功能。
- 分布式数据服务支持的KV数据模型规格: - 分布式数据服务支持的KV数据模型规格:
- 设备协同数据库,针对每条记录,Key的长度≤896 Byte,Value的长度&lt;4 MB。 - 设备协同数据库,针对每条记录,Key的长度≤896 Byte,Value的长度&lt;4 MB。
- 单版本数据库,针对每条记录,Key的长度≤1 KB,Value的度&lt;4 MB。 - 单版本数据库,针对每条记录,Key的长度≤1 KB,Value的度&lt;4 MB。
- 每个应用程序最多支持同时打开16个分布式数据库。 - 每个应用程序最多支持同时打开16个分布式数据库。
......
...@@ -9,7 +9,7 @@ USB服务是应用访问底层的一种设备抽象概念。开发者根据提 ...@@ -9,7 +9,7 @@ USB服务是应用访问底层的一种设备抽象概念。开发者根据提
USB服务系统包含USB API、USB Service、USB HAL。 USB服务系统包含USB API、USB Service、USB HAL。
**图2** USB服务运作机制 **图1** USB服务运作机制
![zh-cn_image_0000001237821727](figures/zh-cn_image_0000001237821727.png) ![zh-cn_image_0000001237821727](figures/zh-cn_image_0000001237821727.png)
......
...@@ -596,16 +596,15 @@ KVStore数据库类型枚举。 ...@@ -596,16 +596,15 @@ KVStore数据库类型枚举。
数据库的安全级别枚举。 数据库的安全级别枚举。
**系统能力:** SystemCapability.DistributedDataManager.KVStore.Core
| 名称 | 值 | 说明 | | 名称 | 值 | 说明 |
| --- | ---- | ----------------------- | | --- | ---- | ----------------------- |
| NO_LEVEL | 0 | 表示数据库不设置安全级别。 | | NO_LEVEL | 0 | 表示数据库不设置安全级别。<br>**系统能力:** SystemCapability.DistributedDataManager.KVStore.DistributedKVStore |
| S0 | 1 | 表示数据库的安全级别为公共级别。 | | S0 | 1 | 表示数据库的安全级别为公共级别。<br>**系统能力:** SystemCapability.DistributedDataManager.KVStore.Core |
| S1 | 2 | 表示数据库的安全级别为低级别,当数据泄露时会产生较低影响。例如,包含壁纸等系统数据的数据库。 | | S1 | 2 | 表示数据库的安全级别为低级别,当数据泄露时会产生较低影响。例如,包含壁纸等系统数据的数据库。<br>**系统能力:** SystemCapability.DistributedDataManager.KVStore.Core |
| S2 | 3 | 表示数据库的安全级别为中级别,当数据泄露时会产生较大影响。例如,包含录音、视频等用户生成数据或通话记录等信息的数据库。 | | S2 | 3 | 表示数据库的安全级别为中级别,当数据泄露时会产生较大影响。例如,包含录音、视频等用户生成数据或通话记录等信息的数据库。<br>**系统能力:** SystemCapability.DistributedDataManager.KVStore.Core |
| S3 | 5 | 表示数据库的安全级别为高级别,当数据泄露时会产生重大影响。例如,包含用户运动、健康、位置等信息的数据库。 | | S3 | 5 | 表示数据库的安全级别为高级别,当数据泄露时会产生重大影响。例如,包含用户运动、健康、位置等信息的数据库。<br>**系统能力:** SystemCapability.DistributedDataManager.KVStore.Core |
| S4 | 6 | 表示数据库的安全级别为关键级别,当数据泄露时会产生严重影响。例如,包含认证凭据、财务数据等信息的数据库。 | | S4 | 6 | 表示数据库的安全级别为关键级别,当数据泄露时会产生严重影响。例如,包含认证凭据、财务数据等信息的数据库。<br>**系统能力:** SystemCapability.DistributedDataManager.KVStore.Core |
## Constants ## Constants
......
# 设置数据项名称 # 设置数据项名称
> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** 本模块提供访问设置数据项的能力。
> 本模块首批接口从API version 8开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
本模块提供设置数据项的访问功能相关接口的说明及示例。
> **说明:**
>
> 本模块首批接口从API version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
## 导入模块 ## 导入模块
```typescript ```ts
import settings from '@ohos.settings'; import settings from '@ohos.settings';
``` ```
## date
提供设置时间和日期格式的数据项。
### 属性
**系统能力:** SystemCapability.Applications.settings.Core
| 名称 | 类型 | 可读 | 可写 | 说明 |
| ------------------- | ------ | ---- | ---- | ------------------------------------------------------------ |
| DATE_FORMAT | string | 是 | 是 | 日期格式。<br/>日期格式包括mm/dd/yyyy、dd/mm/yyyy和yyyy/mm/dd ,其中mm、dd和yyyy分别代表月份、日期和年份。 |
| TIME_FORMAT | string | 是 | 是 | 时间是以12小时格式还是24小时格式显示。<br>值为 “12” 表示12小时格式;<br/>值为 ”24“ 表示24小时格式。 |
| AUTO_GAIN_TIME | string | 是 | 是 | 是否自动从网络获取日期、时间和时区。 <br>值为true表示自动从网络获取信息;<br/>值为false表示不自动获取。 |
| AUTO_GAIN_TIME_ZONE | string | 是 | 是 | 是否自动从NITZ获取时区。 <br>值为true表示自动获取;<br/>值为false表示不自动获取。 |
## display
提供设置显示效果的数据项。
### 属性
**系统能力:** SystemCapability.Applications.settings.Core
| 名称 | 类型 | 可读 | 可写 | 说明 |
| ----------------------------- | ------ | ---- | ---- | ------------------------------------------------------------ |
| FONT_SCALE | string | 是 | 是 | 字体的比例因子,值为浮点数。 |
| SCREEN_BRIGHTNESS_STATUS | string | 是 | 是 | 屏幕亮度。该值的范围从0到255。 |
| AUTO_SCREEN_BRIGHTNESS | string | 是 | 是 | 是否启用屏幕亮度自动调整。<br/>值为AUTO_SCREEN_BRIGHTNESS_MODE,表示启用自动调整;<br/>值为MANUAL_SCREEN_BRIGHTNESS_MODE,表示不启用自动调整。 |
| AUTO_SCREEN_BRIGHTNESS_MODE | number | 是 | 是 | 使用屏幕亮度自动调整时AUTO_SCREEN_BRIGHTNESS的值。 |
| MANUAL_SCREEN_BRIGHTNESS_MODE | number | 是 | 是 | 使用屏幕亮度手动调整时的AUTO_SCREEN_BRIGHTNESS值。 |
| SCREEN_OFF_TIMEOUT | string | 是 | 是 | 设备在一段时间不活动后进入睡眠状态的等待时间(单位:ms)。 |
| DEFAULT_SCREEN_ROTATION | string | 是 | 是 | 启用屏幕的自动旋转时,此属性无效;不启用自动旋转时,以下值可用:<br>值为0,表示屏幕旋转0度;<br>值为1,表示屏幕旋转90度;<br/>值为2,表示屏幕旋转180度;<br/>值为3,表示屏幕旋转270度。 |
| ANIMATOR_DURATION_SCALE | string | 是 | 是 | 动画持续时间的比例因子。这会影响所有此类动画的开始延迟和持续时间。<br/>值为0,表示动画将立即结束,默认值为1。 |
| TRANSITION_ANIMATION_SCALE | string | 是 | 是 | 过渡动画的比例因子。<br/>值为0,表示禁用过渡动画。 |
| WINDOW_ANIMATION_SCALE | string | 是 | 是 | 普通窗口动画的比例因子。<br/>值为0,表示禁用窗口动画。 |
| DISPLAY_INVERSION_STATUS | string | 是 | 是 | 是否启用显示颜色反转。<br/>值为1,表示启用显示颜色反转;<br/>值为0,表示不启用显示颜色反转。 |
## general
提供设置设备常规信息的数据项。
### 属性
**系统能力:** SystemCapability.Applications.settings.Core
| 名称 | 类型 | 可读 | 可写 | 说明 |
| -------------------------------- | ------ | ---- | ---- | ------------------------------------------------------------ |
| SETUP_WIZARD_FINISHED | string | 是 | 是 | 是否已运行启动向导。<br>值为0,表示启动向导尚未运行;<br/>值不是0,表示启动向导已运行。 |
| END_BUTTON_ACTION | string | 是 | 是 | 在用户不在呼叫中时,用户按下呼叫结束按钮会发生的情况。<br/>值为0,表示没有任何反应;<br/>值为1,表示显示主屏幕;<br/>值为2,表示设备进入睡眠状态,屏幕锁定;<br/>值为3,表示显示主屏幕。如果用户已在主屏幕上,设备将进入睡眠状态。 |
| ACCELEROMETER_ROTATION_STATUS | string | 是 | 是 | 是否使用加速计更改屏幕方向,即是否启用自动旋转。<br>值为1,表示启用加速度计;<br/>值为0,表示不启用加速计。 |
| AIRPLANE_MODE_STATUS | string | 是 | 是 | 是否启用飞行模式。<br>值为1,表示启用飞行模式;<br/>值为0,表示不启用飞行模式。 |
| DEVICE_PROVISION_STATUS | string | 是 | 是 | 是否预配设备。<br>在具有单个系统用户的多用户设备上,当值为true时,屏幕可能会被锁定。此外,其他功能无法在系统用户上启动,除非它们被标记为在屏幕锁定上显示。 |
| HDC_STATUS | string | 是 | 是 | 是否启用USB设备上的硬盘控制器(HDC)。<br>值为true,表示启用HDC;<br/>值为false,表示不启用HDC。 |
| BOOT_COUNTING | string | 是 | 是 | 设备开机后的启动操作数。 |
| CONTACT_METADATA_SYNC_STATUS | string | 是 | 是 | 是否启用联系人元数据同步。<br>值为true,表示启用同步;<br/>值为false,表示不启用同步。 |
| DEVELOPMENT_SETTINGS_STATUS | string | 是 | 是 | 是否启用开发人员选项。<br>值为true,表示启用开发人员选项;<br/>值为false,表示不启用开发人员选项。 |
| DEVICE_NAME | string | 是 | 是 | 设备名称。 |
| USB_STORAGE_STATUS | string | 是 | 是 | 是否启用USB大容量存储。<br>值为true,表示启用USB大容量存储;<br/>值为false,表示不启用USB大容量存储。 |
| DEBUGGER_WAITING | string | 是 | 是 | 设备在启动应用程序进行调试时是否等待调试器进行调试。<br>值为1,表示设备等待调试器;<br/>值为0,表示系统不会等待调试器,因此应用程序会正常运行。 |
| DEBUG_APP_PACKAGE | string | 是 | 是 | 要调试的应用程序的bundle name。 |
| ACCESSIBILITY_STATUS | string | 是 | 是 | 是否启用辅助功能。<br>值为1,表示启用辅助功能;<br/>值为0,表示不启用辅助功能。 |
| ACTIVATED_ACCESSIBILITY_SERVICES | string | 是 | 是 | 已激活的辅助功能的列表。 |
| GEOLOCATION_ORIGINS_ALLOWED | string | 是 | 是 | 浏览器可以使用的默认地理位置。多个地理位置由空格分隔。 |
| SKIP_USE_HINTS | string | 是 | 是 | 应用程序是否应在首次启动时尝试跳过所有介绍性提示。这适用于临时用户或熟悉环境的用户。<br>值为1,表示应用程序将尝试在第一次启动时跳过所有介绍性提示;<br/>值为0,表示应用程序不会在首次启动时跳过介绍性提示。 |
| TOUCH_EXPLORATION_STATUS | string | 是 | 是 | 是否启用触摸浏览。<br>值为1,表示启用触摸浏览;<br/>值为0,表示不启用触摸浏览。 |
## input
提供设置有关输入法信息的数据项。
### 属性
**系统能力:** SystemCapability.Applications.settings.Core
| 名称 | 类型 | 可读 | 可写 | 说明 |
| ------------------------------------ | ------ | ---- | ---- | ------------------------------------------------------------ |
| DEFAULT_INPUT_METHOD | string | 是 | 是 | 默认输入法及其ID。 |
| ACTIVATED_INPUT_METHOD_SUB_MODE | string | 是 | 是 | 默认输入法键盘类型及其ID。 |
| ACTIVATED_INPUT_METHODS | string | 是 | 是 | 已激活的输入法的列表。<br>该列表是一个字符串,由已激活的输入法的ID和输入法键盘类型组成。输入法ID后添加冒号':'连接,输入法的键盘类型后添加分号';'连接。用ima代表输入法ID,keyboardType代表键盘类型,示例格式是ima0:keyboardType0;keyboardType1;ima1:ima2:keyboardTypes0。 |
| SELECTOR_VISIBILITY_FOR_INPUT_METHOD | string | 是 | 是 | 输入法选择器是否可见。<br>值为1,表示输入法选择器可见;<br/>值为0,表示输入法选择器不可见。 |
| AUTO_CAPS_TEXT_INPUT | string | 是 | 是 | 是否为文本编辑器启用自动大写。<br>值为0,表示不启用自动大写;<br/>值为1,表示启用自动大写。 |
| AUTO_PUNCTUATE_TEXT_INPUT | string | 是 | 是 | 是否为文本编辑器启用自动标点符号。自动标点符号使文本编辑器能够将两个空格转换为句点'.'和空格。<br>值为0,表示不启用自动标点符号;<br/>值为1,表示启用自动标点符号。 |
| AUTO_REPLACE_TEXT_INPUT | string | 是 | 是 | 是否为文本编辑器启用自动更正。自动更正使文本编辑器能够更正拼写错误。<br>值为0,表示不启用自动更正;<br/>值为1,表示启用自动更正。 |
| SHOW_PASSWORD_TEXT_INPUT | string | 是 | 是 | 是否在文本编辑器中启用密码显示。密码显示使文本编辑器能够在用户键入密码字符时显示密码字符。<br>值为0,表示不启用密码显示;<br/>值为1,表示启用密码显示。 |
## network
提供设置网络信息的数据项。
### 属性
**系统能力:** SystemCapability.Applications.settings.Core
| 名称 | 类型 | 可读 | 可写 | 说明 |
| ------------------------ | ------ | ---- | ---- | ------------------------------------------------------------ |
| DATA_ROAMING_STATUS | string | 是 | 是 | 是否启用数据漫游。<br>值为true,表示启用数据漫游;<br/>值为false,表示不启用数据漫游。 |
| HTTP_PROXY_CFG | string | 是 | 是 | 全局 HTTP 代理的主机名和端口号。主机名和端口号由冒号':'分隔。 |
| NETWORK_PREFERENCE_USAGE | string | 是 | 是 | 要使用的网络的用户首选项。 |
## phone
提供设置来电和去电接听方式的数据项。
### 属性
**系统能力:** SystemCapability.Applications.settings.Core
| 名称 | 类型 | 可读 | 可写 | 说明 |
| ------------------ | ------ | ---- | ---- | ------------------------------------------------------------ |
| RTT_CALLING_STATUS | string | 是 | 是 | 是否启用实时文本 (RTT) 呼叫。启用,来电和去电在设备和运营商支持时作为 RTT 呼叫应答。 <br> 值为1,表示启用RTT 呼叫; <br/> 值为0,表示不启用 RTT 呼叫。 |
## sound
提供设置声音效果的数据项。
### 属性
**系统能力:** SystemCapability.Applications.settings.Core
| 名称 | 类型 | 可读 | 可写 | 说明 |
| ---------------------------- | ------ | ---- | ---- | ------------------------------------------------------------ |
| VIBRATE_WHILE_RINGING | string | 是 | 是 | 设备在来电响铃时是否振动。此属性将由电话和设置应用程序使用。 该值是布尔类型,仅影响设备因来电而响铃的情况,不影响任何其他应用程序或场景。 |
| DEFAULT_ALARM_ALERT | string | 是 | 是 | 系统默认告警的存储区域。 |
| DTMF_TONE_TYPE_WHILE_DIALING | string | 是 | 是 | 拨号时播放的双音多频 (DTMF) 音的类型。 <br>值为0表示常规的短音效,<br/>值为1表示长音效。 |
| DTMF_TONE_WHILE_DIALING | string | 是 | 是 | 拨号时是否播放 DTMF 音。<br>值为1,表示播放 DTMF 音;<br/>值为0,表示不播放。 |
| AFFECTED_MODE_RINGER_STREAMS | string | 是 | 是 | 哪些音频流受振铃模式和请勿打扰 (DND) 模式更改的影响。希望特定的音频流受到振铃模式和 DDN 模式变化的影响,请将对应比特位设置为1。 |
| AFFECTED_MUTE_STREAMS | string | 是 | 是 | 受静音模式影响的音频流。希望特定音频流在静音模式下保持静音,请将相应位设置为1。 |
| DEFAULT_NOTIFICATION_SOUND | string | 是 | 是 | 系统默认通知音的存储区域。 |
| DEFAULT_RINGTONE | string | 是 | 是 | 系统默认铃声的存储区域。 |
| SOUND_EFFECTS_STATUS | string | 是 | 是 | 声音功能是否可用。<br>值为0表示不可用; <br/>值为1表示可用 |
| VIBRATE_STATUS | string | 是 | 是 | 设备是否为事件振动。该参数在系统内部使用。 <br>值为1,表示设备会因事件而振动; <br/>值为0,表示设备不因事件振动。 |
| HAPTIC_FEEDBACK_STATUS | string | 是 | 是 | 设备是否启用触觉反馈。<br/>值为true,表示启用触觉反馈;<br/>值为false,表示不启用触觉反馈。 |
## TTS
提供设置文本到语音 (TTS) 转换信息的数据项。
### 属性
**系统能力:** SystemCapability.Applications.settings.Core
| 名称 | 类型 | 可读 | 可写 | 说明 |
| ------------------- | ------ | ---- | ---- | ------------------------------------------------------------ |
| DEFAULT_TTS_PITCH | string | 是 | 是 | 文本转语音 (TTS) 引擎的默认音高。<br>其中100=1x,该值设置为200,表示频率是正常声音频率的两倍。 |
| DEFAULT_TTS_RATE | string | 是 | 是 | TTS 引擎的默认语速。<br>其中100=1x。 |
| DEFAULT_TTS_SYNTH | string | 是 | 是 | 默认TTS引擎。 |
| ENABLED_TTS_PLUGINS | string | 是 | 是 | 用于TTS的已激活插件包列表, 多个插件包以空格分隔。 |
## wireless
提供设置无线网络信息的数据项。
### 属性
**系统能力:** SystemCapability.Applications.settings.Core
| 名称 | 类型 | 可读 | 可写 | 说明 |
| --------------------------------- | ------ | ---- | ---- | ------------------------------------------------------------ |
| BLUETOOTH_DISCOVER_ABILITY_STATUS | string | 是 | 是 | 设备是否可以被其他设备通过蓝牙发现或连接。<br>值为0表示设备不可以被连接或发现;<br/>值为1表示设备可以被连接但不可以被发现;<br/>值为2表示设备可以被连接和发现。 |
| BLUETOOTH_DISCOVER_TIMEOUT | string | 是 | 是 | 可以通过蓝牙发现设备的持续时间(以秒为单位)。<br>这段时间之后,设备不可以被蓝牙搜寻到。 |
| AIRPLANE_MODE_RADIOS | string | 是 | 是 | 启用飞行模式时要禁用的无线电信号列表。 <br>多个无线电信号用逗号 (,) 分隔。取值包括以下常量:BLUETOOTH_RADIO、 CELL_RADIO、 NFC_RADIO、 WIFI_RADIO。 |
| BLUETOOTH_RADIO | string | 是 | 否 | 常量,作为AIRPLANE_MODE_RADIOS的取值时表示蓝牙在飞行模式下禁用。 |
| CELL_RADIO | string | 是 | 否 | 常量,作为AIRPLANE_MODE_RADIOS的取值时表示蜂窝无线电在飞行模式下禁用。 |
| NFC_RADIO | string | 是 | 否 | 常量,作为AIRPLANE_MODE_RADIOS的取值时表示NFC在飞行模式下禁用。 |
| WIFI_RADIO | string | 是 | 否 | 常量,作为AIRPLANE_MODE_RADIOS的取值时表示Wi-Fi在飞行模式下禁用。 |
| BLUETOOTH_STATUS | string | 是 | 是 | 蓝牙是否可用。 <br>值为true表示蓝牙可用;<br/>值为false表示蓝牙不可用。 |
| OWNER_LOCKDOWN_WIFI_CFG | string | 是 | 是 | 是否应锁定由设备所有者的应用程序创建的Wi-Fi配置。<br>值为true表示Wi-Fi配置应该被锁定;<br/>值为false表示不应该被锁定。 |
| WIFI_DHCP_MAX_RETRY_COUNT | string | 是 | 是 | 尝试从DHCP服务器获取 IP 地址的最大次数。 |
| WIFI_TO_MOBILE_DATA_AWAKE_TIMEOUT | string | 是 | 是 | Wi-Fi连接断开后等待移动数据连接建立时保持唤醒锁的最长时间。 |
| WIFI_STATUS | string | 是 | 是 | Wi-Fi是否可用。<br>值为true表示Wi-Fi可用;<br/>值为false表示Wi-Fi不可用。 |
| WIFI_WATCHDOG_STATUS | string | 是 | 是 | Wi-Fi的WatchDog是否可用。 <br>值为true表示可用;<br/>值为false表示不可用。 |
## setting.getURI
getURI(name: string, callback: AsyncCallback\<object>): void
获取数据项的URI。使用callback异步回调。
**系统能力**:SystemCapability.Applications.settings.Core
**参数**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------- | ---- | ------------------------------------------------------------ |
| name | string | 是 | 数据项的名称。数据项名称分为以下两种:<br>- 上述任意一个数据库中已存在的数据项。<br>- 开发者自行添加的数据项。 |
| callback | AsyncCallback\<object> | 是 | 回调函数。获取数据项的URI。 |
**示例**
```js
settings.getUri(settings.display.SCREEN_BRIGHTNESS_STATUS, (uri) => {
console.log(`callback:uri -> ${JSON.stringify(uri)}`)
})
```
## setting.getURI
getURI(name: string): Promise\<object>
获取数据项的URI。使用Promise异步回调。
**系统能力**:SystemCapability.Applications.settings.Core
**参数**
| 参数名 | 类型 | 必填 | 说明 |
| ------ | ------ | ---- | ------------------------------------------------------------ |
| name | string | 是 | 数据项的名称。数据项名称分为以下两种:<br>- 上述任意一个数据库中已存在的数据项。<br>- 开发者自行添加的数据项。 |
**返回值**
| 类型 | 说明 |
| ---------------- | ------------------------------------ |
| Promise\<object> | Promise对象。返回获取的数据项的URI。 |
**示例**
```js
settings.getUri(settings.display.SCREEN_BRIGHTNESS_STATUS).then((uri) => {
console.log(`promise:uri -> ${JSON.stringify(uri)}`)
})
```
## setting.getValue
getValue(dataAbilityHelper: DataAbilityHelper, name: string, callback: AsyncCallback\<object>): void
获取数据库中指定数据项的值。使用callback异步回调。
**系统能力**:SystemCapability.Applications.settings.Core
**参数**
| 参数名 | 类型 | 必填 | 说明 |
| ----------------- | ------------------------------------------------- | ---- | ------------------------------------------------------------ |
| dataAbilityHelper | [DataAbilityHelper](js-apis-dataAbilityHelper.md) | 是 | 数据管理辅助类。 |
| name | string | 是 | 数据项的名称。数据项名称分为以下两种:<br> - 上述任意一个数据库中已存在的数据项。<br>- 开发者自行添加的数据项。 |
| callback | AsyncCallback\<object> | 是 | 使用callback方式获取数据项的值。 |
**示例**
```js
let uri = settings.getUriSync(settings.display.SCREEN_BRIGHTNESS_STATUS);
let helper = featureAbility.acquireDataAbilityHelper(uri);
settings.getValue(helper, settings.display.SCREEN_BRIGHTNESS_STATUS, (err, value) => {
if (err) {
console.error(`Failed to get the setting. ${err.message} `);
return;
}
console.log(`callback:value -> ${JOSN.stringify(value)}`)
});
```
## setting.getValue
getValue(dataAbilityHelper: DataAbilityHelper, name: string): Promise\<object>
获取数据库中指定数据项的值。使用Promise异步回调。
**系统能力**:SystemCapability.Applications.settings.Core
## settings.getUriSync **参数**
| 参数名 | 类型 | 必填 | 说明 |
| ----------------- | ------------------------------------------------- | ---- | ------------------------------------------------------------ |
| dataAbilityHelper | [DataAbilityHelper](js-apis-dataAbilityHelper.md) | 是 | 数据管理辅助类。 |
| name | string | 是 | 数据项的名称。数据项名称分为以下两种:<br> - 上述任意一个数据库中已存在的数据项。<br>- 开发者自行添加的数据项。 |
**返回值**
| 类型 | 说明 |
| ---------------- | ----------------------------------- |
| Promise\<object> | Promise对象。返回获得的数据项的值。 |
**示例**
```js
let uri = settings.getUriSync(settings.display.SCREEN_BRIGHTNESS_STATUS);
let helper = featureAbility.acquireDataAbilityHelper(uri);
settings.getValue(helper, settings.display.SCREEN_BRIGHTNESS_STATUS).then((value) => {
console.log(`promise:value -> ${JOSN.stringify(value)}`)
});
```
## settings.setValue
setValue(dataAbilityHelper: DataAbilityHelper, name: string, value: object, callback: AsyncCallback\<boolean>): void
将数据项名称及数据项的值保存到数据库中。使用callback异步回调。
**系统能力**:SystemCapability.Applications.settings.Core
**参数**
| 参数名 | 类型 | 必填 | 说明 |
| ----------------- | ------------------------------------------------- | ---- | ------------------------------------------------------------ |
| dataAbilityHelper | [DataAbilityHelper](js-apis-dataAbilityHelper.md) | 是 | 数据管理辅助类。 |
| name | string | 是 | 数据项的名称。数据项名称分为以下两种:<br>- 上述任意一个数据库中已存在的数据项。<br>- 开发者自行添加的数据项。 |
| value | object | 是 | 数据项值。取值范围随业务变动。 |
| callback | AsyncCallback\<boolean> | 是 | 回调函数。返回true表示操作成功,否则操作失败。 |
**示例**
```js
import featureAbility from '@ohos.ability.featureAbility';
//更新数据项亮度的值(该数据项在数据库中已存在,故setValue方法将更新该数据项的值)
let uri = settings.getUriSync(settings.display.SCREEN_BRIGHTNESS_STATUS);
let helper = featureAbility.acquireDataAbilityHelper(uri);
settings.setValue(helper, settings.display.SCREEN_BRIGHTNESS_STATUS, '100', (status) => {
console.log('Callback return whether value is set.');
});
```
## settings.setValue
setValue(dataAbilityHelper: DataAbilityHelper, name: string, value: object): Promise\<boolean>
将数据项名称及数据项的值保存到数据库中。使用Promise异步回调。
**系统能力**:SystemCapability.Applications.settings.Core
**参数**
| 参数名 | 类型 | 必填 | 说明 |
| ----------------- | ------------------------------------------------- | ---- | ------------------------------------------------------------ |
| dataAbilityHelper | [DataAbilityHelper](js-apis-dataAbilityHelper.md) | 是 | 数据管理辅助类。 |
| name | string | 是 | 数据项的名称。数据项名称分为以下两种:<br>- 上述任意一个数据库中已存在的数据项。<br>- 开发者自行添加的数据项。 |
| value | object | 是 | 数据项值。取值范围随业务变动。 |
**返回值**
| 类型 | 说明 |
| ----------------- | -------------------------------------------------- |
| Promise\<boolean> | Promise对象。返回true表示操作成功,否则返回false。 |
**示例**
```js
import featureAbility from '@ohos.ability.featureAbility';
//更新数据项亮度的值(该数据项在数据库中已存在,故setValue方法将更新该数据项的值)
let uri = settings.getUriSync(settings.display.SCREEN_BRIGHTNESS_STATUS);
let helper = featureAbility.acquireDataAbilityHelper(uri);
settings.setValue(helper, settings.display.SCREEN_BRIGHTNESS_STATUS, '100').then((status) => {
console.log('Callback return whether value is set.');
});
```
## settings.enableAirplaneMode
enableAirplaneMode(enable: boolean, callback: AsyncCallback\<void>): void
启用或禁用飞行模式。使用callback异步回调。
**系统能力**:SystemCapability.Applications.settings.Core
**参数**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------------------- | ---- | ----------------------------------------------- |
| enable | boolean | 是 | 是否开启飞行模式。true表示开启,false表示禁用。 |
| callback | AsyncCallback\<void> | 是 | 回调函数。 |
**示例**
```js
isEnabled =true;
enableAirplaneMode(isEnabled, (err) => {
if(err) {
console.log('Failed to enable AirplaneMode.');
return;
}
console.log('Return true if enable.');
})
```
## settings.enableAirplaneMode
enableAirplaneMode(enable: boolean): Promise<void>
启用或禁用飞行模式。使用Promise异步回调。
**系统能力**:SystemCapability.Applications.settings.Core
**参数**
| 参数名 | 类型 | 必填 | 说明 |
| ------ | ------- | ---- | ----------------------------------------------- |
| enable | boolean | 是 | 是否开启飞行模式。true表示开启,false表示禁用。 |
**返回值**
| 类型 | 说明 |
| -------------- | ------------------------- |
| Promise\<void> | 无返回结果的Promise对象。 |
**示例**
```js
isEnabled =true;
enableAirplaneMode(isEnabled).then((err) => {
if(err) {
console.log('Failed to enable AirplaneMode.');
return;
}
console.log('Return true if enable.');
});
```
## settings.canShowFloating
canShowFloating(callback: AsyncCallback\<boolean>): void
检查应用是否能够以悬浮窗形式显示。使用callback异步回调。
**系统能力**:SystemCapability.Applications.settings.Core
**参数**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------- | ---- | ------------------------------------------------------------ |
| callback | AsyncCallback\<boolean> | 是 | 回调函数。<br/>返回true,表示应用能够以悬浮窗形式显示;返回false,则表示不能。 |
**示例**
```js
canShowFloating((status) => {
console.log('Checks whether a specified application can show as float window.');
});
```
## settings.canShowFloating
canShowFloating(): Promise\<boolean>
检查应用是否能够以悬浮窗形式显示。使用Promise异步回调。
**系统能力**:SystemCapability.Applications.settings.Core
**返回值**
| 类型 | 说明 |
| ----------------- | ------------------------------------------------------------ |
| Promise\<boolean> | Promise对象。<br/>返回true,表示应用能够以悬浮窗形式显示;返回false,则表示不能。 |
**示例**
```js
canShowFloating().then((status) => {
console.log('Checks whether a specified application can show as float window.');
});
```
## settings.getUriSync<sup>8+</sup>
getUriSync(name: string): string getUriSync(name: string): string
获取数据项的URI。 获取数据项的URI。
**系统能力**:SystemCapability.Applications.settings.Core **系统能力**:SystemCapability.Applications.settings.Core
- 参数: **参数**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| name | string | 是 | 数据项的名称。数据项名称分为以下两种:<br> <ul><li>数据库中已存在的数据项,包括:<br></li> <ul><li>亮度:'settings.screen.brightness' <br> </li> <li> 时间格式:'settings.time.format' <br> </li></ul> <li>开发者自行添加的数据项。</li></ul>|
- 返回值: | 参数名 | 类型 | 必填 | 说明 |
| 类型 | 说明 | | ------ | ------ | ---- | ------------------------------------------------------------ |
| -------- | -------- | | name | string | 是 | 数据项的名称。数据项名称分为以下两种:<br>- 上述任意一个数据库中已存在的数据项。<br>- 开发者自行添加的数据项。 |
| string | 数据项的URI。 |
- 示例: **返回值**
```typescript
// 获取数据项的URI
let urivar = settings.getUriSync('settings.screen.brightness');
```
| 类型 | 说明 |
| ------ | ------------- |
| string | 数据项的URI。 |
## settings.getValueSync **示例**
```js
// 获取数据项的URI
let urivar = settings.getUriSync(settings.display.SCREEN_BRIGHTNESS_STATUS);
```
## settings.getValueSync<sup>8+</sup>
getValueSync(dataAbilityHelper: DataAbilityHelper, name: string, defValue: string): string getValueSync(dataAbilityHelper: DataAbilityHelper, name: string, defValue: string): string
获取数据项的值。 获取数据项的值。此方法相较getValue为同步方法。
**系统能力**:SystemCapability.Applications.settings.Core
**系统能力**:SystemCapability.Applications.settings.Core。 **参数**
- 参数: | 参数名 | 类型 | 必填 | 说明 |
| 参数名 | 类型 | 必填 | 说明 | | ----------------- | ------------------------------------------------- | ---- | ------------------------------------------------------------ |
| -------- | -------- | -------- | -------- | | dataAbilityHelper | [DataAbilityHelper](js-apis-dataAbilityHelper.md) | 是 | 数据管理辅助类。 |
| dataAbilityHelper | [DataAbilityHelper](js-apis-dataAbilityHelper.md) | 是 | 数据管理辅助类。 | | name | string | 是 | 数据项的名称。数据项名称分为以下两种:<br>- 上述任意一个数据库中已存在的数据项。<br>- 开发者自行添加的数据项。 |
| name | string | 是 | 数据项的名称。数据项名称分为以下两种:<br> <ul><li>数据库中已存在的数据项,包括:<br></li> <ul><li>亮度:'settings.screen.brightness' <br> </li> <li> 时间格式:'settings.time.format' <br> </li></ul> <li>开发者自行添加的数据项。</li></ul>| | defValue | string | 是 | 默认值。由开发者设置,当未从数据库中查询到该数据时,表示返回该默认值。 |
| defValue | string | 是 | 默认值。由开发者设置,当未从数据库中查询到该数据时,则返回该默认值。 |
- 返回值: **返回值**
| 类型 | 说明 |
| -------- | -------- |
| string | 返回数据项的值。 |
- 示例: | 类型 | 说明 |
```typescript | ------ | ---------------- |
import featureAbility from '@ohos.ability.featureAbility'; | string | 返回数据项的值。 |
//获取数据项亮度的值(该数据项在数据库中已存在) **示例**
let brightness = 'settings.screen.brightness';
let uri = settings.getUriSync(brightness);
let helper = featureAbility.acquireDataAbilityHelper(uri);
let value = settings.getValueSync(helper, brightness, '10');
```
```js
import featureAbility from '@ohos.ability.featureAbility';
## settings.setValueSync //获取数据项亮度的值(该数据项在数据库中已存在)
let uri = settings.getUriSync(settings.display.SCREEN_BRIGHTNESS_STATUS);
let helper = featureAbility.acquireDataAbilityHelper(uri);
let value = settings.getValueSync(helper, settings.display.SCREEN_BRIGHTNESS_STATUS, '10');
```
## settings.setValueSync<sup>8+</sup>
setValueSync(dataAbilityHelper: DataAbilityHelper, name: string, value: string): boolean setValueSync(dataAbilityHelper: DataAbilityHelper, name: string, value: string): boolean
设置数据项的值。 设置数据项的值。此方法相较setValue为同步方法。
如果数据库中已经存在该数据项,则setValueSync方法将更新该数据项的值;如果数据库中尚未存在该数据项,则setValueSync方法将向数据库中插入该数据项。 如果数据库中已经存在该数据项,则setValueSync方法将更新该数据项的值;如果数据库中尚未存在该数据项,则setValueSync方法将向数据库中插入该数据项。
**需要权限**:ohos.permission.WRITE_SYSTEM_SETTING **需要权限**:ohos.permission.MANAGE_SECUER_SETTINGS,仅系统应用可用
**系统能力**:SystemCapability.Applications.settings.Core **系统能力**:SystemCapability.Applications.settings.Core
- 参数: **参数**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| dataAbilityHelper | [DataAbilityHelper](js-apis-dataAbilityHelper.md) | 是 | 数据管理辅助类。 |
| name | string | 是 | 数据项的名称。数据项名称分为以下两种:<br> <ul><li>数据库中已存在的数据项,包括:<br></li> <ul><li>亮度:'settings.screen.brightness' <br> </li> <li> 时间格式:'settings.time.format' <br> </li></ul> <li>开发者自行添加的数据项。</li></ul>|
| value | string | 是 | 数据项的具体数值。 |
- 返回值: | 参数名 | 类型 | 必填 | 说明 |
| 类型 | 说明 | | ----------------- | ------------------------------------------------- | ---- | ------------------------------------------------------------ |
| -------- | -------- | | dataAbilityHelper | [DataAbilityHelper](js-apis-dataAbilityHelper.md) | 是 | 数据管理辅助类。 |
| boolean | 返回设置数据项的值是否成功的结果。true表示设置成功,false则表示设置失败。 | | name | string | 是 | 数据项的名称。数据项名称分为以下两种:<br>- 上述任意一个数据库中已存在的数据项。<br>- 开发者自行添加的数据项。 |
| value | string | 是 | 数据项的具体数值。取值范围随业务变动。 |
- 示例: **返回值**
```typescript
import featureAbility from '@ohos.ability.featureAbility';
//更新数据项亮度的值(该数据项在数据库中已存在,故setValueSync方法将更新该数据项的值) | 类型 | 说明 |
let brightness = 'settings.screen.brightness'; | ------- | ------------------------------------------------------------ |
let uri = settings.getUriSync(brightness); | boolean | 返回设置数据项的值是否成功的结果。true表示设置成功,false表示设置失败。 |
let helper = featureAbility.acquireDataAbilityHelper(uri);
let ret = settings.setValueSync(helper, brightness, '100'); **示例**
```
```js
import featureAbility from '@ohos.ability.featureAbility';
//更新数据项亮度的值(该数据项在数据库中已存在,故setValueSync方法将更新该数据项的值)
let uri = settings.getUriSync(settings.display.SCREEN_BRIGHTNESS_STATUS);
let helper = featureAbility.acquireDataAbilityHelper(uri);
let ret = settings.setValueSync(helper, settings.display.SCREEN_BRIGHTNESS_STATUS, '100');
```
...@@ -6,25 +6,21 @@ ...@@ -6,25 +6,21 @@
> >
> 该组件从API Version 8开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 > 该组件从API Version 8开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
## 权限列表
## 子组件 ## 子组件
## 接口 ## 接口
CheckboxGroup( option?: {group?: string} ) CheckboxGroup( options?: {group?: string} )
创建多选框群组,可以控制群组内的Checkbox全选或者不全选,相同group的Checkbox和CheckboxGroup为同一群组。 创建多选框群组,可以控制群组内的Checkbox全选或者不全选,相同group的Checkbox和CheckboxGroup为同一群组。
**参数:** **参数:**
| 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 | | 参数名 | 参数类型 | 必填 | 参数描述 |
| ----- | ------ | ---- | ---- | ----- | | ------ | -------- | ---- | ---------- |
| group | string | 否 | - | 群组名称。 | | group | string | 否 | 群组名称。 |
## 属性 ## 属性
...@@ -50,7 +46,7 @@ CheckboxGroup的选中状态或群组内的Checkbox的选中状态发生变化 ...@@ -50,7 +46,7 @@ CheckboxGroup的选中状态或群组内的Checkbox的选中状态发生变化
| 名称 | 参数类型 | 描述 | | 名称 | 参数类型 | 描述 |
| ------ | ------------------- | -------------- | | ------ | ------------------- | -------------- |
| name | Array&lt;string&gt; | checkBox名称。 | | name | Array&lt;string&gt; | checkBox名称。 |
| status | selectStatus | 选中状态。 | | status | SelectStatus | 选中状态。 |
## SelectStatus枚举说明 ## SelectStatus枚举说明
......
...@@ -6,10 +6,6 @@ ...@@ -6,10 +6,6 @@
> >
> 该组件从API Version 8开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 > 该组件从API Version 8开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
## 权限列表
## 子组件 ## 子组件
...@@ -20,21 +16,21 @@ Gauge(options:{value: number, min?: number, max?: number}) ...@@ -20,21 +16,21 @@ Gauge(options:{value: number, min?: number, max?: number})
**参数:** **参数:**
| 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 | | 参数名 | 参数类型 | 必填 | 参数描述 |
| ----- | ------ | ---- | ---- | --------- | | ------ | -------- | ---- | ---------------------------------- |
| value | number | 是 | - | 当前数据值。 | | value | number | 是 | 当前数据值。 |
| min | number | 否 | 0 | 当前数据段最小值。 | | min | number | 否 | 当前数据段最小值。<br/>默认值:0 |
| max | number | 否 | 100 | 当前数据段最大值。 | | max | number | 否 | 当前数据段最大值。<br/>默认值:100 |
## 属性 ## 属性
| 名称 | 参数类型 | 默认值 | 描述 | | 名称 | 参数类型 | 描述 |
| ----------- | ---------------------------------------- | ---- | --------------------------- | | ----------- | ---------------------------------------- | --------------------------- |
| value | number | 0 | 设置当前数据图表的值。 | | value | number | 设置当前数据图表的值。<br/>默认值:0 |
| startAngle | number | -150 | 设置起始角度位置,时钟0点为0度,顺时针方向为正角度。 | | startAngle | number | 设置起始角度位置,时钟0点为0度,顺时针方向为正角度。<br/>默认值:-150 |
| endAngle | number | 150 | 设置终止角度位置,时钟0点为0度,顺时针方向为正角度。 | | endAngle | number | 设置终止角度位置,时钟0点为0度,顺时针方向为正角度。<br/>默认值:150 |
| colors | Array&lt;ColorStop&gt; | - | 设置图表的颜色,支持分段颜色设置。 | | colors | Array&lt;ColorStop&gt; | 设置图表的颜色,支持分段颜色设置。 |
| strokeWidth | [Length](ts-types.md#length) | - | 设置环形图表的环形厚度。 | | strokeWidth | [Length](ts-types.md#length) | 设置环形图表的环形厚度。 |
## ColorStop ## ColorStop
......
...@@ -7,11 +7,6 @@ Navigation组件一般作为Page页面的根容器,通过属性设置来展示 ...@@ -7,11 +7,6 @@ Navigation组件一般作为Page页面的根容器,通过属性设置来展示
> 该组件从API Version 8开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 > 该组件从API Version 8开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
## 权限列表
## 子组件 ## 子组件
可以包含子组件。 可以包含子组件。
...@@ -26,32 +21,32 @@ Navigation() ...@@ -26,32 +21,32 @@ Navigation()
## 属性 ## 属性
| 名称 | 参数类型 | 默认值 | 描述 | | 名称 | 参数类型 | 描述 |
| -------------- | ---------------------------------------- | ------------------------ | ---------------------------------------- | | -------------- | ---------------------------------------- | ---------------------------------------- |
| title | string&nbsp;\|&nbsp;[CustomBuilder](ts-types.md#custombuilder8)<sup>8+</sup> | - | 页面标题。 | | title | string&nbsp;\|&nbsp;[CustomBuilder](ts-types.md#custombuilder8)<sup>8+</sup> | 页面标题。 |
| subtitle | string | - | 页面副标题。 | | subtitle | string | 页面副标题。 |
| menus | Array<NavigationMenuItem&gt;&nbsp;\|&nbsp;[CustomBuilder](ts-types.md#custombuilder8)<sup>8+</sup> | - | 页面右上角菜单。 | | menus | Array<NavigationMenuItem&gt;&nbsp;\|&nbsp;[CustomBuilder](ts-types.md#custombuilder8)<sup>8+</sup> | 页面右上角菜单。 |
| titleMode | NavigationTitleMode | NavigationTitleMode.Free | 页面标题栏显示模式。 | | titleMode | NavigationTitleMode | 页面标题栏显示模式。<br/>默认值:NavigationTitleMode.Free |
| toolBar | object&nbsp;\|&nbsp;[CustomBuilder](ts-types.md#custombuilder8)<sup>8+</sup> | - | 设置工具栏内容。<br/>items:&nbsp;工具栏所有项。 | | toolBar | object&nbsp;\|&nbsp;[CustomBuilder](ts-types.md#custombuilder8)<sup>8+</sup> | 设置工具栏内容。<br/>items:&nbsp;工具栏所有项。 |
| hideToolBar | boolean | false | 设置隐藏/显示工具栏:<br/>true:&nbsp;隐藏工具栏。<br/>false:&nbsp;显示工具栏。 | | hideToolBar | boolean | 设置隐藏/显示工具栏:<br/>默认值:false<br/>true:&nbsp;隐藏工具栏。<br/>false:&nbsp;显示工具栏。 |
| hideTitleBar | boolean | false | 隐藏标题栏。 | | hideTitleBar | boolean | 隐藏标题栏。<br/>默认值:false |
| hideBackButton | boolean | false | 隐藏返回键。 | | hideBackButton | boolean | 隐藏返回键。<br/>默认值:false |
## NavigationMenuItem类型说明 ## NavigationMenuItem类型说明
| 名称 | 类型 | 必填 | 默认值 | 描述 | | 名称 | 类型 | 必填 | 描述 |
| ------ | ----------------------- | ---- | ---- | --------------- | | ------ | ----------------------- | ---- | ------------------------------ |
| value | string | 是 | - | 菜单栏单个选项的显示文本。 | | value | string | 是 | 菜单栏单个选项的显示文本。 |
| icon | string | 否 | - | 菜单栏单个选项的图标资源路径。 | | icon | string | 否 | 菜单栏单个选项的图标资源路径。 |
| action | ()&nbsp;=&gt;&nbsp;void | 否 | - | 当前选项被选中的事件回调。 | | action | ()&nbsp;=&gt;&nbsp;void | 否 | 当前选项被选中的事件回调。 |
## Object类型说明 ## Object类型说明
| 名称 | 类型 | 必填 | 默认值 | 描述 | | 名称 | 类型 | 必填 | 描述 |
| ------ | ----------------------- | ---- | ---- | --------------- | | ------ | ----------------------- | ---- | ------------------------------ |
| value | string | 是 | - | 工具栏单个选项的显示文本。 | | value | string | 是 | 工具栏单个选项的显示文本。 |
| icon | string | 否 | - | 工具栏单个选项的图标资源路径。 | | icon | string | 否 | 工具栏单个选项的图标资源路径。 |
| action | ()&nbsp;=&gt;&nbsp;void | 否 | - | 当前选项被选中的事件回调。 | | action | ()&nbsp;=&gt;&nbsp;void | 否 | 当前选项被选中的事件回调。 |
## NavigationTitleMode枚举说明 ## NavigationTitleMode枚举说明
......
...@@ -7,11 +7,6 @@ ...@@ -7,11 +7,6 @@
> 该组件从API Version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 > 该组件从API Version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
## 权限列表
## 子组件 ## 子组件
...@@ -25,12 +20,12 @@ Progress(options: {value: number, total?: number, style?: ProgressStyle, type?: ...@@ -25,12 +20,12 @@ Progress(options: {value: number, total?: number, style?: ProgressStyle, type?:
**参数:** **参数:**
| 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 | | 参数名 | 参数类型 | 必填 | 参数描述 |
| -------------------------- | ------------- | ---- | -------------------- | --------------------------------------------------- | | -------------------------- | ------------- | ---- | ------------------------------------------------------------ |
| value | number | 是 | - | 指定当前进度值。 | | value | number | 是 | 指定当前进度值。 |
| total | number | 否 | 100 | 指定进度总长。 | | total | number | 否 | 指定进度总长。<br/>默认值:100 |
| type<sup>8+</sup> | ProgressType | 否 | ProgressType.Linear | 指定进度条类型。 | | type<sup>8+</sup> | ProgressType | 否 | 指定进度条类型。<br/>默认值:ProgressType.Linear |
| style<sup>deprecated</sup> | ProgressStyle | 否 | ProgressStyle.Linear | 指定进度条样式。<br/>该参数从API Version8开始废弃。 | | style<sup>deprecated</sup> | ProgressStyle | 否 | 指定进度条类型。<br/>该参数从API Version8开始废弃,建议使用type替代。<br/>默认值:ProgressStyle.Linear |
## ProgressType枚举说明 ## ProgressType枚举说明
...@@ -54,11 +49,11 @@ Progress(options: {value: number, total?: number, style?: ProgressStyle, type?: ...@@ -54,11 +49,11 @@ Progress(options: {value: number, total?: number, style?: ProgressStyle, type?:
## 属性 ## 属性
| 名称 | 参数类型 | 默认值 | 描述 | | 名称 | 参数类型 | 描述 |
| ------------------ | ------------------------------------------------------------ | ------ | ------------------------------------------------------------ | | ------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ |
| value | number | - | 设置当前进度值。 | | value | number | 设置当前进度值。 |
| color | [ResourceColor](ts-types.md#resourcecolor8) | - | 设置进度条前景色。 | | color | [ResourceColor](ts-types.md#resourcecolor8) | 设置进度条前景色。 |
| style<sup>8+</sup> | {<br/>strokeWidth?:&nbsp;[Length](ts-types.md#length),<br/>scaleCount?:&nbsp;number,<br/>scaleWidth?:&nbsp;[Length](ts-types.md#length)<br/>} | - | 定义组件的样式。<br/>strokeWidth:&nbsp;设置进度条宽度。<br/>scaleCount:&nbsp;设置环形进度条总刻度数。<br/>scaleWidth:&nbsp;设置环形进度条刻度粗细。<br/>刻度粗细大于进度条宽度时,刻度粗细为系统默认粗细。 | | style<sup>8+</sup> | {<br/>strokeWidth?:&nbsp;[Length](ts-types.md#length),<br/>scaleCount?:&nbsp;number,<br/>scaleWidth?:&nbsp;[Length](ts-types.md#length)<br/>} | 定义组件的样式。<br/>strokeWidth:&nbsp;设置进度条宽度。<br/>scaleCount:&nbsp;设置环形进度条总刻度数。<br/>scaleWidth:&nbsp;设置环形进度条刻度粗细。<br/>刻度粗细大于进度条宽度时,刻度粗细为系统默认粗细。 |
## 示例 ## 示例
......
...@@ -7,11 +7,6 @@ ...@@ -7,11 +7,6 @@
> 该组件从API Version 8开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 > 该组件从API Version 8开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
## 权限列表
## 子组件 ## 子组件
...@@ -23,23 +18,23 @@ Radio(options: {value: string, group: string}) ...@@ -23,23 +18,23 @@ Radio(options: {value: string, group: string})
**参数:** **参数:**
| 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 | | 参数名 | 参数类型 | 必填 | 参数描述 |
| ----- | ------ | ---- | ---- | ----------------------------------- | | ------ | -------- | ---- | ------------------------------------------------------------ |
| value | string | 是 | - | 当前单选框的值。 | | value | string | 是 | 当前单选框的值。 |
| group | string | 是 | - | 当前单选框的所属群组名称,相同group的Radio只能有一个被选中。 | | group | string | 是 | 当前单选框的所属群组名称,相同group的Radio只能有一个被选中。 |
## 属性 ## 属性
| 名称 | 参数类型 | 默认值 | 描述 | | 名称 | 参数类型 | 描述 |
| ------- | ------- | ----- | ----------- | | ------- | -------- | ---------------------------------------- |
| checked | boolean | false | 设置单选框的选中状态。 | | checked | boolean | 设置单选框的选中状态。<br/>默认值:false |
## 事件 ## 事件
| 名称 | 功能描述 | | 名称 | 功能描述 |
| ---------------------------------------- | ---------------------------------------- | | ------------------------------------------------ | ------------------------------------------------------------ |
| onChange(callback: (isChecked: boolean) => void) | 单选框选中状态改变时触发回调。<br> -isChecked为true时,代表选中。<br> -isChecked为false时,代表未选中。 | | onChange(callback: (isChecked: boolean) => void) | 单选框选中状态改变时触发回调。<br> - isChecked为true时,代表选中。<br> - isChecked为false时,代表未选中。 |
## 示例 ## 示例
......
...@@ -6,10 +6,6 @@ ...@@ -6,10 +6,6 @@
> >
> 该组件从API Version 8开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 > 该组件从API Version 8开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
## 权限列表
## 子组件 ## 子组件
...@@ -20,21 +16,21 @@ Search(options?: { value?: string; placeholder?: string; icon?: string; controll ...@@ -20,21 +16,21 @@ Search(options?: { value?: string; placeholder?: string; icon?: string; controll
**参数:** **参数:**
| 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 | | 参数名 | 参数类型 | 必填 | 参数描述 |
| ----------- | ---------------- | ---- | ---- | ---------------------------------------- | | ----------- | ---------------- | ---- | ------------------------------------------------------------ |
| value | string | 否 | - | 搜索文本值。 | | value | string | 否 | 搜索文本值。 |
| placeholder | string | 否 | - | 无输入时的提示文本。 | | placeholder | string | 否 | 无输入时的提示文本。 |
| icon | string | 否 | - | 搜索图标路径,默认使用系统搜索图标,支持的图标格式: svg, jpg和png。 | | icon | string | 否 | 搜索图标路径,默认使用系统搜索图标,支持的图标格式: svg, jpg和png。 |
| controller | SearchController | 否 | - | 控制器。 | | controller | SearchController | 否 | 控制器。 |
## 属性 ## 属性
| 名称 | 参数类型 | 默认值 | 描述 | | 名称 | 参数类型 | 描述 |
| ---------------- | ------------------------------------------- | ------ | ------------------------------------------ | | ---------------- | ------------------------------------------- | ------------------------------------------ |
| searchButton | string | 无 | 搜索框末尾搜索按钮文本值,默认无搜索按钮。 | | searchButton | string | 搜索框末尾搜索按钮文本值,默认无搜索按钮。 |
| placeholderColor | [ResourceColor](ts-types.md#resourcecolor8) | - | 设置placeholder颜色。 | | placeholderColor | [ResourceColor](ts-types.md#resourcecolor8) | 设置placeholder颜色。 |
| placeholderFont | [Font](ts-types.md#font) | - | 设置placeholder文本样式。 | | placeholderFont | [Font](ts-types.md#font) | 设置placeholder文本样式。 |
| textFont | [Font](ts-types.md#font) | - | 设置搜索框内文本样式。 | | textFont | [Font](ts-types.md#font) | 设置搜索框内文本样式。 |
## 事件 ## 事件
...@@ -62,9 +58,9 @@ caretPosition(value: number): void ...@@ -62,9 +58,9 @@ caretPosition(value: number): void
**参数:** **参数:**
| 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 | | 参数名 | 参数类型 | 必填 | 参数描述 |
| ----- | ------ | ---- | ---- | ----------------- | | ------ | -------- | ---- | ---------------------------------- |
| value | number | 是 | - | 从字符串开始到光标所在位置的长度。 | | value | number | 是 | 从字符串开始到光标所在位置的长度。 |
## 示例 ## 示例
......
...@@ -7,11 +7,6 @@ ...@@ -7,11 +7,6 @@
> 该组件从API Version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 > 该组件从API Version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
## 权限列表
## 子组件 ## 子组件
...@@ -19,23 +14,23 @@ ...@@ -19,23 +14,23 @@
## 接口 ## 接口
Span(content: string | Resource) Span(value: string | Resource)
**参数:** **参数:**
| 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 | | 参数名 | 参数类型 | 必填 | 参数描述 |
| ------- | ---------------------------------------- | ---- | ------ | ---------- | | ------ | ---------------------------------------------------- | ---- | ---------- |
| content | string\|[Resource](ts-types.md#resource) | 是 | - | 文本内容。 | | value | string&nbsp;\|&nbsp;[Resource](ts-types.md#resource) | 是 | 文本内容。 |
## 属性 ## 属性
通用属性方法仅支持通用文本样式,不支持触摸热区设置。 通用属性方法仅支持通用文本样式,不支持触摸热区设置。
| 名称 | 参数类型 | 默认值 | 描述 | | 名称 | 参数类型 | 描述 |
| ---------- | ---------------------------------------- | ---------------------------------------- | -------------- | | ---------- | ---------------------------------------- | -------------- |
| decoration | {<br/>type:&nbsp;[TextDecorationType](ts-appendix-enums.md#textdecorationtype枚举说明),<br/>color?:&nbsp;[ResourceColor](ts-types.md#resourcecolor8)<br/>} | {<br/>type:&nbsp;TextDecorationType.None<br/>color:Color.Black<br/>} | 设置文本装饰线样式及其颜色。 | | decoration | {<br/>type:&nbsp;[TextDecorationType](ts-appendix-enums.md#textdecorationtype枚举说明),<br/>color?:&nbsp;[ResourceColor](ts-types.md#resourcecolor8)<br/>} | 设置文本装饰线样式及其颜色。<br/>默认值:{<br/>type:&nbsp;TextDecorationType.None<br/>color:Color.Black<br/>} |
| letterSpacing | number \| string | - | 设置文本字符间距。 | | letterSpacing | number \| string | 设置文本字符间距。 |
| textCase | [TextCase](ts-appendix-enums.md#textcase枚举说明) | Normal | 设置文本大小写。 | | textCase | [TextCase](ts-appendix-enums.md#textcase枚举说明) | 设置文本大小写。<br/>默认值:Normal |
## 事件 ## 事件
...@@ -43,6 +38,7 @@ Span(content: string | Resource) ...@@ -43,6 +38,7 @@ Span(content: string | Resource)
通用事件仅支持点击事件。 通用事件仅支持点击事件。
> **说明:** > **说明:**
>
> 由于Span组件无尺寸信息,因此点击事件返回的ClickEvent对象的target属性无效。 > 由于Span组件无尺寸信息,因此点击事件返回的ClickEvent对象的target属性无效。
......
...@@ -7,11 +7,6 @@ ...@@ -7,11 +7,6 @@
> 该组件从API Version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 > 该组件从API Version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
## 权限列表
## 子组件 ## 子组件
可以包含[Span](ts-basic-components-span.md)子组件。 可以包含[Span](ts-basic-components-span.md)子组件。
...@@ -23,24 +18,24 @@ Text(content?: string | Resource) ...@@ -23,24 +18,24 @@ Text(content?: string | Resource)
**参数:** **参数:**
| 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 | | 参数名 | 参数类型 | 必填 | 参数描述 |
| ------- | ------------------------------------------ | ---- | ------ | ------------------------------------------------------------ | | ------- | ------------------------------------------ | ---- | ------------------------------------------------------------ |
| content | string \| [Resource](ts-types.md#resource) | 否 | '' | 文本内容。包含子组件Span时不生效,显示Span内容,并且此时text组件的样式不生效。 | | content | string \| [Resource](ts-types.md#resource) | 否 | 文本内容。包含子组件Span时不生效,显示Span内容,并且此时text组件的样式不生效。<br/>默认值:' ' |
## 属性 ## 属性
| 名称 | 参数类型 | 默认值 | 描述 | | 名称 | 参数类型 | 描述 |
| -------------- | ---------------------------------------- | ---------------------------------------- | ---------------------------------------- | | -------------- | ---------------------------------------- | ---------------------------------------- |
| textAlign | [TextAlign](ts-appendix-enums.md#textalign) | TextAlign.Start | 设置多行文本的文本对齐方式。 | | textAlign | [TextAlign](ts-appendix-enums.md#textalign) | 设置多行文本的文本对齐方式。<br/>默认值:TextAlign.Start |
| textOverflow | {overflow:&nbsp;[TextOverflow](ts-appendix-enums.md#textoverflow)} | {overflow:&nbsp;TextOverflow.Clip} | 设置文本超长时的显示方式。<br/>**说明:**<br/>文本截断是按字截断。例如,英文以单词为最小单位进行截断,若需要以字母为单位进行截断,可在字母间添加零宽空格:\u200B。 | | textOverflow | {overflow:&nbsp;[TextOverflow](ts-appendix-enums.md#textoverflow)} | 设置文本超长时的显示方式。<br/>默认值:{overflow:&nbsp;TextOverflow.Clip}<br/>**说明:**<br/>文本截断是按字截断。例如,英文以单词为最小单位进行截断,若需要以字母为单位进行截断,可在字母间添加零宽空格:\u200B。 |
| maxLines | number | Infinity | 设置文本的最大行数。 | | maxLines | number | 设置文本的最大行数。<br/>默认值:Infinity |
| lineHeight | string&nbsp;\|&nbsp;number&nbsp;\|&nbsp;[Resource](ts-types.md#resource) | - | 设置文本的文本行高,设置值不大于0时,不限制文本行高,自适应字体大小,Length为number类型时单位为fp。 | | lineHeight | string&nbsp;\|&nbsp;number&nbsp;\|&nbsp;[Resource](ts-types.md#resource) | 设置文本的文本行高,设置值不大于0时,不限制文本行高,自适应字体大小,Length为number类型时单位为fp。 |
| decoration | {<br/>type:&nbsp;[TextDecorationType](ts-appendix-enums.md#textdecorationtype),<br/>color?:&nbsp;[ResourceColor](ts-types.md#resourcecolor8)<br/>} | {<br/>type:&nbsp;TextDecorationType.None,<br/>color:Color.Black<br/>} | 设置文本装饰线样式及其颜色。 | | decoration | {<br/>type:&nbsp;[TextDecorationType](ts-appendix-enums.md#textdecorationtype),<br/>color?:&nbsp;[ResourceColor](ts-types.md#resourcecolor8)<br/>} | 设置文本装饰线样式及其颜色。<br/>默认值:{<br/>type:&nbsp;TextDecorationType.None,<br/>color:Color.Black<br/>} |
| baselineOffset | number \| string | - | 设置文本基线的偏移量。 | | baselineOffset | number \| string | 设置文本基线的偏移量。 |
| letterSpacing | number \| string | - | 设置文本字符间距。 | | letterSpacing | number \| string | 设置文本字符间距。 |
| minFontSize | number&nbsp;\|&nbsp;string&nbsp;\|&nbsp;[Resource](ts-types.md#resource) | - | 设置文本最小显示字号。 | | minFontSize | number&nbsp;\|&nbsp;string&nbsp;\|&nbsp;[Resource](ts-types.md#resource) | 设置文本最小显示字号。 |
| maxFontSize | number&nbsp;\|&nbsp;string&nbsp;\|&nbsp;[Resource](ts-types.md#resource) | - | 设置文本最大显示字号。 | | maxFontSize | number&nbsp;\|&nbsp;string&nbsp;\|&nbsp;[Resource](ts-types.md#resource) | 设置文本最大显示字号。 |
| textCase | [TextCase](ts-appendix-enums.md#textcase) | TextCase.Normal | 设置文本大小写。 | | textCase | [TextCase](ts-appendix-enums.md#textcase) | 设置文本大小写。<br/>默认值:TextCase.Normal |
> **说明:** > **说明:**
......
...@@ -7,11 +7,6 @@ ...@@ -7,11 +7,6 @@
> 该组件从API Version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 > 该组件从API Version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
## 权限列表
## 子组件 ## 子组件
...@@ -23,32 +18,32 @@ TextArea(value?:{placeholder?: ResourceStr, text?: ResourceStr, controller?: Tex ...@@ -23,32 +18,32 @@ TextArea(value?:{placeholder?: ResourceStr, text?: ResourceStr, controller?: Tex
**参数:** **参数:**
| 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 | | 参数名 | 参数类型 | 必填 | 参数描述 |
| ----------------------- | ---------------------------------------- | ---- | ---- | -------------- | | ----------------------- | ---------------------------------------- | ---- | -------------- |
| placeholder | [ResourceStr](ts-types.md#resourcestr8) | 否 | - | 无输入时的提示文本。 | | placeholder | [ResourceStr](ts-types.md#resourcestr8) | 否 | 无输入时的提示文本。 |
| text | [ResourceStr](ts-types.md#resourcestr8) | 否 | - | 设置输入框当前的文本内容。 | | text | [ResourceStr](ts-types.md#resourcestr8) | 否 | 设置输入框当前的文本内容。 |
| controller<sup>8+</sup> | [TextAreaController](#textareacontroller8) | 否 | - | 设置TextArea控制器。 | | controller<sup>8+</sup> | [TextAreaController](#textareacontroller8) | 否 | 设置TextArea控制器。 |
## 属性 ## 属性
除支持通用属性外,还支持以下属性: 除支持通用属性外,还支持以下属性:
| 名称 | 参数类型 | 默认值 | 描述 | | 名称 | 参数类型 | 描述 |
| ------------------------ | ------------------------------------------------------------ | ------ | ------------------------------------------------------------ | | ------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ |
| placeholderColor | [ResourceColor](ts-types.md#resourcecolor8) | - | 设置placeholder文本颜色。 | | placeholderColor | [ResourceColor](ts-types.md#resourcecolor8) | 设置placeholder文本颜色。 |
| placeholderFont | [Font](ts-types.md#font) | - | 设置placeholder文本样式:<br/>-&nbsp;size:&nbsp;设置文本尺寸,Length为number类型时,使用fp单位。<br/>-&nbsp;weight:&nbsp;设置文本的字体粗细,number类型取值[100,&nbsp;900],取值间隔为100,默认为400,取值越大,字体越粗。<br/>-&nbsp;family:&nbsp;设置文本的字体列表。使用多个字体,使用','进行分割,优先级按顺序生效,例如:'Arial,&nbsp;sans-serif'。<br/>-&nbsp;style:&nbsp;设置文本的字体样式。 | | placeholderFont | [Font](ts-types.md#font) | 设置placeholder文本样式:<br/>-&nbsp;size:&nbsp;设置文本尺寸,Length为number类型时,使用fp单位。<br/>-&nbsp;weight:&nbsp;设置文本的字体粗细,number类型取值[100,&nbsp;900],取值间隔为100,默认为400,取值越大,字体越粗。<br/>-&nbsp;family:&nbsp;设置文本的字体列表。使用多个字体,使用','进行分割,优先级按顺序生效,例如:'Arial,&nbsp;sans-serif'。<br/>-&nbsp;style:&nbsp;设置文本的字体样式。 |
| textAlign | [TextAlign](ts-appendix-enums.md#textalign) | Start | 设置文本水平对齐方式。 | | textAlign | [TextAlign](ts-appendix-enums.md#textalign) | 设置文本水平对齐方式。<br/>默认值:TextAlign.Start |
| caretColor | [ResourceColor](ts-types.md#resourcecolor8) | - | 设置输入框光标颜色。 | | caretColor | [ResourceColor](ts-types.md#resourcecolor8) | 设置输入框光标颜色。 |
| 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/>} | - | 通过正则表达式设置输入过滤器。满足表达式的输入允许显示,不满足的输入被忽略。仅支持单个字符匹配,不支持字符串匹配。例如:^(?=.\*\d)(?=.\*[a-z])(?=.\*[A-Z]).{8,10}$,不支持过滤8到10位的强密码。<br/>-&nbsp;value:设置正则表达式。<br/>-&nbsp;error:正则匹配失败时,返回被忽略的内容。 | | 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/>} | 通过正则表达式设置输入过滤器。满足表达式的输入允许显示,不满足的输入被忽略。仅支持单个字符匹配,不支持字符串匹配。例如:^(?=.\*\d)(?=.\*[a-z])(?=.\*[A-Z]).{8,10}$,不支持过滤8到10位的强密码。<br/>-&nbsp;value:设置正则表达式。<br/>-&nbsp;error:正则匹配失败时,返回被忽略的内容。 |
## 事件 ## 事件
| 名称 | 功能描述 | | 名称 | 功能描述 |
| ---------------------------------------- | ---------------------------------------- | | ------------------------------------------------------------ | ------------------------------------------------------------ |
| onChange(callback:&nbsp;(value:&nbsp;string)&nbsp;=&gt;&nbsp;void) | 输入发生变化时,触发回调。 | | onChange(callback:&nbsp;(value:&nbsp;string)&nbsp;=&gt;&nbsp;void) | 输入发生变化时,触发回调。 |
| onCopy<sup>8+</sup>(callback:(value:&nbsp;string)&nbsp;=&gt;&nbsp;void) | 长按输入框内部区域弹出剪贴板后,点击剪切板复制按钮,触发回调。<br/>value:复制的文本内容。 | | onCopy<sup>8+</sup>(callback:(value:&nbsp;string)&nbsp;=&gt;&nbsp;void) | 长按输入框内部区域弹出剪贴板后,点击剪切板复制按钮,触发回调。<br/>- value:复制的文本内容。 |
| onCut<sup>8+</sup>(callback:(value:&nbsp;string)&nbsp;=&gt;&nbsp;void) | 长按输入框内部区域弹出剪贴板后,点击剪切板剪切按钮,触发回调。<br/>value:剪切的文本内容。 | | onCut<sup>8+</sup>(callback:(value:&nbsp;string)&nbsp;=&gt;&nbsp;void) | 长按输入框内部区域弹出剪贴板后,点击剪切板剪切按钮,触发回调。<br/>- value:剪切的文本内容。 |
| onPaste<sup>8+</sup>(callback:(value:&nbsp;string)&nbsp;=&gt;&nbsp;void) | 长按输入框内部区域弹出剪贴板后,点击剪切板粘贴按钮,触发回调。<br/>value:粘贴的文本内容。 | | onPaste<sup>8+</sup>(callback:(value:&nbsp;string)&nbsp;=&gt;&nbsp;void) | 长按输入框内部区域弹出剪贴板后,点击剪切板粘贴按钮,触发回调。<br/>- value:粘贴的文本内容。 |
## TextAreaController<sup>8+</sup> ## TextAreaController<sup>8+</sup>
...@@ -69,9 +64,9 @@ caretPosition(value: number): void ...@@ -69,9 +64,9 @@ caretPosition(value: number): void
**参数:** **参数:**
| 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 | | 参数名 | 参数类型 | 必填 | 参数描述 |
| ----- | ------ | ---- | ---- | ------------------- | | ------ | -------- | ---- | -------------------------------------- |
| value | number | 是 | - | 从字符串开始到光标所在位置的字符长度。 | | value | number | 是 | 从字符串开始到光标所在位置的字符长度。 |
## 示例 ## 示例
......
...@@ -27,9 +27,9 @@ TextClock(options?: {timeZoneOffset?: number, controller?: TextClockController}) ...@@ -27,9 +27,9 @@ TextClock(options?: {timeZoneOffset?: number, controller?: TextClockController})
## 属性 ## 属性
| 名称 | 参数类型 | 默认值 | 描述 | | 名称 | 参数类型 | 默认值 | 描述 |
| ------ | ------ | -------- | ---------------------------------------- | | ------ | -------- | ------ | ------------------------------------------------------------ |
| format | string | 'hhmmss' | 设置显示时间格式,如“yyyy/mm/dd”、“yyyy-mm-dd”等。支持的时间格式化字符串:<ul><li>yyyy(年份)</li><li>mm(英文月份简写)</li><li>mmm(英文月份简写)</li><li>mmmm(英文月份全称)</li><li>dd(英文星期简写)</li><li>ddd(英文星期简写)</li><li>dddd(英文星期全称)</li><li>HH(24小时制)</li><li>hh(12小时制)</li><li>MM/mm(分钟)</li><li>SS/ss(秒)</li></ul> | | format | string | 'hms' | 设置显示时间格式。<br/>日期间隔符固定为"/",时间间隔符为":"。<br/>如yyyyMMdd,yyyy-MM-dd显示为yyyy/MM/dd,<br/>hhmmss显示为hh:mm:ss。 <br/>时间格式只用写一位即可,如"hhmmss"等同于"hms"。<br/>支持的时间格式化字符串:<br/>- YYYY/yyyy:完整年份。<br/>- YY/yy:年份后两位。<br/>- M:月份(若想使用01月则使用MM)。<br/>- d:日期(若想使用01日则使用dd)。<br/>- D:年中日(一年中的第几天)。<br/>- H:24小时制。<br/>- h:12小时制。<br/>- m:分钟。<br/>- s:秒。<br/>- SSS:毫秒。 |
## 事件 ## 事件
......
...@@ -7,11 +7,6 @@ ...@@ -7,11 +7,6 @@
> 该组件从API Version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 > 该组件从API Version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
## 权限列表
## 子组件 ## 子组件
...@@ -23,25 +18,25 @@ TextInput(value?:{placeholder?: [ResourceStr](ts-types.md#resourcestr8), text?: ...@@ -23,25 +18,25 @@ TextInput(value?:{placeholder?: [ResourceStr](ts-types.md#resourcestr8), text?:
**参数:** **参数:**
| 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 | | 参数名 | 参数类型 | 必填 | 参数描述 |
| ----------------------- | ---------------------------------------- | ---- | ---- | --------------- | | ----------------------- | ---------------------------------------- | ---- | --------------- |
| placeholder | [ResourceStr](ts-types.md#resourcestr8) | 否 | - | 无输入时的提示文本。 | | placeholder | [ResourceStr](ts-types.md#resourcestr8) | 否 | 无输入时的提示文本。 |
| text | [ResourceStr](ts-types.md#resourcestr8) | 否 | - | 设置输入框当前的文本内容。 | | text | [ResourceStr](ts-types.md#resourcestr8) | 否 | 设置输入框当前的文本内容。 |
| controller<sup>8+</sup> | [TextInputController](#textinputcontroller8) | 否 | - | 设置TextInput控制器。 | | controller<sup>8+</sup> | [TextInputController](#textinputcontroller8) | 否 | 设置TextInput控制器。 |
## 属性 ## 属性
除支持通用属性外,还支持以下属性: 除支持通用属性外,还支持以下属性:
| 名称 | 参数类型 | 默认值 | 描述 | | 名称 | 参数类型 | 描述 |
| ----------------------------- | ------------------------------------------------------------ | ----------------- | ------------------------------------------------------------ | | ----------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| type | InputType | InputType.Normal | 设置输入框类型。 | | type | InputType | 设置输入框类型。<br/>默认值:InputType.Normal |
| placeholderColor | [ResourceColor](ts-types.md#resourcecolor8) | - | 设置placeholder颜色。 | | placeholderColor | [ResourceColor](ts-types.md#resourcecolor8) | 设置placeholder颜色。 |
| placeholderFont | [Font](ts-types.md#font) | - | 设置placeholder文本样式:<br/>-&nbsp;size:&nbsp;设置文本尺寸,Length为number类型时,使用fp单位。<br/>-&nbsp;weight:&nbsp;设置文本的字体粗细,number类型取值[100,&nbsp;900],取值间隔为100,默认为400,取值越大,字体越粗。<br/>-&nbsp;family:&nbsp;设置文本的字体列表。使用多个字体,使用','进行分割,优先级按顺序生效。例如:'Arial,&nbsp;sans-serif'。<br/>-&nbsp;style:&nbsp;设置文本的字体样式。 | | placeholderFont | [Font](ts-types.md#font) | 设置placeholder文本样式:<br/>-&nbsp;size:&nbsp;设置文本尺寸,Length为number类型时,使用fp单位。<br/>-&nbsp;weight:&nbsp;设置文本的字体粗细,number类型取值[100,&nbsp;900],取值间隔为100,默认为400,取值越大,字体越粗。<br/>-&nbsp;family:&nbsp;设置文本的字体列表。使用多个字体,使用','进行分割,优先级按顺序生效。例如:'Arial,&nbsp;sans-serif'。<br/>-&nbsp;style:&nbsp;设置文本的字体样式。 |
| enterKeyType | EnterKeyType | EnterKeyType.Done | 设置输入法回车键类型。 | | enterKeyType | EnterKeyType | 设置输入法回车键类型。<br/>默认值:EnterKeyType.Done |
| caretColor | [ResourceColor](ts-types.md#resourcecolor8) | - | 设置输入框光标颜色。 | | caretColor | [ResourceColor](ts-types.md#resourcecolor8) | 设置输入框光标颜色。 |
| maxLength | number | - | 设置文本的最大输入字符数。 | | maxLength | number | 设置文本的最大输入字符数。 |
| 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/>} | - | 正则表达式,满足表达式的输入允许显示,不满足正则表达式的输入被忽略。仅支持单个字符匹配,不支持字符串匹配。例如:^(?=.\*\d)(?=.\*[a-z])(?=.\*[A-Z]).{8,10}$,8到10位的强密码不支持过滤。<br/>-&nbsp;value:设置正则表达式。<br/>-&nbsp;error:正则匹配失败时,返回被忽略的内容。 | | 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/>} | 正则表达式,满足表达式的输入允许显示,不满足正则表达式的输入被忽略。仅支持单个字符匹配,不支持字符串匹配。例如:^(?=.\*\d)(?=.\*[a-z])(?=.\*[A-Z]).{8,10}$,8到10位的强密码不支持过滤。<br/>-&nbsp;value:设置正则表达式。<br/>-&nbsp;error:正则匹配失败时,返回被忽略的内容。 |
## EnterKeyType枚举说明 ## EnterKeyType枚举说明
...@@ -90,9 +85,9 @@ caretPosition(value:&nbsp;number): void ...@@ -90,9 +85,9 @@ caretPosition(value:&nbsp;number): void
**参数:** **参数:**
| 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 | | 参数名 | 参数类型 | 必填 | 参数描述 |
| ----- | ------ | ---- | ---- | ---------------------------------------- | | ------ | -------- | ---- | ------------------------------------------------------------ |
| value | number | 是 | - | 设置输入光标的位置。<br/>value:从字符串开始到光标所在位置的字符长度。 | | value | number | 是 | 设置输入光标的位置。<br/>value:从字符串开始到光标所在位置的字符长度。 |
## 示例 ## 示例
......
...@@ -7,11 +7,6 @@ ...@@ -7,11 +7,6 @@
> 该组件从API Version 8开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 > 该组件从API Version 8开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
## 权限列表
## 子组件 ## 子组件
...@@ -25,24 +20,24 @@ TextPicker(options?: {range: string[] | [Resource](ts-types.md#resource), select ...@@ -25,24 +20,24 @@ TextPicker(options?: {range: string[] | [Resource](ts-types.md#resource), select
**参数:** **参数:**
| 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 | | 参数名 | 参数类型 | 必填 | 参数描述 |
| -------- | -------- | ---- | ----- | --------------- | | -------- | -------- | ---- | --------------- |
| range | string[]&nbsp;\|&nbsp;[Resource](ts-types.md#resource) | 是 | - | 选择器的数据选择范围。 | | range | string[]&nbsp;\|&nbsp;[Resource](ts-types.md#resource) | 是 | 选择器的数据选择范围。 |
| selected | number | 否 | 0 | 选中项在数组中的index值。 | | selected | number | 否 | 选中项在数组中的index值。<br/>默认值:0 |
| value | string | 否 | 第一个元素值 | 选中项的值,优先级低于selected。 | | value | string | 否 | 选中项的值,优先级低于selected。<br/>默认值:第一个元素值 |
## 属性 ## 属性
| 名称 | 参数类型 | 默认值 | 描述 | | 名称 | 参数类型 | 描述 |
| ----------------------- | ---------------- | ------ | -------------------------- | | ----------------------- | ---------------- | -------------------------- |
| defaultPickerItemHeight | number \| string | - | 默认Picker内容项元素高度。 | | defaultPickerItemHeight | number \| string | 默认Picker内容项元素高度。 |
## 事件 ## 事件
| 名称 | 描述 | | 名称 | 描述 |
| ------------------------------------------------------------ | ------------------------------------------------------------ | | ------------------------------------------------------------ | ------------------------------------------------------------ |
| onChange(callback:&nbsp;(value:&nbsp;string,&nbsp;index:&nbsp;number)&nbsp;=&gt;&nbsp;void) | 滑动选中TextPicker文本内容后,触发该回调。<br/>-&nbsp;value:&nbsp;当前选中项的文本。<br/>-&nbsp;index:&nbsp;当前选中项的下标。 | | onChange(callback:&nbsp;(value:&nbsp;string,&nbsp;index:&nbsp;number)&nbsp;=&gt;&nbsp;void) | 滑动选中TextPicker文本内容后,触发该回调。<br/>-&nbsp;value:&nbsp;当前选中项的文本。<br/>-&nbsp;index:&nbsp;当前选中项的索引值。 |
## 示例 ## 示例
......
# LongPressGesture # LongPressGesture
> **说明:** > **说明:**
>
> 从API Version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 > 从API Version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
## 权限列表
## 接口 ## 接口
LongPressGesture(options?: { fingers?: number, repeat?: boolean, duration?: number }) LongPressGesture(value?: { fingers?: number, repeat?: boolean, duration?: number })
**参数:** **参数:**
| 参数名称 | 参数类型 | 必填 | 默认值 | 参数描述 | | 参数名称 | 参数类型 | 必填 | 参数描述 |
| -------- | ------- | ---- | ----- | -------------------------------- | | -------- | -------- | ---- | ------------------------------------------------------------ |
| fingers | number | 否 | 1 | 触发长按的最少手指数,最小为1指,&nbsp;最大取值为10指。 | | fingers | number | 否 | 触发长按的最少手指数,最小为1指,&nbsp;最大取值为10指。<br/>默认值:1 |
| repeat | boolean | 否 | false | 是否连续触发事件回调。 | | repeat | boolean | 否 | 是否连续触发事件回调。<br/>默认值:false |
| duration | number | 否 | 500 | 最小触发长按的时间,单位为毫秒(ms)。 | | duration | number | 否 | 最小触发长按的时间,单位为毫秒(ms)。<br/>默认值:500 |
## 事件 ## 事件
| 名称 | 功能描述 | | 名称 | 功能描述 |
| ---------------------------------------- | ------------------------------ | | ------------------------------------------------------------ | --------------------------------------------------- |
| onAction((event?:&nbsp;GestureEvent)&nbsp;=&gt;&nbsp;void) | LongPress手势识别成功回调。 | | onAction(event:&nbsp;(event?:&nbsp;[GestureEvent](ts-gesture-settings.md))&nbsp;=&gt;&nbsp;void) | LongPress手势识别成功回调。 |
| onActionEnd((event?:&nbsp;GestureEvent)&nbsp;=&gt;&nbsp;void) | LongPress手势识别成功,手指抬起后触发回调。 | | onActionEnd(event:&nbsp;(event?:&nbsp;[GestureEvent](ts-gesture-settings.md))&nbsp;=&gt;&nbsp;void) | LongPress手势识别成功,手指抬起后触发回调。 |
| onActionCancel(event:&nbsp;()&nbsp;=&gt;&nbsp;void) | LongPress手势识别成功,接收到触摸取消事件触发回调。 | | onActionCancel(event:&nbsp;()&nbsp;=&gt;&nbsp;void) | LongPress手势识别成功,接收到触摸取消事件触发回调。 |
## GestureEvent对象中与LongPress手势相关的属性
| 属性名称 | 属性类型 | 描述 |
| ------ | ------- | ------------ |
| repeat | boolean | 事件是否为重复触发事件。 |
## 示例 ## 示例
......
# PanGesture # PanGesture
用于触发拖动手势事件,滑动的最小距离为5vp时拖动手势识别成功。
> **说明:** > **说明:**
>
> 从API Version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 > 从API Version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
## 权限列表
## 接口 ## 接口
PanGesture(options?: { fingers?: number, direction?: PanDirection, distance?: number } | [PanGestureOptions](#pangestureoptions)) PanGesture(value?: { fingers?: number, direction?: PanDirection, distance?: number } | [PanGestureOptions](#pangestureoptions))
**参数:** **参数:**
| 参数名称 | 参数类型 | 必填 | 默认值 | 参数描述 | | 参数名称 | 参数类型 | 必填 | 参数描述 |
| --------- | ------------ | ---- | ------ | ------------------------------------------------------------ | | --------- | ------------ | ---- | ------------------------------------------------------------ |
| fingers | number | 否 | 1 | 触发滑动的最少手指数,最小为1指,&nbsp;最大取值为10指。 | | fingers | number | 否 | 触发拖动的最少手指数,最小为1指,&nbsp;最大取值为10指。<br/>默认值:1 |
| direction | PanDirection | 否 | All | 设置滑动方向,此枚举值支持逻辑与(&amp;)和逻辑或(\|)运算。 | | direction | PanDirection | 否 | 触发拖动的手势方向,此枚举值支持逻辑与(&amp;)和逻辑或(\|)运算。<br/>默认值:PanDirection.All |
| distance | number | 否 | 5.0 | 最小滑动识别距离,单位为vp。<br/>**说明:**<br/>> tab滑动与该拖动手势事件同时存在时,可将distance值设为1,使拖动更灵敏,避免造成事件错乱。 | | distance | number | 否 | 最小拖动识别距离,单位为vp。<br/>默认值:5.0<br/>**说明:**<br/>> tab滑动与该拖动手势事件同时存在时,可将distance值设为1,使拖动更灵敏,避免造成事件错乱。 |
## PanDirection枚举说明 ## PanDirection枚举说明
| 名称 | 描述 | | 名称 | 描述 |
| ---------- | ---------- | | -------- | -------- |
| All | 所有方向可滑动。 | | All | 所有方向。 |
| Horizontal | 水平方向可滑动。 | | Horizontal | 水平方向。 |
| Vertical | 竖直方向可滑动。 | | Vertical | 竖直方向。 |
| Left | 向左滑动。 | | Left | 向左拖动。 |
| Right | 向右滑动。 | | Right | 向右拖动。 |
| Up | 向上滑动。 | | Up | 向上拖动。 |
| Down | 向下滑动。 | | Down | 向下拖动。 |
| None | 任何方向都不可滑动。 | | None | 任何方向都不可触发拖动手势事件。 |
## PanGestureOptions ## PanGestureOptions
...@@ -43,31 +40,26 @@ PanGestureOptions(options?: { fingers?: number, direction?: PanDirection, distan ...@@ -43,31 +40,26 @@ PanGestureOptions(options?: { fingers?: number, direction?: PanDirection, distan
**参数:** **参数:**
同PanGesture参数说明。 同PanGesture参数说明。
**接口:** **接口:**
| 名称 | 功能描述 | | 名称 | 功能描述 |
| -------------------------------------- | -------------- | | -------- | -------- |
| setDirection(value:&nbsp;PanDirection) | 设置direction属性。 | | setDirection(value:&nbsp;PanDirection) | 设置direction属性。 |
| setDistance(value:&nbsp;number) | 设置distance属性。 | | setDistance(value:&nbsp;number) | 设置distance属性。 |
| setFingers(value:&nbsp;number) | 设置fingers属性。 | | setFingers(value:&nbsp;number) | 设置fingers属性。 |
## 事件
| 名称 | 功能描述 | ## 事件
| ---------------------------------------- | ------------------------ |
| onActionStart(callback:&nbsp;(event?:&nbsp;GestureEvent)&nbsp;=&gt;&nbsp;void) | Pan手势识别成功回调。 |
| onActionUpdate(callback:&nbsp;(event?:&nbsp;GestureEvent)&nbsp;=&gt;&nbsp;void) | Pan手势移动过程中回调。 |
| onActionEnd(callback:&nbsp;(event?:&nbsp;GestureEvent)&nbsp;=&gt;&nbsp;void) | Pan手势识别成功,手指抬起后触发回调。 |
| onActionCancel(callback:&nbsp;()&nbsp;=&gt;&nbsp;void) | Pan手势识别成功,接收到触摸取消事件触发回调。 |
## GestureEvent对象中与Pan手势相关的属性 | 名称 | 功能描述 |
| -------- | -------- |
| onActionStart(event:&nbsp;(event?:&nbsp;[GestureEvent](ts-gesture-settings.md))&nbsp;=&gt;&nbsp;void) | Pan手势识别成功回调。 |
| onActionUpdate(event:&nbsp;(event?:&nbsp;[GestureEvent](ts-gesture-settings.md))&nbsp;=&gt;&nbsp;void) | Pan手势移动过程中回调。 |
| onActionEnd(event:&nbsp;(event?:&nbsp;[GestureEvent](ts-gesture-settings.md))&nbsp;=&gt;&nbsp;void) | Pan手势识别成功,手指抬起后触发回调。 |
| onActionCancel(event:&nbsp;()&nbsp;=&gt;&nbsp;void) | Pan手势识别成功,接收到触摸取消事件触发回调。 |
| 属性名称 | 属性类型 | 描述 |
| ------- | ------ | -------------- |
| offsetX | number | 手势事件偏移量,单位为vp。 |
| offsetY | number | 手势事件偏移量,单位为vp。 |
## 示例 ## 示例
......
# PinchGesture # PinchGesture
> **说明:** > **说明:**
>
> 从API Version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 > 从API Version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
## 权限列表
## 接口 ## 接口
PinchGesture(options?: { fingers?: number, distance?: number }) PinchGesture(value?: { fingers?: number, distance?: number })
**参数:** **参数:**
| 参数名称 | 参数类型 | 必填 | 默认值 | 参数描述 | | 参数名称 | 参数类型 | 必填 | 参数描述 |
| -------- | ------ | ---- | ---- | ----------------------------- | | -------- | -------- | ---- | ------------------------------------------------------------ |
| fingers | number | 否 | 2 | 触发捏合的最少手指数,&nbsp;最小为2指,最大为5指。 | | fingers | number | 否 | 触发捏合的最少手指数,&nbsp;最小为2指,最大为5指。<br/>默认值:2 |
| distance | number | 否 | 3.0 | 最小识别距离,单位为vp。 | | distance | number | 否 | 最小识别距离,单位为vp。<br/>默认值:3.0 |
## 事件 ## 事件
| 名称 | 功能描述 | | 名称 | 功能描述 |
| ---------------------------------------- | -------------------------- | | ------------------------------------------------------------ | ----------------------------------------------- |
| onActionStart((event?:&nbsp;GestureEvent)&nbsp;=&gt;&nbsp;void) | Pinch手势识别成功回调。 | | onActionStart(event:(event?:&nbsp;[GestureEvent](ts-gesture-settings.md))&nbsp;=&gt;&nbsp;void) | Pinch手势识别成功回调。 |
| onActionUpdate((event?:&nbsp;GestureEvent)&nbsp;=&gt;&nbsp;void) | Pinch手势移动过程中回调。 | | onActionUpdate(event:(event?:&nbsp;[GestureEvent](ts-gesture-settings.md))&nbsp;=&gt;&nbsp;void) | Pinch手势移动过程中回调。 |
| onActionEnd((event?:&nbsp;GestureEvent)&nbsp;=&gt;&nbsp;void) | Pinch手势识别成功,手指抬起后触发回调。 | | onActionEnd(event:(event?:&nbsp;[GestureEvent](ts-gesture-settings.md))&nbsp;=&gt;&nbsp;void) | Pinch手势识别成功,手指抬起后触发回调。 |
| onActionCancel(event:&nbsp;()&nbsp;=&gt;&nbsp;void) | Pinch手势识别成功,接收到触摸取消事件触发回调。 | | onActionCancel(event:&nbsp;()&nbsp;=&gt;&nbsp;void) | Pinch手势识别成功,接收到触摸取消事件触发回调。 |
## GestureEvent对象中与Pinch手势相关的属性
| 属性名称 | 属性类型 | 描述 |
| ------------ | ------ | -------------------------- |
| scale | number | 缩放比例,用于PinchGesture手势触发场景。 |
| pinchCenterX | number | 捏合手势中心点X轴坐标,单位为px。 |
| pinchCenterY | number | 捏合手势中心点Y轴坐标,单位为px。 |
## 示例 ## 示例
......
# RotationGesture # RotationGesture
> **说明:** > **说明:**
>
> 从API Version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 > 从API Version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
## 权限列表
## 接口 ## 接口
RotationGesture(options?: { fingers?: number, angle?: number }) RotationGesture(value?: { fingers?: number, angle?: number })
**参数:** **参数:**
| 参数名称 | 参数类型 | 必填 | 默认值 | 参数描述 | | 参数名称 | 参数类型 | 必填 | 参数描述 |
| ------- | ------ | ---- | ---- | ----------------------------- | | -------- | -------- | ---- | ------------------------------------------------------------ |
| fingers | number | 否 | 2 | 触发旋转的最少手指数,&nbsp;最小为2指,最大为5指。 | | fingers | number | 否 | 触发旋转的最少手指数,&nbsp;最小为2指,最大为5指。<br/>默认值:2 |
| angle | number | 否 | 1.0 | 触发旋转手势的最小改变度数,单位为度数。 | | angle | number | 否 | 触发旋转手势的最小改变度数,单位为度数。<br/>默认值:1.0 |
## 事件 ## 事件
| 名称 | 功能描述 | | 名称 | 功能描述 |
| ---------------------------------------- | ----------------------------- | | ------------------------------------------------------------ | -------------------------------------------------- |
| onActionStart((event?:&nbsp;GestureEvent)&nbsp;=&gt;&nbsp;void) | Rotation手势识别成功回调。 | | onActionStart(event: (event?:&nbsp;[GestureEvent](ts-gesture-settings.md))&nbsp;=&gt;&nbsp;void) | Rotation手势识别成功回调。 |
| onActionUpdate((event?:&nbsp;GestureEvent)&nbsp;=&gt;&nbsp;void) | Rotation手势移动过程中回调。 | | onActionUpdate(event: (event?:&nbsp;[GestureEvent](ts-gesture-settings.md))&nbsp;=&gt;&nbsp;void) | Rotation手势移动过程中回调。 |
| onActionEnd((event?:&nbsp;GestureEvent)&nbsp;=&gt;&nbsp;void) | Rotation手势识别成功,手指抬起后触发回调。 | | onActionEnd(event: (event?:&nbsp;[GestureEvent](ts-gesture-settings.md))&nbsp;=&gt;&nbsp;void) | Rotation手势识别成功,手指抬起后触发回调。 |
| onActionCancel(event:&nbsp;()&nbsp;=&gt;&nbsp;void) | Rotation手势识别成功,接收到触摸取消事件触发回调。 | | onActionCancel(event:&nbsp;()&nbsp;=&gt;&nbsp;void) | Rotation手势识别成功,接收到触摸取消事件触发回调。 |
## GestureEvent对象中与Rotation手势相关的属性
| 属性名称 | 属性类型 | 描述 |
| ----- | ------ | ----- |
| angle | number | 旋转角度。 |
## 示例 ## 示例
......
# SwipeGesture # SwipeGesture
> **说明:** > **说明:**
>
> 从API Version 8开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 > 从API Version 8开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
## 权限列表
## 接口 ## 接口
SwipeGesture(value?: { fingers?: number; direction?: SwipeDirection; speed?: number }) SwipeGesture(value?: { fingers?: number; direction?: SwipeDirection; speed?: number })
**参数:** **参数:**
| 参数名称 | 参数类型 | 必填 | 默认值 | 参数描述 | | 参数名称 | 参数类型 | 必填 | 默认值 | 参数描述 |
| --------- | -------------- | ---- | ------------------ | ----------------------------- | | -------- | -------- | -------- | -------- | -------- |
| fingers | number | 否 | 1 | 触发滑动的最少手指数,默认为1,最小为1指,最大为10指。 | | fingers | number | 否 | 1 | 触发滑动的最少手指数,默认为1,最小为1指,最大为10指。 |
| direction | SwipeDirection | 否 | SwipeDirection.All | 滑动方向。 | | direction | SwipeDirection | 否 | SwipeDirection.All | 触发滑动手势的滑动方向。 |
| speed | number | 否 | 100 | 识别滑动的最小速度(100VP/秒)。 | | speed | number | 否 | 100 | 识别滑动的最小速度(默认为100vp/秒)。 |
## SwipeDirection枚举说明 ## SwipeDirection枚举说明
| 名称 | 描述 | | 名称 | 描述 |
| ---------- | ----- | | -------- | -------- |
| All | 所有方向。 | | All | 所有方向。 |
| Horizontal | 水平方向。 | | Horizontal | 水平方向。 |
| Vertical | 竖直方向。 | | Vertical | 竖直方向。 |
| None | 任何方向均不可触发。 |
## 事件
| 名称 | 功能描述 | ## 事件
| ---------------------------------------- | ----------- |
| onAction(callback:(event?:&nbsp;GestureEvent)&nbsp;=&gt;&nbsp;void) | 滑动手势识别成功回调。 |
## GestureEvent对象中与Swipe手势相关的属性 | 名称 | 功能描述 |
| -------- | -------- |
| onAction(event:(event?:&nbsp;[GestureEvent](ts-gesture-settings.md))&nbsp;=&gt;&nbsp;void) | 滑动手势识别成功回调。 |
| 参数名 | 类型 | 说明 |
| ----- | ------ | ---------------------------------------- |
| angle | number | 滑动手势的角度,即两根手指间的线段与水平方向的夹角变化的度数。<br/>>&nbsp;&nbsp;**说明:**<br/>>&nbsp;角度计算方式:滑动手势被识别到后,连接两根手指之间的线被识别为起始线条,随着手指的滑动,手指之间的线条会发生旋转,根据起始线条两端点和当前线条两端点的坐标,使用反正切函数分别计算其相对于水平方向的夹角,最后arctan2(cy2-cy1,cx2-cx1)-arctan2(y2-y1,x2-x1)为旋转的角度。以起始线条为坐标系,顺时针旋转为0到180度,逆时针旋转为-180到0度。 |
| speed | number | 滑动手势的速度,是所有手指滑动的平均速度,单位为VP/秒。 |
![zh-cn_image_0000001231374559](figures/zh-cn_image_0000001231374661.png) ![zh-cn_image_0000001231374559](figures/zh-cn_image_0000001231374661.png)
## 示例 ## 示例
...@@ -64,7 +54,7 @@ struct SwipeGestureExample { ...@@ -64,7 +54,7 @@ struct SwipeGestureExample {
.width(260).height(260) .width(260).height(260)
.rotate({x: 0, y: 0, z: 1, angle: this.rotateAngle}) .rotate({x: 0, y: 0, z: 1, angle: this.rotateAngle})
.gesture( .gesture(
SwipeGesture({fingers: 1, direction:SwipeDirection.Vertical}) SwipeGesture({fingers: 1, direction: SwipeDirection.Vertical})
.onAction((event: GestureEvent) => { .onAction((event: GestureEvent) => {
this.speed = event.speed this.speed = event.speed
this.rotateAngle = event.angle this.rotateAngle = event.angle
......
# TapGesture # TapGesture
> **说明:** > **说明:**
>
> 从API Version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 > 从API Version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
## 权限列表
## 接口 ## 接口
TapGesture(options?: { count?: number, fingers?: number }) TapGesture(value?: { count?: number, fingers?: number })
**参数:** **参数:**
| 参数名称 | 参数类型 | 必填 | 默认值 | 参数描述 | | 参数名称 | 参数类型 | 必填 | 参数描述 |
| ------- | ------ | ---- | ---- | ---------------------------------------- | | -------- | -------- | ---- | ------------------------------------------------------------ |
| count | number | 否 | 1 | 识别的连续点击次数。如果设置小于1,会被转化为默认值。<br/>>&nbsp;&nbsp;**说明:**<br/>>&nbsp;如配置多击,上一次抬起和下一次按下的超时时间为300毫秒(ms)。 | | count | number | 否 | 识别的连续点击次数。如果设置小于1,会被转化为默认值。<br/>默认值:1<br/>>&nbsp;&nbsp;**说明:**<br/>>&nbsp;如配置多击,上一次抬起和下一次按下的超时时间为300毫秒(ms)。 |
| fingers | number | 否 | 1 | 触发点击的最少手指数,最小为1指,&nbsp;最大为10指。<br/>>&nbsp;&nbsp;**说明:**<br/>>&nbsp;1.&nbsp;当配置多指时,第一根手指按下后300毫秒(ms)内未有足够的手指数按下,手势识别失败。<br/>>&nbsp;<br/>>&nbsp;2.&nbsp;实际点击手指数超过配置值,手势识别失败。 | | fingers | number | 否 | 触发点击的最少手指数,最小为1指,&nbsp;最大为10指。<br/>默认值:1<br/>>&nbsp;&nbsp;**说明:**<br/>>&nbsp;1.&nbsp;当配置多指时,第一根手指按下后300毫秒(ms)内未有足够的手指数按下,手势识别失败。<br/>>&nbsp;2.&nbsp;实际点击手指数超过配置值,手势识别失败。 |
## 事件 ## 事件
| 名称 | 功能描述 | | 名称 | 功能描述 |
| ---------------------------------------- | ------------ | | ------------------------------------------------------------ | --------------------- |
| onAction((event?:&nbsp;[GestureEvent](ts-gesture-settings.md))&nbsp;=&gt;&nbsp;void) | Tap手势识别成功回调。 | | onAction(event: (event?:&nbsp;[GestureEvent](ts-gesture-settings.md))&nbsp;=&gt;&nbsp;void) | Tap手势识别成功回调。 |
## 示例 ## 示例
......
# CanvasRenderingContext2D对象 # CanvasRenderingContext2D对象
> **说明:** > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
> > 从API Version 8开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
> 从API Version 8开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
使用RenderingContext在Canvas组件上进行绘制,绘制对象可以是矩形、文本、图片等。 使用RenderingContext在Canvas组件上进行绘制,绘制对象可以是矩形、文本、图片等。
...@@ -12,51 +11,50 @@ ...@@ -12,51 +11,50 @@
CanvasRenderingContext2D(setting: RenderingContextSetting) CanvasRenderingContext2D(setting: RenderingContextSetting)
**参数:** **参数:**
| 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 | | 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 |
| ------- | ---------------------------------------- | ---- | ---- | ---------------------------------------- | | ------- | ---------------------------------------- | ---- | ---- | ---------------------------------------- |
| setting | [RenderingContextSettings](#renderingcontextsettings) | 是 | - | 见[RenderingContextSettings](#renderingcontextsettings)。 | | setting | [RenderingContextSettings](#renderingcontextsettings) | 是 | - | 见[RenderingContextSettings](#renderingcontextsettings)。 |
### RenderingContextSettings ### RenderingContextSettings
RenderingContextSettings(antialias?: bool) RenderingContextSettings(antialias?: boolean)
用来配置CanvasRenderingContext2D对象的参数,包括是否开启抗锯齿。 用来配置CanvasRenderingContext2D对象的参数,包括是否开启抗锯齿。
**参数:** **参数:**
| 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 |
| --------- | ---- | ---- | ----- | ---------------- | | 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 |
| antialias | bool | 否 | false | 表明canvas是否开启抗锯齿。 | | --------- | ------- | ---- | ----- | ---------------- |
| antialias | boolean | 否 | false | 表明canvas是否开启抗锯齿。 |
## 属性 ## 属性
| 名称 | 类型 | 默认值 | 描述 | | 名称 | 类型 | 描述 |
| ---------------------------------------- | ---------------------------------------- | ---------------------------------------- | ---------------------------------------- | | ---------------------------------------- | ---------------------------------------- | ---------------------------------------- |
| [fillStyle](#fillstyle) | &lt;color&gt;&nbsp;\|&nbsp;[CanvasGradient](ts-components-canvas-canvasgradient.md)&nbsp;\|&nbsp;[CanvasPattern](#canvaspattern) | - | 指定绘制的填充色。<br/>-&nbsp;类型为&lt;color&gt;时,表示设置填充区域的颜色。<br/>-&nbsp;类型为CanvasGradient时,表示渐变对象,使用[createLinearGradient](#createlineargradient)方法创建。<br/>-&nbsp;类型为CanvasPattern时,使用[createPattern](#createpattern)方法创建。 | | [fillStyle](#fillstyle) | string&nbsp;\|&nbsp;[CanvasGradient](ts-components-canvas-canvasgradient.md)&nbsp;\|&nbsp;[CanvasPattern](#canvaspattern) | 指定绘制的填充色。<br/>-&nbsp;类型为string时,表示设置填充区域的颜色。<br/>-&nbsp;类型为CanvasGradient时,表示渐变对象,使用[createLinearGradient](#createlineargradient)方法创建。<br/>-&nbsp;类型为CanvasPattern时,使用[createPattern](#createpattern)方法创建。 |
| [lineWidth](#linewidth) | number | - | 设置绘制线条的宽度。 | | [lineWidth](#linewidth) | number | 设置绘制线条的宽度。 |
| [strokeStyle](#strokestyle) | &lt;color&gt;&nbsp;\|&nbsp;[CanvasGradient](ts-components-canvas-canvasgradient.md)&nbsp;\|&nbsp;[CanvasPattern](#canvaspattern) | - | 设置描边的颜色。<br/>-&nbsp;类型为&lt;color&gt;时,表示设置描边使用的颜色。<br/>-&nbsp;类型为CanvasGradient时,表示渐变对象,使用[createLinearGradient](#createlineargradient)方法创建。<br/>-&nbsp;类型为CanvasPattern时,使用[createPattern](#createpattern)方法创建。 | | [strokeStyle](#strokestyle) | string&nbsp;\|&nbsp;[CanvasGradient](ts-components-canvas-canvasgradient.md)&nbsp;\|&nbsp;[CanvasPattern](#canvaspattern) | 设置描边的颜色。<br/>-&nbsp;类型为string时,表示设置描边使用的颜色。<br/>-&nbsp;类型为CanvasGradient时,表示渐变对象,使用[createLinearGradient](#createlineargradient)方法创建。<br/>-&nbsp;类型为CanvasPattern时,使用[createPattern](#createpattern)方法创建。 |
| [lineCap](#linecap) | string | 'butt' | 指定线端点的样式,可选值为:<br/>-&nbsp;'butt':线端点以方形结束。<br/>-&nbsp;'round':线端点以圆形结束。<br/>-&nbsp;'square':线端点以方形结束,该样式下会增加一个长度和线段厚度相同,宽度是线段厚度一半的矩形。 | | [lineCap](#linecap) | CanvasLineCap | 指定线端点的样式,可选值为:<br/>-&nbsp;'butt':线端点以方形结束。<br/>-&nbsp;'round':线端点以圆形结束。<br/>-&nbsp;'square':线端点以方形结束,该样式下会增加一个长度和线段厚度相同,宽度是线段厚度一半的矩形。<br/>默认值:'butt'。 |
| [lineJoin](#linejoin) | string | 'miter' | 指定线段间相交的交点样式,可选值为:<br/>-&nbsp;'round':在线段相连处绘制一个扇形,扇形的圆角半径是线段的宽度。<br/>-&nbsp;'bevel':在线段相连处使用三角形为底填充,&nbsp;每个部分矩形拐角独立。<br/>-&nbsp;'miter':在相连部分的外边缘处进行延伸,使其相交于一点,形成一个菱形区域,该属性可以通过设置miterLimit属性展现效果。 | | [lineJoin](#linejoin) | CanvasLineJoin | 指定线段间相交的交点样式,可选值为:<br/>-&nbsp;'round':在线段相连处绘制一个扇形,扇形的圆角半径是线段的宽度。<br/>-&nbsp;'bevel':在线段相连处使用三角形为底填充,&nbsp;每个部分矩形拐角独立。<br/>-&nbsp;'miter':在相连部分的外边缘处进行延伸,使其相交于一点,形成一个菱形区域,该属性可以通过设置miterLimit属性展现效果。<br/>默认值:'miter'。 |
| [miterLimit](#miterlimit) | number | 10 | 设置斜接面限制值,该值指定了线条相交处内角和外角的距离。 | | [miterLimit](#miterlimit) | number | 设置斜接面限制值,该值指定了线条相交处内角和外角的距离。 <br/>默认值:10。 |
| [font](#font) | string | 'normal&nbsp;normal&nbsp;14px&nbsp;sans-serif' | 设置文本绘制中的字体样式。<br/>语法:ctx.font='font-size&nbsp;font-family'<br/>-&nbsp;font-size(可选),指定字号和行高,单位只支持px。<br/>-&nbsp;font-family(可选),指定字体系列。<br/>语法:ctx.font='font-style&nbsp;font-weight&nbsp;font-size&nbsp;font-family'<br/>-&nbsp;font-style(可选),用于指定字体样式,支持如下几种样式:'normal',talic。<br/>-&nbsp;font-weight(可选),用于指定字体的粗细,支持如下几种类型:'normal',&nbsp;'bold',&nbsp;'bolder',&nbsp;'lighter',&nbsp;100,&nbsp;200,&nbsp;300,&nbsp;400,&nbsp;500,&nbsp;600,&nbsp;700,&nbsp;800,&nbsp;900。<br/>-&nbsp;font-size(可选),指定字号和行高,单位只支持px。<br/>-&nbsp;font-family(可选),指定字体系列,支持如下几种类型:'sans-serif',&nbsp;'serif',&nbsp;'monospace'。 | | [font](#font) | string | 设置文本绘制中的字体样式。<br/>语法:ctx.font='font-size&nbsp;font-family'<br/>-&nbsp;font-size(可选),指定字号和行高,单位只支持px。<br/>-&nbsp;font-family(可选),指定字体系列。<br/>语法:ctx.font='font-style&nbsp;font-weight&nbsp;font-size&nbsp;font-family'<br/>-&nbsp;font-style(可选),用于指定字体样式,支持如下几种样式:'normal','italic'。<br/>-&nbsp;font-weight(可选),用于指定字体的粗细,支持如下几种类型:'normal',&nbsp;'bold',&nbsp;'bolder',&nbsp;'lighter',&nbsp;100,&nbsp;200,&nbsp;300,&nbsp;400,&nbsp;500,&nbsp;600,&nbsp;700,&nbsp;800,&nbsp;900。<br/>-&nbsp;font-size(可选),指定字号和行高,单位只支持px。<br/>-&nbsp;font-family(可选),指定字体系列,支持如下几种类型:'sans-serif',&nbsp;'serif',&nbsp;'monospace'。<br/>默认值:'normal normal 14px sans-serif'。 |
| [textAlign](#textalign) | string | 'left' | 设置文本绘制中的文本对齐方式,可选值为:<br/>-&nbsp;'left':文本左对齐。<br/>-&nbsp;'right':文本右对齐。<br/>-&nbsp;'center':文本居中对齐。<br/>-&nbsp;'start':文本对齐界线开始的地方。<br/>-&nbsp;'end':文本对齐界线结束的地方。<br/>>&nbsp;&nbsp;**说明:**<br/>>&nbsp;ltr布局模式下'start'和'left'一致,rtl布局模式下'start'和'right'一致·。 | | [textAlign](#textalign) | CanvasTextAlign | 设置文本绘制中的文本对齐方式,可选值为:<br/>-&nbsp;'left':文本左对齐。<br/>-&nbsp;'right':文本右对齐。<br/>-&nbsp;'center':文本居中对齐。<br/>-&nbsp;'start':文本对齐界线开始的地方。<br/>-&nbsp;'end':文本对齐界线结束的地方。<br/>>&nbsp;![icon-note.gif](public_sys-resources/icon-note.gif)&nbsp;**说明:**<br/>>&nbsp;ltr布局模式下'start'和'left'一致,rtl布局模式下'start'和'right'一致·。<br/>默认值:'left'。 |
| [textBaseline](#textbaseline) | string | 'alphabetic' | 设置文本绘制中的水平对齐方式,可选值为:<br/>-&nbsp;'alphabetic':文本基线是标准的字母基线。<br/>-&nbsp;'top':文本基线在文本块的顶部。<br/>-&nbsp;'hanging':文本基线是悬挂基线。<br/>-&nbsp;'middle':文本基线在文本块的中间。<br/>-&nbsp;'ideographic':文字基线是表意字基线;如果字符本身超出了alphabetic基线,那么ideograhpic基线位置在字符本身的底部。<br/>-&nbsp;'bottom':文本基线在文本块的底部。&nbsp;与ideographic基线的区别在于ideographic基线不需要考虑下行字母。 | | [textBaseline](#textbaseline) | CanvasTextBaseline | 设置文本绘制中的水平对齐方式,可选值为:<br/>-&nbsp;'alphabetic':文本基线是标准的字母基线。<br/>-&nbsp;'top':文本基线在文本块的顶部。<br/>-&nbsp;'hanging':文本基线是悬挂基线。<br/>-&nbsp;'middle':文本基线在文本块的中间。<br/>-&nbsp;'ideographic':文字基线是表意字基线;如果字符本身超出了alphabetic基线,那么ideograhpic基线位置在字符本身的底部。<br/>-&nbsp;'bottom':文本基线在文本块的底部。&nbsp;与ideographic基线的区别在于ideographic基线不需要考虑下行字母。<br/>默认值:'alphabetic'。 |
| [globalAlpha](#globalalpha) | number | - | 设置透明度,0.0为完全透明,1.0为完全不透明。 | | [globalAlpha](#globalalpha) | number | 设置透明度,0.0为完全透明,1.0为完全不透明。 |
| [lineDashOffset](#linedashoffset) | number | 0.0 | 设置画布的虚线偏移量,精度为float。 | | [lineDashOffset](#linedashoffset) | number | 设置画布的虚线偏移量,精度为float。 <br/>默认值:0.0。 |
| [globalCompositeOperation](#globalcompositeoperation) | string | 'source-over' | 设置合成操作的方式。类型字段可选值有'source-over','source-atop','source-in','source-out','destination-over','destination-atop','destination-in','destination-out','lighter','copy','xor'。 | | [globalCompositeOperation](#globalcompositeoperation) | string | 设置合成操作的方式。类型字段可选值有'source-over','source-atop','source-in','source-out','destination-over','destination-atop','destination-in','destination-out','lighter','copy','xor'。<br/>默认值:'source-over'。 |
| [shadowBlur](#shadowblur) | number | 0.0 | 设置绘制阴影时的模糊级别,值越大越模糊,精度为float。 | | [shadowBlur](#shadowblur) | number | 设置绘制阴影时的模糊级别,值越大越模糊,精度为float。 <br/>默认值:0.0。 |
| [shadowColor](#shadowcolor) | &lt;color&gt; | - | 设置绘制阴影时的阴影颜色。 | | [shadowColor](#shadowcolor) | string | 设置绘制阴影时的阴影颜色。 |
| [shadowOffsetX](#shadowoffsetx) | number | - | 设置绘制阴影时和原有对象的水平偏移值。 | | [shadowOffsetX](#shadowoffsetx) | number | 设置绘制阴影时和原有对象的水平偏移值。 |
| [shadowOffsetY](#shadowoffsety) | number | - | 设置绘制阴影时和原有对象的垂直偏移值。 | | [shadowOffsetY](#shadowoffsety) | number | 设置绘制阴影时和原有对象的垂直偏移值。 |
| [imageSmoothingEnabled](#imagesmoothingenabled) | boolean | true | 用于设置绘制图片时是否进行图像平滑度调整,true为启用,false为不启用。 | | [imageSmoothingEnabled](#imagesmoothingenabled) | boolean | 用于设置绘制图片时是否进行图像平滑度调整,true为启用,false为不启用。 <br/>默认值:true。 |
| imageSmoothingQuality | string | 'low' | 用于设置图像平滑度,支持如下三种类型:'low',&nbsp;'medium',&nbsp;'high'。 |
> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
> **说明:** >fillStyle、shadowColor与 strokeStyle 中string类型格式为 'rgb(255, 255, 255)','rgba(255, 255, 255, 1.0)','\#FFFFFF'。
>
> &lt;color&gt;类型格式为 'rgb(255, 255, 255)','rgba(255, 255, 255, 1.0)','\#FFFFFF'。
### fillStyle ### fillStyle
...@@ -427,6 +425,7 @@ struct LineDashOffset { ...@@ -427,6 +425,7 @@ struct LineDashOffset {
.onReady(() =>{ .onReady(() =>{
this.context.arc(100, 75, 50, 0, 6.28) this.context.arc(100, 75, 50, 0, 6.28)
this.context.setLineDash([10,20]) this.context.setLineDash([10,20])
this.context.lineDashOffset = 10.0;
this.context.stroke(); this.context.stroke();
}) })
} }
...@@ -597,6 +596,7 @@ struct ShadowOffsetX { ...@@ -597,6 +596,7 @@ struct ShadowOffsetX {
struct ShadowOffsetY { struct ShadowOffsetY {
private settings: RenderingContextSettings = new RenderingContextSettings(true) private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context) Canvas(this.context)
...@@ -660,16 +660,19 @@ fillRect(x: number, y: number, w: number, h: number): void ...@@ -660,16 +660,19 @@ fillRect(x: number, y: number, w: number, h: number): void
填充一个矩形。 填充一个矩形。
**参数:** **参数:**
| 参数 | 类型 | 必填 | 默认值 | 说明 |
| ------ | ------ | ---- | ---- | ------------- |
| x | number | 是 | 0 | 指定矩形左上角点的x坐标。 |
| y | number | 是 | 0 | 指定矩形左上角点的y坐标。 |
| width | number | 是 | 0 | 指定矩形的宽度。 |
| height | number | 是 | 0 | 指定矩形的高度。 |
**示例:** | 参数 | 类型 | 必填 | 默认值 | 说明 |
``` | ------ | ------ | ---- | ---- | ------------- |
| x | number | 是 | 0 | 指定矩形左上角点的x坐标。 |
| y | number | 是 | 0 | 指定矩形左上角点的y坐标。 |
| width | number | 是 | 0 | 指定矩形的宽度。 |
| height | number | 是 | 0 | 指定矩形的高度。 |
**示例:**
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct FillRect { struct FillRect {
...@@ -701,21 +704,25 @@ strokeRect(x: number, y: number, w: number, h: number): void ...@@ -701,21 +704,25 @@ strokeRect(x: number, y: number, w: number, h: number): void
绘制具有边框的矩形,矩形内部不填充。 绘制具有边框的矩形,矩形内部不填充。
**参数:** **参数:**
| 参数 | 类型 | 必填 | 默认值 | 说明 |
| ------ | ------ | ---- | ---- | ------------ |
| x | number | 是 | 0 | 指定矩形的左上角x坐标。 |
| y | number | 是 | 0 | 指定矩形的左上角y坐标。 |
| width | number | 是 | 0 | 指定矩形的宽度。 |
| height | number | 是 | 0 | 指定矩形的高度。 |
**示例:** | 参数 | 类型 | 必填 | 默认值 | 说明 |
``` | ------ | ------ | ---- | ---- | ------------ |
| x | number | 是 | 0 | 指定矩形的左上角x坐标。 |
| y | number | 是 | 0 | 指定矩形的左上角y坐标。 |
| w | number | 是 | 0 | 指定矩形的宽度。 |
| h | number | 是 | 0 | 指定矩形的高度。 |
**示例:**
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct StrokeRect { struct StrokeRect {
private settings: RenderingContextSettings = new RenderingContextSettings(true) private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context) Canvas(this.context)
...@@ -741,21 +748,25 @@ clearRect(x: number, y: number, w: number, h: number): void ...@@ -741,21 +748,25 @@ clearRect(x: number, y: number, w: number, h: number): void
删除指定区域内的绘制内容。 删除指定区域内的绘制内容。
**参数:** **参数:**
| 参数 | 类型 | 必填 | 默认值 | 描述 |
| ------ | ------ | ---- | ---- | ------------- |
| x | number | 是 | 0 | 指定矩形上的左上角x坐标。 |
| y | number | 是 | 0 | 指定矩形上的左上角y坐标。 |
| width | number | 是 | 0 | 指定矩形的宽度。 |
| height | number | 是 | 0 | 指定矩形的高度。 |
**示例:** | 参数 | 类型 | 必填 | 默认值 | 描述 |
``` | ------ | ------ | ---- | ---- | ------------- |
| x | number | 是 | 0 | 指定矩形上的左上角x坐标。 |
| y | number | 是 | 0 | 指定矩形上的左上角y坐标。 |
| w | number | 是 | 0 | 指定矩形的宽度。 |
| h | number | 是 | 0 | 指定矩形的高度。 |
**示例:**
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct ClearRect { struct ClearRect {
private settings: RenderingContextSettings = new RenderingContextSettings(true) private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context) Canvas(this.context)
...@@ -779,24 +790,29 @@ clearRect(x: number, y: number, w: number, h: number): void ...@@ -779,24 +790,29 @@ clearRect(x: number, y: number, w: number, h: number): void
### fillText ### fillText
fillText(text: string, x: number, y: number): void fillText(text: string, x: number, y: number, maxWidth?: number): void
绘制填充类文本。 绘制填充类文本。
**参数:** **参数:**
| 参数 | 类型 | 必填 | 默认值 | 说明 |
| ---- | ------ | ---- | ---- | --------------- |
| text | string | 是 | “” | 需要绘制的文本内容。 |
| x | number | 是 | 0 | 需要绘制的文本的左下角x坐标。 |
| y | number | 是 | 0 | 需要绘制的文本的左下角y坐标。 |
**示例:** | 参数 | 类型 | 必填 | 默认值 | 说明 |
``` | ---- | ------ | ---- | ---- | --------------- |
| text | string | 是 | “” | 需要绘制的文本内容。 |
| x | number | 是 | 0 | 需要绘制的文本的左下角x坐标。 |
| y | number | 是 | 0 | 需要绘制的文本的左下角y坐标。 |
| maxWidth | number | 否 | - | 指定文本允许的最大宽度。 |
**示例:**
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct FillText { struct FillText {
private settings: RenderingContextSettings = new RenderingContextSettings(true) private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context) Canvas(this.context)
...@@ -819,24 +835,29 @@ fillText(text: string, x: number, y: number): void ...@@ -819,24 +835,29 @@ fillText(text: string, x: number, y: number): void
### strokeText ### strokeText
strokeText(text: string, x: number, y: number): void strokeText(text: string, x: number, y: number, maxWidth?:number): void
绘制描边类文本。 绘制描边类文本。
**参数:** **参数:**
| 参数 | 类型 | 必填 | 默认值 | 描述 |
| ---- | ------ | ---- | ---- | --------------- |
| text | string | 是 | “” | 需要绘制的文本内容。 |
| x | number | 是 | 0 | 需要绘制的文本的左下角x坐标。 |
| y | number | 是 | 0 | 需要绘制的文本的左下角y坐标。 |
**示例:** | 参数 | 类型 | 必填 | 默认值 | 描述 |
``` | ---- | ------ | ---- | ---- | --------------- |
| text | string | 是 | “” | 需要绘制的文本内容。 |
| x | number | 是 | 0 | 需要绘制的文本的左下角x坐标。 |
| y | number | 是 | 0 | 需要绘制的文本的左下角y坐标。 |
| maxWidth | number | 否 | - | 需要绘制的文本的最大宽度 。|
**示例:**
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct StrokeText { struct StrokeText {
private settings: RenderingContextSettings = new RenderingContextSettings(true) private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context) Canvas(this.context)
...@@ -863,28 +884,49 @@ measureText(text: string): TextMetrics ...@@ -863,28 +884,49 @@ measureText(text: string): TextMetrics
该方法返回一个文本测算的对象,通过该对象可以获取指定文本的宽度值。 该方法返回一个文本测算的对象,通过该对象可以获取指定文本的宽度值。
**参数:** **参数:**
| 参数 | 类型 | 必填 | 默认值 | 说明 |
| ---- | ------ | ---- | ---- | ---------- | | 参数 | 类型 | 必填 | 默认值 | 说明 |
| text | string | 是 | "" | 需要进行测量的文本。 | | ---- | ------ | ---- | ---- | ---------- |
| text | string | 是 | "" | 需要进行测量的文本。 |
**返回值:**
- 返回值
| 类型 | 说明 | | 类型 | 说明 |
| ----------- | ------- | | ----------- | ------- |
| TextMetrics | 文本的尺寸信息 | | TextMetrics | 文本的尺寸信息 |
- TextMetrics类型描述 **TextMetrics类型描述:**
| 属性 | 类型 | 描述 |
| ----- | ------ | ------- | | 属性 | 类型 | 描述 |
| width | number | 字符串的宽度。 | | ----- | ------ | ------- |
| width | number | 字符串的宽度。 |
| height | number | 字符串的高度。 |
| actualBoundingBoxAscent | number | 从CanvasRenderingContext2D.textBaseline 属性标明的水平线到渲染文本的矩形边界顶部的距离,当前值为0。 |
| actualBoundingBoxDescent | number | 从CanvasRenderingContext2D.textBaseline 属性标明的水平线到渲染文本的矩形边界底部的距离,当前值为0。 |
| actualBoundingBoxLeft | number | 平行于基线,从CanvasRenderingContext2D.textAlign 属性确定的对齐点到文本矩形边界左侧的距离,当前值为0。 |
| actualBoundingBoxRight | number | 平行于基线,从CanvasRenderingContext2D.textAlign 属性确定的对齐点到文本矩形边界右侧的距离,当前值为0。|
| alphabeticBaseline | number | 从CanvasRenderingContext2D.textBaseline 属性标明的水平线到线框的 alphabetic 基线的距离,当前值为0。|
| emHeightAscent | number | 从CanvasRenderingContext2D.textBaseline 属性标明的水平线到线框中 em 方块顶部的距离,当前值为0。|
| emHeightDescent | number | 从CanvasRenderingContext2D.textBaseline 属性标明的水平线到线框中 em 方块底部的距离,当前值为0。|
| fontBoundingBoxAscent | number | 从CanvasRenderingContext2D.textBaseline 属性标明的水平线到渲染文本的所有字体的矩形最高边界顶部的距离,当前值为0。|
| fontBoundingBoxDescent | number | 从CanvasRenderingContext2D.textBaseline 属性标明的水平线到渲染文本的所有字体的矩形边界最底部的距离,当前值为0。|
| hangingBaseline | number | 从CanvasRenderingContext2D.textBaseline 属性标明的水平线到线框的 hanging 基线的距离,当前值为0。|
| ideographicBaseline | number | 从CanvasRenderingContext2D.textBaseline 属性标明的水平线到线框的 ideographic 基线的距离,当前值为0。|
**示例:**
```
**示例:**
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct MeasureText { struct MeasureText {
private settings: RenderingContextSettings = new RenderingContextSettings(true) private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context) Canvas(this.context)
...@@ -912,19 +954,22 @@ stroke(path?: Path2D): void ...@@ -912,19 +954,22 @@ stroke(path?: Path2D): void
进行边框绘制操作。 进行边框绘制操作。
**参数:** **参数:**
| 参数 | 类型 | 必填 | 默认值 | 描述 |
| ---- | ---------------------------------------- | ---- | ---- | ------------ |
| path | [Path2D](ts-components-canvas-path2d.md) | 否 | null | 需要绘制的Path2D。 |
**示例:** | 参数 | 类型 | 必填 | 默认值 | 描述 |
``` | ---- | ---------------------------------------- | ---- | ---- | ------------ |
| path | [Path2D](ts-components-canvas-path2d.md) | 否 | null | 需要绘制的Path2D。 |
**示例:**
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct Stroke { struct Stroke {
private settings: RenderingContextSettings = new RenderingContextSettings(true) private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context) Canvas(this.context)
...@@ -953,14 +998,16 @@ beginPath(): void ...@@ -953,14 +998,16 @@ beginPath(): void
创建一个新的绘制路径。 创建一个新的绘制路径。
**示例:** **示例:**
```
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct BeginPath { struct BeginPath {
private settings: RenderingContextSettings = new RenderingContextSettings(true) private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context) Canvas(this.context)
...@@ -991,20 +1038,23 @@ moveTo(x: number, y: number): void ...@@ -991,20 +1038,23 @@ moveTo(x: number, y: number): void
路径从当前点移动到指定点。 路径从当前点移动到指定点。
**参数:** **参数:**
| 参数 | 类型 | 必填 | 默认值 | 说明 |
| ---- | ------ | ---- | ---- | --------- |
| x | number | 是 | 0 | 指定位置的x坐标。 |
| y | number | 是 | 0 | 指定位置的y坐标。 |
**示例:** | 参数 | 类型 | 必填 | 默认值 | 说明 |
``` | ---- | ------ | ---- | ---- | --------- |
| x | number | 是 | 0 | 指定位置的x坐标。 |
| y | number | 是 | 0 | 指定位置的y坐标。 |
**示例:**
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct MoveTo { struct MoveTo {
private settings: RenderingContextSettings = new RenderingContextSettings(true) private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context) Canvas(this.context)
...@@ -1033,20 +1083,23 @@ lineTo(x: number, y: number): void ...@@ -1033,20 +1083,23 @@ lineTo(x: number, y: number): void
从当前点到指定点进行路径连接。 从当前点到指定点进行路径连接。
**参数:** **参数:**
| 参数 | 类型 | 必填 | 默认值 | 描述 |
| ---- | ------ | ---- | ---- | --------- |
| x | number | 是 | 0 | 指定位置的x坐标。 |
| y | number | 是 | 0 | 指定位置的y坐标。 |
**示例:** | 参数 | 类型 | 必填 | 默认值 | 描述 |
``` | ---- | ------ | ---- | ---- | --------- |
| x | number | 是 | 0 | 指定位置的x坐标。 |
| y | number | 是 | 0 | 指定位置的y坐标。 |
**示例:**
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct LineTo { struct LineTo {
private settings: RenderingContextSettings = new RenderingContextSettings(true) private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context) Canvas(this.context)
...@@ -1075,14 +1128,16 @@ closePath(): void ...@@ -1075,14 +1128,16 @@ closePath(): void
结束当前路径形成一个封闭路径。 结束当前路径形成一个封闭路径。
**示例:** **示例:**
```
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct ClosePath { struct ClosePath {
private settings: RenderingContextSettings = new RenderingContextSettings(true) private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context) Canvas(this.context)
...@@ -1109,25 +1164,34 @@ closePath(): void ...@@ -1109,25 +1164,34 @@ closePath(): void
### createPattern ### createPattern
createPattern(image: ImageBitmap, repetition: string): void createPattern(image: ImageBitmap, repetition: string | null): CanvasPattern | null
通过指定图像和重复方式创建图片填充的模板。 通过指定图像和重复方式创建图片填充的模板。
**参数:** **参数:**
| 参数 | 类型 | 必填 | 默认值 | 描述 |
| ---------- | ---------------------------------------- | ---- | ---- | ---------------------------------------- |
| image | [ImageBitmap](ts-components-canvas-imagebitmap.md) | 是 | null | 图源对象,具体参考ImageBitmap对象。 |
| repetition | string | 是 | “” | 设置图像重复的方式,取值为:'repeat'、'repeat-x'、&nbsp;'repeat-y'、'no-repeat'。 |
**示例:** | 参数 | 类型 | 必填 | 默认值 | 描述 |
``` | ---------- | ---------------------------------------- | ---- | ---- | ---------------------------------------- |
| image | [ImageBitmap](ts-components-canvas-imagebitmap.md) | 是 | null | 图源对象,具体参考ImageBitmap对象。 |
| repetition | string | 是 | “” | 设置图像重复的方式,取值为:'repeat'、'repeat-x'、&nbsp;'repeat-y'、'no-repeat'。 |
**返回值:**
| 类型 | 说明 |
| ---------- | ---------------------------------------- |
| [CanvasPattern](#canvaspattern) | 通过指定图像和重复方式创建图片填充的模板对象。 |
**示例:**
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct CreatePattern { struct CreatePattern {
private settings: RenderingContextSettings = new RenderingContextSettings(true) private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private img:ImageBitmap = new ImageBitmap("common/images/icon.jpg") private img:ImageBitmap = new ImageBitmap("common/images/icon.jpg")
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context) Canvas(this.context)
...@@ -1155,24 +1219,27 @@ bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number, ...@@ -1155,24 +1219,27 @@ bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number,
创建三次贝赛尔曲线的路径。 创建三次贝赛尔曲线的路径。
**参数:** **参数:**
| 参数 | 类型 | 必填 | 默认值 | 描述 |
| ---- | ------ | ---- | ---- | -------------- |
| cp1x | number | 是 | 0 | 第一个贝塞尔参数的x坐标值。 |
| cp1y | number | 是 | 0 | 第一个贝塞尔参数的y坐标值。 |
| cp2x | number | 是 | 0 | 第二个贝塞尔参数的x坐标值。 |
| cp2y | number | 是 | 0 | 第二个贝塞尔参数的y坐标值。 |
| x | number | 是 | 0 | 路径结束时的x坐标值。 |
| y | number | 是 | 0 | 路径结束时的y坐标值。 |
**示例:** | 参数 | 类型 | 必填 | 默认值 | 描述 |
``` | ---- | ------ | ---- | ---- | -------------- |
| cp1x | number | 是 | 0 | 第一个贝塞尔参数的x坐标值。 |
| cp1y | number | 是 | 0 | 第一个贝塞尔参数的y坐标值。 |
| cp2x | number | 是 | 0 | 第二个贝塞尔参数的x坐标值。 |
| cp2y | number | 是 | 0 | 第二个贝塞尔参数的y坐标值。 |
| x | number | 是 | 0 | 路径结束时的x坐标值。 |
| y | number | 是 | 0 | 路径结束时的y坐标值。 |
**示例:**
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct BezierCurveTo { struct BezierCurveTo {
private settings: RenderingContextSettings = new RenderingContextSettings(true) private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context) Canvas(this.context)
...@@ -1201,21 +1268,25 @@ quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void ...@@ -1201,21 +1268,25 @@ quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void
创建二次贝赛尔曲线的路径。 创建二次贝赛尔曲线的路径。
**参数:** **参数:**
| 参数 | 类型 | 必填 | 默认值 | 描述 |
| ---- | ------ | ---- | ---- | ----------- |
| cpx | number | 是 | 0 | 贝塞尔参数的x坐标值。 |
| cpy | number | 是 | 0 | 贝塞尔参数的y坐标值。 |
| x | number | 是 | 0 | 路径结束时的x坐标值。 |
| y | number | 是 | 0 | 路径结束时的y坐标值。 |
**示例:** | 参数 | 类型 | 必填 | 默认值 | 描述 |
``` | ---- | ------ | ---- | ---- | ----------- |
| cpx | number | 是 | 0 | 贝塞尔参数的x坐标值。 |
| cpy | number | 是 | 0 | 贝塞尔参数的y坐标值。 |
| x | number | 是 | 0 | 路径结束时的x坐标值。 |
| y | number | 是 | 0 | 路径结束时的y坐标值。 |
**示例:**
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct QuadraticCurveTo { struct QuadraticCurveTo {
private settings: RenderingContextSettings = new RenderingContextSettings(true); private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context) Canvas(this.context)
...@@ -1240,28 +1311,31 @@ quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void ...@@ -1240,28 +1311,31 @@ quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void
### arc ### arc
arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, anticlockwise?: boolean): void arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, counterclockwise?: boolean): void
绘制弧线路径。 绘制弧线路径。
**参数:** **参数:**
| 参数 | 类型 | 必填 | 默认值 | 描述 |
| ------------- | ------- | ---- | ----- | ---------- |
| x | number | 是 | 0 | 弧线圆心的x坐标值。 |
| y | number | 是 | 0 | 弧线圆心的y坐标值。 |
| radius | number | 是 | 0 | 弧线的圆半径。 |
| startAngle | number | 是 | 0 | 弧线的起始弧度。 |
| endAngle | number | 是 | 0 | 弧线的终止弧度。 |
| anticlockwise | boolean | 否 | false | 是否逆时针绘制圆弧。 |
**示例:** | 参数 | 类型 | 必填 | 默认值 | 描述 |
``` | ------------- | ------- | ---- | ----- | ---------- |
| x | number | 是 | 0 | 弧线圆心的x坐标值。 |
| y | number | 是 | 0 | 弧线圆心的y坐标值。 |
| radius | number | 是 | 0 | 弧线的圆半径。 |
| startAngle | number | 是 | 0 | 弧线的起始弧度。 |
| endAngle | number | 是 | 0 | 弧线的终止弧度。 |
| counterclockwise | boolean | 否 | false | 是否逆时针绘制圆弧。 |
**示例:**
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct Arc { struct Arc {
private settings: RenderingContextSettings = new RenderingContextSettings(true) private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context) Canvas(this.context)
...@@ -1289,23 +1363,26 @@ arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void ...@@ -1289,23 +1363,26 @@ arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void
依据圆弧经过的点和圆弧半径创建圆弧路径。 依据圆弧经过的点和圆弧半径创建圆弧路径。
**参数:** **参数:**
| 参数 | 类型 | 必填 | 默认值 | 描述 |
| ------ | ------ | ---- | ---- | --------------- |
| x1 | number | 是 | 0 | 圆弧经过的第一个点的x坐标值。 |
| y1 | number | 是 | 0 | 圆弧经过的第一个点的y坐标值。 |
| x2 | number | 是 | 0 | 圆弧经过的第二个点的x坐标值。 |
| y2 | number | 是 | 0 | 圆弧经过的第二个点的y坐标值。 |
| radius | number | 是 | 0 | 圆弧的圆半径值。 |
**示例:** | 参数 | 类型 | 必填 | 默认值 | 描述 |
``` | ------ | ------ | ---- | ---- | --------------- |
| x1 | number | 是 | 0 | 圆弧经过的第一个点的x坐标值。 |
| y1 | number | 是 | 0 | 圆弧经过的第一个点的y坐标值。 |
| x2 | number | 是 | 0 | 圆弧经过的第二个点的x坐标值。 |
| y2 | number | 是 | 0 | 圆弧经过的第二个点的y坐标值。 |
| radius | number | 是 | 0 | 圆弧的圆半径值。 |
**示例:**
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct ArcTo { struct ArcTo {
private settings: RenderingContextSettings = new RenderingContextSettings(true) private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context) Canvas(this.context)
...@@ -1329,31 +1406,33 @@ arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void ...@@ -1329,31 +1406,33 @@ arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void
### ellipse ### ellipse
ellipse(x: number, y: number, radiusX: number, radiusY: number, rotation: number, startAngle: number, endAngle: number, anticlockwise?: boolean): void ellipse(x: number, y: number, radiusX: number, radiusY: number, rotation: number, startAngle: number, endAngle: number, counterclockwise?: boolean): void
在规定的矩形区域绘制一个椭圆。 在规定的矩形区域绘制一个椭圆。
**参数:** **参数:**
| 参数 | 类型 | 必填 | 默认值 | 说明 |
| ------------- | ------- | ---- | ----- | ----------------- |
| x | number | 是 | 0 | 椭圆圆心的x轴坐标。 |
| y | number | 是 | 0 | 椭圆圆心的y轴坐标。 |
| radiusX | number | 是 | 0 | 椭圆x轴的半径长度。 |
| radiusY | number | 是 | 0 | 椭圆y轴的半径长度。 |
| rotation | number | 是 | 0 | 椭圆的旋转角度,单位为弧度。 |
| startAngle | number | 是 | 0 | 椭圆绘制的起始点角度,以弧度表示。 |
| endAngle | number | 是 | 0 | 椭圆绘制的结束点角度,以弧度表示。 |
| anticlockwise | boolean | 否 | false | 是否以逆时针方向绘制椭圆。 |
**示例:** | 参数 | 类型 | 必填 | 默认值 | 说明 |
| ------------- | ------- | ---- | ----- | ----------------- |
| x | number | 是 | 0 | 椭圆圆心的x轴坐标。 |
| y | number | 是 | 0 | 椭圆圆心的y轴坐标。 |
| radiusX | number | 是 | 0 | 椭圆x轴的半径长度。 |
| radiusY | number | 是 | 0 | 椭圆y轴的半径长度。 |
| rotation | number | 是 | 0 | 椭圆的旋转角度,单位为弧度。 |
| startAngle | number | 是 | 0 | 椭圆绘制的起始点角度,以弧度表示。 |
| endAngle | number | 是 | 0 | 椭圆绘制的结束点角度,以弧度表示。 |
| counterclockwise | boolean | 否 | false | 是否以逆时针方向绘制椭圆。 |
``` **示例:**
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct CanvasExample { struct CanvasExample {
private settings: RenderingContextSettings = new RenderingContextSettings(true) private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context) Canvas(this.context)
...@@ -1377,26 +1456,29 @@ ellipse(x: number, y: number, radiusX: number, radiusY: number, rotation: number ...@@ -1377,26 +1456,29 @@ ellipse(x: number, y: number, radiusX: number, radiusY: number, rotation: number
### rect ### rect
rect(x: number, y: number, width: number, height: number): void rect(x: number, y: number, w: number, h: number): void
创建矩形路径。 创建矩形路径。
**参数:** **参数:**
| 参数 | 类型 | 必填 | 默认值 | 描述 |
| ------ | ------ | ---- | ---- | ------------- |
| x | number | 是 | 0 | 指定矩形的左上角x坐标值。 |
| y | number | 是 | 0 | 指定矩形的左上角y坐标值。 |
| width | number | 是 | 0 | 指定矩形的宽度。 |
| height | number | 是 | 0 | 指定矩形的高度。 |
**示例:** | 参数 | 类型 | 必填 | 默认值 | 描述 |
``` | ------ | ------ | ---- | ---- | ------------- |
| x | number | 是 | 0 | 指定矩形的左上角x坐标值。 |
| y | number | 是 | 0 | 指定矩形的左上角y坐标值。 |
| w | number | 是 | 0 | 指定矩形的宽度。 |
| h | number | 是 | 0 | 指定矩形的高度。 |
**示例:**
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct CanvasExample { struct CanvasExample {
private settings: RenderingContextSettings = new RenderingContextSettings(true) private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context) Canvas(this.context)
...@@ -1419,12 +1501,21 @@ rect(x: number, y: number, width: number, height: number): void ...@@ -1419,12 +1501,21 @@ rect(x: number, y: number, width: number, height: number): void
### fill ### fill
fill(): void fill(fillRule?: CanvasFillRule): void
对封闭路径进行填充。 对封闭路径进行填充。
**示例:** **参数:**
```
| 参数 | 类型 | 必填 | 默认值 | 描述 |
| ------ | ------ | ---- | ---- | ------------- |
| fillRule | CanvasFillRule | 否 | "nonzero" | 指定要填充对象的规则。<br/>可选参数为:"nonzero", "evenodd"。|
**示例:**
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct Fill { struct Fill {
...@@ -1451,14 +1542,73 @@ fill(): void ...@@ -1451,14 +1542,73 @@ fill(): void
![zh-cn_image_0000001238952381](figures/zh-cn_image_0000001238952381.png) ![zh-cn_image_0000001238952381](figures/zh-cn_image_0000001238952381.png)
fill(path: Path2D, fillRule?: CanvasFillRule): void
对封闭路径进行填充。
**参数:**
| 参数 | 类型 | 必填 | 默认值 | 描述 |
| ------ | ------ | ---- | ---- | ------------- |
| path | Path2D | 是 | | Path2D填充路径。 |
| fillRule | CanvasFillRule | 否 | "nonzero" | 指定要填充对象的规则。<br/>可选参数为:"nonzero", "evenodd"。|
**示例:**
```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%')
}
}
```
![zh-cn_image_000000127777774](figures/zh-cn_image_000000127777774.png)
### clip ### clip
clip(): void clip(fillRule?: CanvasFillRule): void
设置当前路径为剪切路径。 设置当前路径为剪切路径。
**示例:** **参数:**
```
| 参数 | 类型 | 必填 | 默认值 | 描述 |
| ------ | ------ | ---- | ---- | ------------- |
| fillRule | CanvasFillRule | 否 | "nonzero" | 指定要剪切对象的规则。<br/>可选参数为:"nonzero", "evenodd"。|
**示例:**
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct Clip { struct Clip {
...@@ -1488,25 +1638,75 @@ clip(): void ...@@ -1488,25 +1638,75 @@ clip(): void
![zh-cn_image_0000001194032462](figures/zh-cn_image_0000001194032462.png) ![zh-cn_image_0000001194032462](figures/zh-cn_image_0000001194032462.png)
clip(path: Path2D, fillRule?: CanvasFillRule): void
对封闭路径进行填充。该接口为空接口。
**参数:**
| 参数 | 类型 | 必填 | 默认值 | 描述 |
| ------ | ------ | ---- | ---- | ------------- |
| path | Path2D | 是 | - | Path2D剪切路径。 |
| fillRule | CanvasFillRule | 否 | "nonzero" | 指定要剪切对象的规则。<br/>可选参数为:"nonzero", "evenodd"。|
### filter
filter(filter: string): void
为Canvas图形设置各类滤镜效果。该接口为空接口。
**参数:**
| 参数 | 类型 | 必填 | 默认值 | 说明 |
| ------ | ------ | ---- | ---- | ------------- |
| filter | string | 是 | - | 接受各类滤镜效果的函数。|
### getTransform
getTransform(): Matrix2D
获取当前被应用到上下文的转换矩阵。该接口为空接口。
### resetTransform
resetTransform(): void
使用单位矩阵重新设置当前变形。该接口为空接口。
### direction
direction(direction: CanvasDirection): void
绘制文本时,描述当前文本方向的属性。该接口为空接口。
### rotate ### rotate
rotate(rotate: number): void rotate(angle: number): void
针对当前坐标轴进行顺时针旋转。 针对当前坐标轴进行顺时针旋转。
**参数:** **参数:**
| 参数 | 类型 | 必填 | 默认值 | 描述 |
| ------ | ------ | ---- | ---- | ---------------------------------------- |
| rotate | number | 是 | 0 | 设置顺时针旋转的弧度值,可以通过Math.PI&nbsp;/&nbsp;180将角度转换为弧度值。 |
**示例:** | 参数 | 类型 | 必填 | 默认值 | 描述 |
``` | ------ | ------ | ---- | ---- | ---------------------------------------- |
| angle | number | 是 | 0 | 设置顺时针旋转的弧度值,可以通过Math.PI&nbsp;/&nbsp;180将角度转换为弧度值。 |
**示例:**
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct Rotate { struct Rotate {
private settings: RenderingContextSettings = new RenderingContextSettings(true) private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context) Canvas(this.context)
...@@ -1533,20 +1733,23 @@ scale(x: number, y: number): void ...@@ -1533,20 +1733,23 @@ scale(x: number, y: number): void
设置canvas画布的缩放变换属性,后续的绘制操作将按照缩放比例进行缩放。 设置canvas画布的缩放变换属性,后续的绘制操作将按照缩放比例进行缩放。
**参数:** **参数:**
| 参数 | 类型 | 必填 | 默认值 | 描述 |
| ---- | ------ | ---- | ---- | ----------- |
| x | number | 是 | 0 | 设置水平方向的缩放值。 |
| y | number | 是 | 0 | 设置垂直方向的缩放值。 |
**示例:** | 参数 | 类型 | 必填 | 默认值 | 描述 |
``` | ---- | ------ | ---- | ---- | ----------- |
| x | number | 是 | 0 | 设置水平方向的缩放值。 |
| y | number | 是 | 0 | 设置垂直方向的缩放值。 |
**示例:**
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct Scale { struct Scale {
private settings: RenderingContextSettings = new RenderingContextSettings(true) private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context) Canvas(this.context)
...@@ -1570,35 +1773,38 @@ scale(x: number, y: number): void ...@@ -1570,35 +1773,38 @@ scale(x: number, y: number): void
### transform ### transform
transform(scaleX: number, skewX: number, skewY: number, scaleY: number, translateX: number, translateY: number): void transform(a: number, b: number, c: number, d: number, e: number, f: number): void
transform方法对应一个变换矩阵,想对一个图形进行变化的时候,只要设置此变换矩阵相应的参数,对图形的各个定点的坐标分别乘以这个矩阵,就能得到新的定点的坐标。矩阵变换效果可叠加。 transform方法对应一个变换矩阵,想对一个图形进行变化的时候,只要设置此变换矩阵相应的参数,对图形的各个定点的坐标分别乘以这个矩阵,就能得到新的定点的坐标。矩阵变换效果可叠加。
> **说明:** > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
> 变换后的坐标计算方式(x和y为变换前坐标,x'和y'为变换后坐标): > 变换后的坐标计算方式(x和y为变换前坐标,x'和y'为变换后坐标):
> >
> - x' = scaleX \* x + skewY \* y + translateX > - x' = scaleX \* x + skewY \* y + translateX
> >
> - y' = skewX \* x + scaleY \* y + translateY > - y' = skewX \* x + scaleY \* y + translateY
**参数:** **参数:**
| 参数 | 类型 | 必填 | 默认值 | 描述 |
| ---------- | ------ | ---- | ---- | -------- |
| scaleX | number | 是 | 0 | 指定水平缩放值。 |
| skewX | number | 是 | 0 | 指定水平倾斜值。 |
| skewY | number | 是 | 0 | 指定垂直倾斜值。 |
| scaleY | number | 是 | 0 | 指定垂直缩放值。 |
| translateX | number | 是 | 0 | 指定水平移动值。 |
| translateY | number | 是 | 0 | 指定垂直移动值。 |
**示例:** | 参数 | 类型 | 必填 | 默认值 | 描述 |
``` | ---------- | ------ | ---- | ---- | -------- |
| a | number | 是 | 0 |scaleX: 指定水平缩放值。 |
| b | number | 是 | 0 |skewX: 指定水平倾斜值。 |
| c | number | 是 | 0 |skewY: 指定垂直倾斜值。 |
| d | number | 是 | 0 |scaleY: 指定垂直缩放值。 |
| e | number | 是 | 0 |translateX: 指定水平移动值。 |
| f | number | 是 | 0 |translateY: 指定垂直移动值。 |
**示例:**
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct Transform { struct Transform {
private settings: RenderingContextSettings = new RenderingContextSettings(true) private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context) Canvas(this.context)
...@@ -1627,28 +1833,31 @@ transform方法对应一个变换矩阵,想对一个图形进行变化的时 ...@@ -1627,28 +1833,31 @@ transform方法对应一个变换矩阵,想对一个图形进行变化的时
### setTransform ### setTransform
setTransform(scaleX: number, skewX: number, skewY: number, scale: number, translateX: number, translateY: number): void setTransform(a: number, b: number, c: number, d: number, e: number, f: number): void
setTransfrom方法使用的参数和transform()方法相同,但setTransform()方法会重置现有的变换矩阵并创建新的变换矩阵。 setTransfrom方法使用的参数和transform()方法相同,但setTransform()方法会重置现有的变换矩阵并创建新的变换矩阵。
**参数:** **参数:**
| 参数 | 类型 | 必填 | 默认值 | 描述 |
| ---------- | ------ | ---- | ---- | -------- |
| scaleX | number | 是 | 0 | 指定水平缩放值。 |
| skewX | number | 是 | 0 | 指定水平倾斜值。 |
| skewY | number | 是 | 0 | 指定垂直倾斜值。 |
| scaleY | number | 是 | 0 | 指定垂直缩放值。 |
| translateX | number | 是 | 0 | 指定水平移动值。 |
| translateY | number | 是 | 0 | 指定垂直移动值。 |
**示例:** | 参数 | 类型 | 必填 | 默认值 | 描述 |
``` | ---------- | ------ | ---- | ---- | -------- |
| a | number | 是 | 0 |scaleX: 指定水平缩放值。 |
| b | number | 是 | 0 |skewX: 指定水平倾斜值。 |
| c | number | 是 | 0 |skewY: 指定垂直倾斜值。 |
| d | number | 是 | 0 |scaleY: 指定垂直缩放值。 |
| e | number | 是 | 0 |translateX: 指定水平移动值。 |
| f | number | 是 | 0 |translateY: 指定垂直移动值。 |
**示例:**
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct SetTransform { struct SetTransform {
private settings: RenderingContextSettings = new RenderingContextSettings(true) private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context) Canvas(this.context)
...@@ -1672,26 +1881,34 @@ setTransfrom方法使用的参数和transform()方法相同,但setTransform() ...@@ -1672,26 +1881,34 @@ setTransfrom方法使用的参数和transform()方法相同,但setTransform()
![zh-cn_image_0000001238712421](figures/zh-cn_image_0000001238712421.png) ![zh-cn_image_0000001238712421](figures/zh-cn_image_0000001238712421.png)
setTransform(transform?: Matrix2D): void
以Matrix2D对象为模板重置现有的变换矩阵并创建新的变换矩阵。该接口为空接口。
### translate ### translate
translate(x: number, y: number): void translate(x: number, y: number): void
移动当前坐标系的原点。 移动当前坐标系的原点。
**参数:** **参数:**
| 参数 | 类型 | 必填 | 默认值 | 描述 |
| ---- | ------ | ---- | ---- | -------- |
| x | number | 是 | 0 | 设置水平平移量。 |
| y | number | 是 | 0 | 设置竖直平移量。 |
**示例:** | 参数 | 类型 | 必填 | 默认值 | 描述 |
``` | ---- | ------ | ---- | ---- | -------- |
| x | number | 是 | 0 | 设置水平平移量。 |
| y | number | 是 | 0 | 设置竖直平移量。 |
**示例:**
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct Translate { struct Translate {
private settings: RenderingContextSettings = new RenderingContextSettings(true) private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context) Canvas(this.context)
...@@ -1717,34 +1934,38 @@ translate(x: number, y: number): void ...@@ -1717,34 +1934,38 @@ translate(x: number, y: number): void
drawImage(image: ImageBitmap | PixelMap, dx: number, dy: number): void drawImage(image: ImageBitmap | PixelMap, dx: number, dy: number): void
drawImage(image: ImageBitmap | PixelMap, dx: number, dy: number, dWidth: number, dHeight: number): void drawImage(image: ImageBitmap | PixelMap, dx: number, dy: number, dw: number, dh: number): void
drawImage(image: ImageBitmap | PixelMap, sx: number, sy: number, sWidth: number, sHeight: number, dx: number, dy: number, dWidth: number, dHeight: number):void drawImage(image: ImageBitmap | PixelMap, sx: number, sy: number, sw: number, sh: number, dx: number, dy: number, dw: number, dh: number):void
进行图像绘制。 进行图像绘制。
**参数:** **参数:**
| 参数 | 类型 | 必填 | 默认值 | 描述 |
| ------- | ---------------------------------------- | ---- | ---- | ---------------------------------------- |
| image | [ImageBitmap](ts-components-canvas-imagebitmap.md)[PixelMap](../apis/js-apis-image.md#pixelmap7) | 是 | null | 图片资源,请参考ImageBitmap或PixelMap。 |
| sx | number | 否 | 0 | 裁切源图像时距离源图像左上角的x坐标值。 |
| sy | number | 否 | 0 | 裁切源图像时距离源图像左上角的y坐标值。 |
| sWidth | number | 否 | 0 | 裁切源图像时需要裁切的宽度。 |
| sHeight | number | 否 | 0 | 裁切源图像时需要裁切的高度。 |
| dx | number | 是 | 0 | 绘制区域左上角在x轴的位置。 |
| dy | number | 是 | 0 | 绘制区域左上角在y&nbsp;轴的位置。 |
| dWidth | number | 否 | 0 | 绘制区域的宽度。 当绘制区域的宽度和裁剪图像的宽度不一致时,将图像宽度拉伸或压缩为绘制区域的宽度。 |
| dHeight | number | 否 | 0 | 绘制区域的高度。 当绘制区域的高度和裁剪图像的高度不一致时,将图像高度拉伸或压缩为绘制区域的高度。 |
| 参数 | 类型 | 必填 | 默认值 | 描述 |
| ------- | ---------------------------------------- | ---- | ---- | ---------------------------------------- |
| image | [ImageBitmap](ts-components-canvas-imagebitmap.md)[PixelMap](../apis/js-apis-image.md#pixelmap7) | 是 | null | 图片资源,请参考ImageBitmap或PixelMap。 |
| sx | number | 否 | 0 | 裁切源图像时距离源图像左上角的x坐标值。 |
| sy | number | 否 | 0 | 裁切源图像时距离源图像左上角的y坐标值。 |
| sw | number | 否 | 0 | 裁切源图像时需要裁切的宽度。 |
| sh | number | 否 | 0 | 裁切源图像时需要裁切的高度。 |
| dx | number | 是 | 0 | 绘制区域左上角在x轴的位置。 |
| dy | number | 是 | 0 | 绘制区域左上角在y&nbsp;轴的位置。 |
| dw | number | 否 | 0 | 绘制区域的宽度。当绘制区域的宽度和裁剪图像的宽度不一致时,将图像宽度拉伸或压缩为绘制区域的宽度。 |
| dh | number | 否 | 0 | 绘制区域的高度。当绘制区域的高度和裁剪图像的高度不一致时,将图像高度拉伸或压缩为绘制区域的高度。 |
**示例:**
``` **示例:**
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct ImageExample { struct ImageExample {
private settings: RenderingContextSettings = new RenderingContextSettings(true); private settings: RenderingContextSettings = new RenderingContextSettings(true);
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
private img:ImageBitmap = new ImageBitmap("common/images/example.jpg"); private img:ImageBitmap = new ImageBitmap("common/images/example.jpg");
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context) Canvas(this.context)
...@@ -1766,79 +1987,257 @@ drawImage(image: ImageBitmap | PixelMap, sx: number, sy: number, sWidth: number, ...@@ -1766,79 +1987,257 @@ drawImage(image: ImageBitmap | PixelMap, sx: number, sy: number, sWidth: number,
### createImageData ### createImageData
createImageData(width: number, height: number): Object createImageData(sw: number, sh: number): ImageData
创建新的ImageData 对象,请参考[ImageData](ts-components-canvas-imagebitmap.md) 创建新的ImageData 对象,请参考[ImageData](ts-components-canvas-imagebitmap.md)
**参数:** **参数:**
| 参数 | 类型 | 必填 | 默认 | 描述 |
| ------ | ------ | ---- | ---- | ------------- | | 参数 | 类型 | 必填 | 默认 | 描述 |
| width | number | 是 | 0 | ImageData的宽度。 | | ------ | ------ | ---- | ---- | ------------- |
| height | number | 是 | 0 | ImageData的高度。 | | sw | number | 是 | 0 | ImageData的宽度。 |
| sh | number | 是 | 0 | ImageData的高度。 |
### createImageData ### createImageData
createImageData(imageData: Object): Object createImageData(imageData: ImageData): ImageData
创建新的ImageData 对象,请参考[ImageData](ts-components-canvas-imagebitmap.md) 创建新的ImageData 对象,请参考[ImageData](ts-components-canvas-imagebitmap.md)
**参数:** **参数:**
| 参数 | 类型 | 必填 | 默认 | 描述 |
| --------- | ------ | ---- | ---- | ----------------- | | 参数 | 类型 | 必填 | 默认 | 描述 |
| imagedata | Object | 是 | null | 复制现有的ImageData对象。 | | --------- | ------ | ---- | ---- | ----------------- |
| imagedata | [ImageData](ts-components-canvas-imagebitmap.md)| 是 | null | 复制现有的ImageData对象。 |
**返回值:**
| 类型 | 说明 |
| ---------- | ---------------------------------------- |
| [ImageData](ts-components-canvas-imagebitmap.md) | 新的ImageData对象。|
### getPixelMap ### getPixelMap
getPixelMap(sx: number, sy: number, sw: number, sh: number): PixelMap getPixelMap(sx: number, sy: number, sw: number, sh: number): PixelMap
以当前canvas指定区域内的像素创建[PixelMap](../apis/js-apis-image.md#pixelmap7)对象。 以当前canvas指定区域内的像素创建[PixelMap](../apis/js-apis-image.md#pixelmap7)对象。
**参数:**
| 参数 | 类型 | 必填 | 默认值 | 描述 | **参数:**
| ---- | ------ | ---- | ---- | --------------- |
| sx | number | 是 | 0 | 需要输出的区域的左上角x坐标。 | | 参数 | 类型 | 必填 | 默认值 | 描述 |
| sy | number | 是 | 0 | 需要输出的区域的左上角y坐标。 | | ---- | ------ | ---- | ---- | --------------- |
| sw | number | 是 | 0 | 需要输出的区域的宽度。 | | sx | number | 是 | 0 | 需要输出的区域的左上角x坐标。 |
| sh | number | 是 | 0 | 需要输出的区域的高度。 | | sy | number | 是 | 0 | 需要输出的区域的左上角y坐标。 |
| sw | number | 是 | 0 | 需要输出的区域的宽度。 |
| sh | number | 是 | 0 | 需要输出的区域的高度。 |
**返回值:**
| 类型 | 说明 |
| ---------- | ---------------------------------------- |
| [PixelMap](../apis/js-apis-image.md#pixelmap7) | 新的PixelMap对象。 |
### getImageData ### getImageData
getImageData(sx: number, sy: number, sw: number, sh: number): Object getImageData(sx: number, sy: number, sw: number, sh: number): ImageData
以当前canvas指定区域内的像素创建[ImageData](ts-components-canvas-imagebitmap.md)对象。 以当前canvas指定区域内的像素创建[ImageData](ts-components-canvas-imagebitmap.md)对象。
**参数:**
| 参数 | 类型 | 必填 | 默认值 | 描述 | **参数:**
| ---- | ------ | ---- | ---- | --------------- |
| sx | number | 是 | 0 | 需要输出的区域的左上角x坐标。 | | 参数 | 类型 | 必填 | 默认值 | 描述 |
| sy | number | 是 | 0 | 需要输出的区域的左上角y坐标。 | | ---- | ------ | ---- | ---- | --------------- |
| sw | number | 是 | 0 | 需要输出的区域的宽度。 | | sx | number | 是 | 0 | 需要输出的区域的左上角x坐标。 |
| sh | number | 是 | 0 | 需要输出的区域的高度。 | | sy | number | 是 | 0 | 需要输出的区域的左上角y坐标。 |
| sw | number | 是 | 0 | 需要输出的区域的宽度。 |
| sh | number | 是 | 0 | 需要输出的区域的高度。 |
**返回值:**
| 类型 | 说明 |
| ---------- | ---------------------------------------- |
| [ImageData](ts-components-canvas-imagebitmap.md) | 新的ImageData对象。 |
### putImageData ### putImageData
putImageData(imageData: Object, dx: number, dy: number, dirtyX?: number, dirtyY?: number, dirtyWidth?: number, dirtyHeight?: number): void putImageData(imageData: ImageData, dx: number, dy: number): void
putImageData(imageData: ImageData, dx: number, dy: number, dirtyX: number, dirtyY: number, dirtyWidth: number, dirtyHeight: number): void
使用[ImageData](ts-components-canvas-imagebitmap.md)数据填充新的矩形区域。 使用[ImageData](ts-components-canvas-imagebitmap.md)数据填充新的矩形区域。
**参数:**
| 参数 | 类型 | 必填 | 默认值 | 描述 |
| ----------- | ------ | ---- | ------------ | ----------------------------- |
| imagedata | [ImageData](ts-components-canvas-imagebitmap.md) | 是 | null | 包含像素值的ImageData对象。 |
| dx | number | 是 | 0 | 填充区域在x轴方向的偏移量。 |
| dy | number | 是 | 0 | 填充区域在y轴方向的偏移量。 |
| dirtyX | number | 否 | 0 | 源图像数据矩形裁切范围左上角距离源图像左上角的x轴偏移量。 |
| dirtyY | number | 否 | 0 | 源图像数据矩形裁切范围左上角距离源图像左上角的y轴偏移量。 |
| dirtyWidth | number | 否 | imagedata的宽度 | 源图像数据矩形裁切范围的宽度。 |
| dirtyHeight | number | 否 | imagedata的高度 | 源图像数据矩形裁切范围的高度。 |
**示例:**
```ts
// xxx.ets
@Entry
@Component
struct PutImageData {
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 imageData = this.context.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.context.putImageData(imageData, 10, 10)
})
}
.width('100%')
.height('100%')
}
}
```
![zh-cn_image_0000001238952387](figures/zh-cn_image_0000001238952387.png)
### setLineDash
setLineDash(segments: number[]): void
设置画布的虚线样式。
**参数:** **参数:**
| 参数 | 类型 | 必填 | 默认值 | 描述 |
| ----------- | ------ | ---- | ------------ | ----------------------------- | | 参数 | 类型 | 描述 |
| imagedata | Object | 是 | null | 包含像素值的ImageData对象。 | | -------- | ----- | -------------------- |
| dx | number | 是 | 0 | 填充区域在x轴方向的偏移量。 | | segments | number[] | 描述线段如何交替和线段间距长度的数组。 |
| dy | number | 是 | 0 | 填充区域在y轴方向的偏移量。 |
| dirtyX | number | 否 | 0 | 源图像数据矩形裁切范围左上角距离源图像左上角的x轴偏移量。 | **示例:**
| dirtyY | number | 否 | 0 | 源图像数据矩形裁切范围左上角距离源图像左上角的y轴偏移量。 |
| dirtyWidth | number | 否 | imagedata的宽度 | 源图像数据矩形裁切范围的宽度。 | ```ts
| dirtyHeight | number | 否 | imagedata的高度 | 源图像数据矩形裁切范围的高度。 | // xxx.ets
@Entry
@Component
struct SetLineDash {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context)
.width('100%')
.height('100%')
.backgroundColor('#ffff00')
.onReady(() =>{
this.context.arc(100, 75, 50, 0, 6.28)
this.context.setLineDash([10,20])
})
}
.width('100%')
.height('100%')
}
}
```
![zh-cn_image_000000127777771](figures/zh-cn_image_000000127777771.png)
### getLineDash
getLineDash(): number[]
获得当前画布的虚线样式。
**返回值:**
| 类型 | 说明 |
| ----- | ------------------------ |
| number[] | 返回数组,该数组用来描述线段如何交替和间距长度。 |
**示例:** **示例:**
```ts
// xxx.ets
@Entry
@Component
struct GetLineDash {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context)
.width('100%')
.height('100%')
.backgroundColor('#ffff00')
.onReady(() =>{
var grad = this.context.createLinearGradient(50,0, 300,100)
this.context.arc(100, 75, 50, 0, 6.28)
this.context.setLineDash([10,20])
this.context.stroke();
let res = this.context.getLineDash()
})
}
.width('100%')
.height('100%')
}
}
``` ```
### imageSmoothingQuality
imageSmoothingQuality(quality: imageSmoothingQuality)
用于设置图像平滑度。该接口为空接口。
**参数:**
| 参数 | 类型 | 描述 |
| ------ | ----------- | ------------------ |
| quality |imageSmoothingQuality | 支持如下三种类型:'low',&nbsp;'medium',&nbsp;'high'。 |
### transferFromImageBitmap
transferFromImageBitmap(bitmap: ImageBitmap): void
显示给定的ImageBitmap对象。
**参数:**
| 参数 | 类型 | 描述 |
| ------ | ----------- | ------------------ |
| bitmap |[ImageData](ts-components-canvas-imagebitmap.md) | 待显示的ImageBitmap对象。 |
**示例:**
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct PutImageData { struct PutImageData {
private settings: RenderingContextSettings = new RenderingContextSettings(true) private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings)
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
...@@ -1847,14 +2246,16 @@ putImageData(imageData: Object, dx: number, dy: number, dirtyX?: number, dirtyY? ...@@ -1847,14 +2246,16 @@ putImageData(imageData: Object, dx: number, dy: number, dirtyX?: number, dirtyY?
.height('100%') .height('100%')
.backgroundColor('#ffff00') .backgroundColor('#ffff00')
.onReady(() =>{ .onReady(() =>{
var imageData = this.context.createImageData(100, 100) var imageData = this.offContext.createImageData(100, 100)
for (var i = 0; i < imageData.data.length; i += 4) { for (var i = 0; i < imageData.data.length; i += 4) {
imageData.data[i + 0] = 255 imageData.data[i + 0] = 255
imageData.data[i + 1] = 0 imageData.data[i + 1] = 0
imageData.data[i + 2] = 255 imageData.data[i + 2] = 255
imageData.data[i + 3] = 255 imageData.data[i + 3] = 255
} }
this.context.putImageData(imageData, 10, 10) this.offContext.putImageData(imageData, 10, 10)
var image = this.offContext.transferToImageBitmap()
this.context.transferFromImageBitmap(image)
}) })
} }
.width('100%') .width('100%')
...@@ -1862,8 +2263,52 @@ putImageData(imageData: Object, dx: number, dy: number, dirtyX?: number, dirtyY? ...@@ -1862,8 +2263,52 @@ putImageData(imageData: Object, dx: number, dy: number, dirtyX?: number, dirtyY?
} }
} }
``` ```
![zh-cn_image_000000127777773](figures/zh-cn_image_000000127777773.png)
![zh-cn_image_0000001238952387](figures/zh-cn_image_0000001238952387.png) ### toDataURL
toDataURL(type?: string, quality?: number): string
生成一个包含图片展示的URL。
**参数:**
| 参数名 | 参数类型 | 必填 | 描述 |
| ------- | ------ | ---- | ---------------------------------------- |
| type | string | 否 | 可选参数,用于指定图像格式,默认格式为image/png。 |
| quality | number | 否 | 在指定图片格式为image/jpeg或image/webp的情况下,可以从0到1的区间内选择图片的质量。如果超出取值范围,将会使用默认值0.92。 |
**返回值:**
| 类型 | 说明 |
| ------ | --------- |
| string | 图像的URL地址。 |
**示例:**
```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
...@@ -1872,14 +2317,17 @@ restore(): void ...@@ -1872,14 +2317,17 @@ restore(): void
对保存的绘图上下文进行恢复。 对保存的绘图上下文进行恢复。
**示例:** **示例:**
```
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct CanvasExample { struct CanvasExample {
private settings: RenderingContextSettings = new RenderingContextSettings(true) private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private img:ImageBitmap = new ImageBitmap("common/images/icon.jpg")
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context) Canvas(this.context)
...@@ -1901,16 +2349,18 @@ restore(): void ...@@ -1901,16 +2349,18 @@ restore(): void
save(): void save(): void
对当前的绘图上下文进行保存 将当前状态放入栈中,保存canvas的全部状态,通常在需要保存绘制状态时调用
**示例:** **示例:**
```
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct CanvasExample { struct CanvasExample {
private settings: RenderingContextSettings = new RenderingContextSettings(true) private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context) Canvas(this.context)
...@@ -1934,16 +2384,19 @@ createLinearGradient(x0: number, y0: number, x1: number, y1: number): void ...@@ -1934,16 +2384,19 @@ createLinearGradient(x0: number, y0: number, x1: number, y1: number): void
创建一个线性渐变色。 创建一个线性渐变色。
**参数:** **参数:**
| 参数 | 类型 | 必填 | 默认值 | 描述 |
| ---- | ------ | ---- | ---- | -------- |
| x0 | number | 是 | 0 | 起点的x轴坐标。 |
| y0 | number | 是 | 0 | 起点的y轴坐标。 |
| x1 | number | 是 | 0 | 终点的x轴坐标。 |
| y1 | number | 是 | 0 | 终点的y轴坐标。 |
**示例:** | 参数 | 类型 | 必填 | 默认值 | 描述 |
``` | ---- | ------ | ---- | ---- | -------- |
| x0 | number | 是 | 0 | 起点的x轴坐标。 |
| y0 | number | 是 | 0 | 起点的y轴坐标。 |
| x1 | number | 是 | 0 | 终点的x轴坐标。 |
| y1 | number | 是 | 0 | 终点的y轴坐标。 |
**示例:**
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct CreateLinearGradient { struct CreateLinearGradient {
...@@ -1980,18 +2433,21 @@ createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number, ...@@ -1980,18 +2433,21 @@ createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number,
创建一个径向渐变色。 创建一个径向渐变色。
**参数:** **参数:**
| 参数 | 类型 | 必填 | 默认值 | 描述 |
| ---- | ------ | ---- | ---- | ----------------- |
| x0 | number | 是 | 0 | 起始圆的x轴坐标。 |
| y0 | number | 是 | 0 | 起始圆的y轴坐标。 |
| r0 | number | 是 | 0 | 起始圆的半径。必须是非负且有限的。 |
| x1 | number | 是 | 0 | 终点圆的x轴坐标。 |
| y1 | number | 是 | 0 | 终点圆的y轴坐标。 |
| r1 | number | 是 | 0 | 终点圆的半径。必须为非负且有限的。 |
**示例:** | 参数 | 类型 | 必填 | 默认值 | 描述 |
``` | ---- | ------ | ---- | ---- | ----------------- |
| x0 | number | 是 | 0 | 起始圆的x轴坐标。 |
| y0 | number | 是 | 0 | 起始圆的y轴坐标。 |
| r0 | number | 是 | 0 | 起始圆的半径。必须是非负且有限的。 |
| x1 | number | 是 | 0 | 终点圆的x轴坐标。 |
| y1 | number | 是 | 0 | 终点圆的y轴坐标。 |
| r1 | number | 是 | 0 | 终点圆的半径。必须为非负且有限的。 |
**示例:**
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct CreateRadialGradient { struct CreateRadialGradient {
......
# Canvas # Canvas
> **说明:** > **说明:** 该组件从API Version 8开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
>
> 该组件从API Version 8开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
提供画布组件,用于自定义绘制图形。 提供画布组件,用于自定义绘制图形。
...@@ -16,13 +14,13 @@ ...@@ -16,13 +14,13 @@
## 接口 ## 接口
Canvas(context: CanvasRenderingContext2D) Canvas(context?: CanvasRenderingContext2D)
**参数:** **参数:**
| 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 | | 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 |
| ------- | ---------------------------------------- | ---- | ---- | ---------------------------- | | ------- | ---------------------------------------- | ---- | ---- | ---------------------------- |
| context | [CanvasRenderingContext2D](ts-canvasrenderingcontext2d.md) | 是 | - | 见CanvasRenderingContext2D对象。 | | context | [CanvasRenderingContext2D](ts-canvasrenderingcontext2d.md) | 否 | - | 见CanvasRenderingContext2D对象。 |
## 属性 ## 属性
...@@ -34,7 +32,7 @@ Canvas(context: CanvasRenderingContext2D) ...@@ -34,7 +32,7 @@ Canvas(context: CanvasRenderingContext2D)
| 名称 | 参数 | 描述 | | 名称 | 参数 | 描述 |
| ----------------------------- | ---- | -------------------- | | ----------------------------- | ---- | -------------------- |
| onReady(callback: () => void) | 无 | 画布组件的事件回调,可以在此时进行绘制。 | | onReady(event: () => void) | 无 | 画布组件的事件回调,可以在此时进行绘制。 |
## 示例 ## 示例
......
# ImageBitmap对象 # ImageBitmap对象
> **说明:** > **说明:**
> > 从 API Version 8 开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
> 从 API Version 8 开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
CanvasImageData对象可以存储canvas渲染的像素数据。 ImageBitmap对象可以存储canvas渲染的像素数据。
## 属性 ## 属性
| 属性 | 类型 | 描述 | | 属性 | 类型 | 描述 |
| ------ | ------------------------- | ---------------------------- | | -------- | -------- | -------- |
| width | number | 矩形区域实际像素宽度。 | | width | number | ImageBitmap的像素宽度。 |
| height | number | 矩形区域实际像素高度。 | | height | number | ImageBitmap的像素高度。 |
| data | &lt;Uint8ClampedArray&gt; | 一维数组,保存了相应的颜色数据,数据值范围为0到255。 |
## 方法
### close
close()
释放ImageBitmap对象相关联的所有图形资源。该接口为空接口。
\ No newline at end of file
# ImageData对象 # ImageData对象
> **说明:** > **说明:**
> > 从 API Version 8 开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
> 从 API Version 8 开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
ImageData对象可以存储canvas渲染的像素数据。 ImageData对象可以存储canvas渲染的像素数据。
...@@ -10,8 +9,9 @@ ImageData对象可以存储canvas渲染的像素数据。 ...@@ -10,8 +9,9 @@ ImageData对象可以存储canvas渲染的像素数据。
## 属性 ## 属性
| 属性 | 类型 | 描述 | | 属性 | 类型 | 描述 |
| ------ | ------------------------- | ---------------------------- | | -------- | -------- | -------- |
| width | number | 矩形区域实际像素宽度。 | | width | number | 矩形区域实际像素宽度。 |
| height | number | 矩形区域实际像素高度。 | | height | number | 矩形区域实际像素高度。 |
| data | &lt;Uint8ClampedArray&gt; | 一维数组,保存了相应的颜色数据,数据值范围为0到255。 | | data | Uint8ClampedArray | 一维数组,保存了相应的颜色数据,数据值范围为0到255。 |
# Path2D对象 # Path2D对象
> **说明:** > **说明:**
> > 从 API Version 8 开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
> 从 API Version 8 开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
路径对象,支持通过对象的接口进行路径的描述,并通过Canvas的stroke接口进行绘制。 路径对象,支持通过对象的接口进行路径的描述,并通过Canvas的stroke接口进行绘制。
...@@ -10,26 +9,31 @@ ...@@ -10,26 +9,31 @@
## addPath ## addPath
addPath(path: Object): void addPath(path: path2D, transform?:Matrix2D): void
将另一个路径添加到当前的路径对象中。 将另一个路径添加到当前的路径对象中。
- 参数 **参数:**
| 参数 | 类型 | 必填 | 默认值 | 描述 |
| ---- | ------ | ---- | ---- | -------------- |
| path | Object | 是 | null | 需要添加到当前路径的路径对象 |
- 示例 | 参数 | 类型 | 必填 | 默认值 | 描述 |
``` | -------- | -------- | -------- | -------- | -------- |
| path | path2D | 是 | - | 需要添加到当前路径的路径对象。|
| transform | Matrix2D | 否 | null | 新增路径的变换矩阵对象。 |
**示例:**
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct AddPath { struct AddPath {
private settings: RenderingContextSettings = new RenderingContextSettings(true) private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private path2Da: Path2D = new Path2D("M250 150 L150 350 L350 350 Z") private path2Da: Path2D = new Path2D("M250 150 L150 350 L350 350 Z")
private path2Db: Path2D = new Path2D() private path2Db: Path2D = new Path2D()
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context) Canvas(this.context)
...@@ -56,15 +60,17 @@ closePath(): void ...@@ -56,15 +60,17 @@ closePath(): void
将路径的当前点移回到路径的起点,当前点到起点间画一条直线。如果形状已经闭合或只有一个点,则此功能不执行任何操作。 将路径的当前点移回到路径的起点,当前点到起点间画一条直线。如果形状已经闭合或只有一个点,则此功能不执行任何操作。
- 示例 **示例:**
```
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct ClosePath { struct ClosePath {
private settings: RenderingContextSettings = new RenderingContextSettings(true) private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private path2Db: Path2D = new Path2D() private path2Db: Path2D = new Path2D()
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context) Canvas(this.context)
...@@ -94,21 +100,24 @@ moveTo(x: number, y: number): void ...@@ -94,21 +100,24 @@ moveTo(x: number, y: number): void
将路径的当前坐标点移动到目标点,移动过程中不绘制线条。 将路径的当前坐标点移动到目标点,移动过程中不绘制线条。
- 参数 **参数:**
| 参数 | 类型 | 必填 | 默认值 | 描述 |
| ---- | ------ | ---- | ---- | ------- |
| x | number | 是 | 0 | 目标点X轴坐标 |
| y | number | 是 | 0 | 目标点Y轴坐标 |
- 示例 | 参数 | 类型 | 必填 | 默认值 | 描述 |
``` | -------- | -------- | -------- | -------- | -------- |
| x | number | 是 | 0 | 目标点X轴坐标。 |
| y | number | 是 | 0 | 目标点Y轴坐标。 |
**示例:**
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct MoveTo { struct MoveTo {
private settings: RenderingContextSettings = new RenderingContextSettings(true) private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private path2Db: Path2D = new Path2D() private path2Db: Path2D = new Path2D()
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context) Canvas(this.context)
...@@ -138,21 +147,24 @@ lineTo(x: number, y: number): void ...@@ -138,21 +147,24 @@ lineTo(x: number, y: number): void
从当前点绘制一条直线到目标点。 从当前点绘制一条直线到目标点。
- 参数 **参数:**
| 参数 | 类型 | 必填 | 默认值 | 描述 |
| ---- | ------ | ---- | ---- | ------- |
| x | number | 是 | 0 | 目标点X轴坐标 |
| y | number | 是 | 0 | 目标点Y轴坐标 |
- 示例 | 参数 | 类型 | 必填 | 默认值 | 描述 |
``` | -------- | -------- | -------- | -------- | -------- |
| x | number | 是 | 0 | 目标点X轴坐标。 |
| y | number | 是 | 0 | 目标点Y轴坐标。 |
**示例:**
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct LineTo { struct LineTo {
private settings: RenderingContextSettings = new RenderingContextSettings(true) private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private path2Db: Path2D = new Path2D() private path2Db: Path2D = new Path2D()
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context) Canvas(this.context)
...@@ -183,25 +195,28 @@ bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number, ...@@ -183,25 +195,28 @@ bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number,
创建三次贝赛尔曲线的路径。 创建三次贝赛尔曲线的路径。
- 参数 **参数:**
| 参数 | 类型 | 必填 | 默认值 | 描述 |
| ---- | ------ | ---- | ---- | -------------- | | 参数 | 类型 | 必填 | 默认值 | 描述 |
| cp1x | number | 是 | 0 | 第一个贝塞尔参数的x坐标值。 | | -------- | -------- | -------- | -------- | -------- |
| cp1y | number | 是 | 0 | 第一个贝塞尔参数的y坐标值。 | | cp1x | number | 是 | 0 | 第一个贝塞尔参数的x坐标值。 |
| cp2x | number | 是 | 0 | 第二个贝塞尔参数的x坐标值。 | | cp1y | number | 是 | 0 | 第一个贝塞尔参数的y坐标值。 |
| cp2y | number | 是 | 0 | 第二个贝塞尔参数的y坐标值。 | | cp2x | number | 是 | 0 | 第二个贝塞尔参数的x坐标值。 |
| x | number | 是 | 0 | 路径结束时的x坐标值。 | | cp2y | number | 是 | 0 | 第二个贝塞尔参数的y坐标值。 |
| y | number | 是 | 0 | 路径结束时的y坐标值。 | | x | number | 是 | 0 | 路径结束时的x坐标值。 |
| y | number | 是 | 0 | 路径结束时的y坐标值。 |
- 示例
``` **示例:**
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct BezierCurveTo { struct BezierCurveTo {
private settings: RenderingContextSettings = new RenderingContextSettings(true) private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private path2Db: Path2D = new Path2D() private path2Db: Path2D = new Path2D()
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context) Canvas(this.context)
...@@ -228,23 +243,26 @@ quadraticCurveTo(cpx: number, cpy: number, x: number ,y: number): void ...@@ -228,23 +243,26 @@ quadraticCurveTo(cpx: number, cpy: number, x: number ,y: number): void
创建二次贝赛尔曲线的路径。 创建二次贝赛尔曲线的路径。
- 参数 **参数:**
| 参数 | 类型 | 必填 | 默认值 | 描述 |
| ---- | ------ | ---- | ---- | ----------- |
| cpx | number | 是 | 0 | 贝塞尔参数的x坐标值。 |
| cpy | number | 是 | 0 | 贝塞尔参数的y坐标值。 |
| x | number | 是 | 0 | 路径结束时的x坐标值。 |
| y | number | 是 | 0 | 路径结束时的y坐标值。 |
- 示例 | 参数 | 类型 | 必填 | 默认值 | 描述 |
``` | -------- | -------- | -------- | -------- | -------- |
| cpx | number | 是 | 0 | 贝塞尔参数的x坐标值。 |
| cpy | number | 是 | 0 | 贝塞尔参数的y坐标值。 |
| x | number | 是 | 0 | 路径结束时的x坐标值。 |
| y | number | 是 | 0 | 路径结束时的y坐标值。 |
**示例:**
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct QuadraticCurveTo { struct QuadraticCurveTo {
private settings: RenderingContextSettings = new RenderingContextSettings(true) private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private path2Db: Path2D = new Path2D() private path2Db: Path2D = new Path2D()
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context) Canvas(this.context)
...@@ -268,29 +286,32 @@ quadraticCurveTo(cpx: number, cpy: number, x: number ,y: number): void ...@@ -268,29 +286,32 @@ quadraticCurveTo(cpx: number, cpy: number, x: number ,y: number): void
## arc ## arc
arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, anticlockwise?: boolean): void arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, counterclockwise?: boolean): void
绘制弧线路径。 绘制弧线路径。
- 参数 **参数:**
| 参数 | 类型 | 必填 | 默认值 | 描述 |
| ------------- | ------- | ---- | ----- | ---------- | | 参数 | 类型 | 必填 | 默认值 | 描述 |
| x | number | 是 | 0 | 弧线圆心的x坐标值。 | | -------- | -------- | -------- | -------- | -------- |
| y | number | 是 | 0 | 弧线圆心的y坐标值。 | | x | number | 是 | 0 | 弧线圆心的x坐标值。 |
| radius | number | 是 | 0 | 弧线的圆半径。 | | y | number | 是 | 0 | 弧线圆心的y坐标值。 |
| startAngle | number | 是 | 0 | 弧线的起始弧度。 | | radius | number | 是 | 0 | 弧线的圆半径。 |
| endAngle | number | 是 | 0 | 弧线的终止弧度。 | | startAngle | number | 是 | 0 | 弧线的起始弧度。 |
| anticlockwise | boolean | 否 | false | 是否逆时针绘制圆弧。 | | endAngle | number | 是 | 0 | 弧线的终止弧度。 |
| counterclockwise | boolean | 否 | false | 是否逆时针绘制圆弧。 |
- 示例
``` **示例:**
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct Arc { struct Arc {
private settings: RenderingContextSettings = new RenderingContextSettings(true) private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private path2Db: Path2D = new Path2D() private path2Db: Path2D = new Path2D()
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context) Canvas(this.context)
...@@ -316,24 +337,27 @@ arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void ...@@ -316,24 +337,27 @@ arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void
依据圆弧经过的点和圆弧半径创建圆弧路径。 依据圆弧经过的点和圆弧半径创建圆弧路径。
- 参数 **参数:**
| 参数 | 类型 | 必填 | 默认值 | 描述 |
| ------ | ------ | ---- | ---- | --------------- |
| x1 | number | 是 | 0 | 圆弧经过的第一个点的x坐标值。 |
| y1 | number | 是 | 0 | 圆弧经过的第一个点的y坐标值。 |
| x2 | number | 是 | 0 | 圆弧经过的第二个点的x坐标值。 |
| y2 | number | 是 | 0 | 圆弧经过的第二个点的y坐标值。 |
| radius | number | 是 | 0 | 圆弧的圆半径值。 |
- 示例 | 参数 | 类型 | 必填 | 默认值 | 描述 |
``` | -------- | -------- | -------- | -------- | -------- |
| x1 | number | 是 | 0 | 圆弧经过的第一个点的x坐标值。 |
| y1 | number | 是 | 0 | 圆弧经过的第一个点的y坐标值。 |
| x2 | number | 是 | 0 | 圆弧经过的第二个点的x坐标值。 |
| y2 | number | 是 | 0 | 圆弧经过的第二个点的y坐标值。 |
| radius | number | 是 | 0 | 圆弧的圆半径值。 |
**示例:**
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct ArcTo { struct ArcTo {
private settings: RenderingContextSettings = new RenderingContextSettings(true) private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private path2Db: Path2D = new Path2D() private path2Db: Path2D = new Path2D()
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context) Canvas(this.context)
...@@ -356,31 +380,34 @@ arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void ...@@ -356,31 +380,34 @@ arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void
## ellipse ## ellipse
ellipse(x: number, y: number, radiusX: number, radiusY: number, rotation: number, startAngle: number, endAngle: number, anticlockwise?: number): void ellipse(x: number, y: number, radiusX: number, radiusY: number, rotation: number, startAngle: number, endAngle: number, counterclockwise?: number): void
在规定的矩形区域绘制一个椭圆。 在规定的矩形区域绘制一个椭圆。
- 参数 **参数:**
| 参数 | 类型 | 必填 | 默认值 | 描述 |
| ------------- | ------ | ---- | ---- | ------------------------------------ | | 参数 | 类型 | 必填 | 默认值 | 描述 |
| x | number | 是 | 0 | 椭圆圆心的x轴坐标。 | | -------- | -------- | -------- | -------- | -------- |
| y | number | 是 | 0 | 椭圆圆心的y轴坐标。 | | x | number | 是 | 0 | 椭圆圆心的x轴坐标。 |
| radiusX | number | 是 | 0 | 椭圆x轴的半径长度。 | | y | number | 是 | 0 | 椭圆圆心的y轴坐标。 |
| radiusY | number | 是 | 0 | 椭圆y轴的半径长度。 | | radiusX | number | 是 | 0 | 椭圆x轴的半径长度。 |
| rotation | number | 是 | 0 | 椭圆的旋转角度,单位为弧度。 | | radiusY | number | 是 | 0 | 椭圆y轴的半径长度。 |
| startAngle | number | 是 | 0 | 椭圆绘制的起始点角度,以弧度表示。 | | rotation | number | 是 | 0 | 椭圆的旋转角度,单位为弧度。 |
| endAngle | number | 是 | 0 | 椭圆绘制的结束点角度,以弧度表示。 | | startAngle | number | 是 | 0 | 椭圆绘制的起始点角度,以弧度表示。 |
| anticlockwise | number | 否 | 0 | 是否以逆时针方向绘制椭圆,0为顺时针,1为逆时针。(可选参数,默认为0) | | endAngle | number | 是 | 0 | 椭圆绘制的结束点角度,以弧度表示。 |
| counterclockwise | number | 否 | 0 | 是否以逆时针方向绘制椭圆,0为顺时针,1为逆时针。(可选参数,默认为0) |
- 示例
``` **示例:**
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct CanvasExample { struct CanvasExample {
private settings: RenderingContextSettings = new RenderingContextSettings(true) private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private path2Db: Path2D = new Path2D() private path2Db: Path2D = new Path2D()
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context) Canvas(this.context)
...@@ -403,27 +430,30 @@ ellipse(x: number, y: number, radiusX: number, radiusY: number, rotation: number ...@@ -403,27 +430,30 @@ ellipse(x: number, y: number, radiusX: number, radiusY: number, rotation: number
## rect ## rect
rect(x: number, y: number, width: number, height: number): void rect(x: number, y: number, w: number, h: number): void
创建矩形路径。 创建矩形路径。
- 参数 **参数:**
| 参数 | 类型 | 必填 | 默认值 | 描述 |
| ------ | ------ | ---- | ---- | ------------- |
| x | number | 是 | 0 | 指定矩形的左上角x坐标值。 |
| y | number | 是 | 0 | 指定矩形的左上角y坐标值。 |
| width | number | 是 | 0 | 指定矩形的宽度。 |
| height | number | 是 | 0 | 指定矩形的高度。 |
- 示例 | 参数 | 类型 | 必填 | 默认值 | 描述 |
``` | -------- | -------- | -------- | -------- | -------- |
| x | number | 是 | 0 | 指定矩形的左上角x坐标值。 |
| y | number | 是 | 0 | 指定矩形的左上角y坐标值。 |
| w | number | 是 | 0 | 指定矩形的宽度。 |
| h | number | 是 | 0 | 指定矩形的高度。 |
**示例:**
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct CanvasExample { struct CanvasExample {
private settings: RenderingContextSettings = new RenderingContextSettings(true) private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private path2Db: Path2D = new Path2D() private path2Db: Path2D = new Path2D()
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context) Canvas(this.context)
......
...@@ -7,11 +7,6 @@ ...@@ -7,11 +7,6 @@
> 该组件从API Version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 > 该组件从API Version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
## 权限列表
## 子组件 ## 子组件
支持单个子组件。 支持单个子组件。
...@@ -28,7 +23,7 @@ TabContent() ...@@ -28,7 +23,7 @@ TabContent()
| 名称 | 参数类型 | 默认值 | 描述 | | 名称 | 参数类型 | 默认值 | 描述 |
| ------ | ------------------------------------------------------------ | ------ | ------------------------------------------------------------ | | ------ | ------------------------------------------------------------ | ------ | ------------------------------------------------------------ |
| tabBar | string&nbsp;\|&nbsp;[Resource](ts-types.md#resource)&nbsp;\|&nbsp;{<br/>icon?:&nbsp;string&nbsp;\|&nbsp;[Resource](ts-types.md#resource),<br/>text?:&nbsp;string&nbsp;\|&nbsp;[Resource](ts-types.md#resource)<br/>}<br/>\|&nbsp;[CustomBuilder](ts-types.md#custombuilder8)<sup>8+</sup> | - | 设置TabBar上显示内容。<br/>CustomBuilder:&nbsp;构造器,内部可以传入组件(API8版本以上适用)。<br/>>&nbsp;&nbsp;**说明:**<br/>>&nbsp;如果icon采用svg格式图源,则要求svg图源删除其自有宽高属性值。如采用带有自有宽高属性的svg图源,icon大小则是svg本身内置的宽高属性值大小。 | | tabBar | string&nbsp;\|&nbsp;[Resource](ts-types.md#resource)&nbsp;\|&nbsp;{<br/>icon?:&nbsp;string&nbsp;\|&nbsp;[Resource](ts-types.md#resource),<br/>text?:&nbsp;string&nbsp;\|&nbsp;[Resource](ts-types.md#resource)<br/>}<br/>\|&nbsp;[CustomBuilder](ts-types.md#custombuilder8)<sup>8+</sup> | - | 设置TabBar上显示内容。<br/>CustomBuilder:&nbsp;构造器,内部可以传入组件(API8版本以上适用)。<br/>**说明:**<br/>如果icon采用svg格式图源,则要求svg图源删除其自有宽高属性值。如采用带有自有宽高属性的svg图源,icon大小则是svg本身内置的宽高属性值大小。 |
> **说明:** > **说明:**
> - TabContent组件不支持设置通用宽度属性,其宽度默认撑满Tabs父组件。 > - TabContent组件不支持设置通用宽度属性,其宽度默认撑满Tabs父组件。
......
...@@ -7,11 +7,6 @@ ...@@ -7,11 +7,6 @@
> 该组件从API Version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 > 该组件从API Version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
## 权限列表
## 子组件 ## 子组件
包含子组件[TabContent](ts-container-tabcontent.md) 包含子组件[TabContent](ts-container-tabcontent.md)
...@@ -19,7 +14,7 @@ ...@@ -19,7 +14,7 @@
## 接口说明 ## 接口说明
Tabs(value: {barPosition?: BarPosition, index?: number, controller?: [TabsController](#tabscontroller)}) Tabs(value?: {barPosition?: BarPosition, index?: number, controller?: [TabsController](#tabscontroller)})
**参数:** **参数:**
......
...@@ -43,7 +43,7 @@ ...@@ -43,7 +43,7 @@
## 响应手势事件 ## 响应手势事件
组件通过gesture方法绑定手势对象,可以通过手势对象提供的事件相应响应手势操作。如通过TapGesture对象的onAction事件响应点击事件。具体事件定义见各个手势对象章节。 组件通过gesture方法绑定手势对象,可以通过手势对象提供的事件相应响应手势操作。例如通过TapGesture对象的onAction事件响应点击事件。其余手势的事件定义见各个手势对象章节。
- TapGesture事件说明 - TapGesture事件说明
| 名称 | 功能描述 | | 名称 | 功能描述 |
...@@ -51,10 +51,36 @@ ...@@ -51,10 +51,36 @@
| onAction((event?:GestureEvent)&nbsp;=&gt;&nbsp;void) | Tap手势识别成功回调。 | | onAction((event?:GestureEvent)&nbsp;=&gt;&nbsp;void) | Tap手势识别成功回调。 |
- GestureEvent对象说明 - GestureEvent对象说明
| 属性名称 | 属性类型 | 描述 | | 名称 | 类型 | 描述 |
| -------- | -------- | -------- | | -------- | -------- | -------- |
| timestamp | number | 事件时间戳。 | | timestamp<sup>8+</sup> | number | 事件时间戳。 |
| target<sup>8+</sup> | [EventTarget](ts-universal-events-click.md) | 触发手势事件的元素对象。 | | target<sup>8+</sup> | [EventTarget](ts-universal-events-click.md) | 触发手势事件的元素对象显示区域。 |
| source<sup>8+</sup> | SourceType | 事件输入设备。 |
| repeat | boolean | 是否为重复触发事件,用于LongPressGesture手势触发场景。 |
| fingerList<sup>8+</sup> | FingerInfo[] | 触发事件的所有手指信息,用于LongPressGesture与TapGesture手势触发场景。 |
| offsetX | number | 手势事件x轴偏移量,单位为vp,用于PanGesture手势触发场景。 |
| offsetY | number | 手势事件y轴偏移量,单位为vp,用于PanGesture手势触发场景。 |
| angle | number | 用于RotationGesture手势触发场景时,表示旋转角度;用于SwipeGesture手势触发场景时,表示滑动手势的角度,即两根手指间的线段与水平方向的夹角变化的度数。<br/>>&nbsp;&nbsp;**说明:**<br/>>&nbsp;角度计算方式:滑动手势被识别到后,连接两根手指之间的线被识别为起始线条,随着手指的滑动,手指之间的线条会发生旋转,根据起始线条两端点和当前线条两端点的坐标,使用反正切函数分别计算其相对于水平方向的夹角,最后arctan2(cy2-cy1,cx2-cx1)-arctan2(y2-y1,x2-x1)为旋转的角度。以起始线条为坐标系,顺时针旋转为0到180度,逆时针旋转为-180到0度。 |
| speed<sup>8+</sup> | number | 滑动手势速度,即所有手指滑动的平均速度,单位为vp/秒,用于SwipeGesture手势触发场景。 |
| scale | number | 缩放比例,用于PinchGesture手势触发场景。 |
| pinchCenterX | number | 捏合手势中心点x轴坐标,单位为vp,用于PinchGesture手势触发场景。 |
| pinchCenterY | number | 捏合手势中心点y轴坐标,单位为vp,用于PinchGesture手势触发场景。 |
- SourceType
| 名称 | 描述 |
| -------- | -------- |
| Unknown | 未知设备。 |
| Mouse | 鼠标。 |
| TouchScreen | 触摸屏。 |
- FingerInfo对象说明
| 名称 | 类型 | 描述 |
| -------- | -------- | -------- |
| id | number | 手指的索引编号。 |
| globalX | number | 相对于设备屏幕左上角的x轴坐标。 |
| globalY | number | 相对于设备屏幕左上角的y轴坐标。 |
| localX | number | 相对于当前组件元素左上角的x轴坐标。 |
| localY | number | 相对于当前组件元素左上角的y轴坐标。 |
## 示例 ## 示例
......
# Video # Video
视频播放组件。
> **说明:** > **说明:**
>
> 该组件从API Version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 > 该组件从API Version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
视频播放组件。
## 需要权限 ## 需要权限
使用网络视频时,需要申请权限ohos.permission.INTERNET。具体申请方式请参考[权限申请声明](../../security/accesstoken-guidelines.md) 使用网络视频时,需要申请权限ohos.permission.INTERNET。具体申请方式请参考[权限申请声明](../../security/accesstoken-guidelines.md)
...@@ -16,7 +17,7 @@ ...@@ -16,7 +17,7 @@
## 接口 ## 接口
Video(value: {src?: string | Resource, currentProgressRate?: number | string | PlaybackSpeed, previewUri?: string | PixelMap | Resource, controller?: VideoController}) Video(value: {src?: string | Resource, currentProgressRate?: number | string | PlaybackSpeed, previewUri?: string | PixelMap | Resource, controller?: VideoController})
**参数:** **参数:**
...@@ -51,16 +52,16 @@ ...@@ -51,16 +52,16 @@
## 事件 ## 事件
| 名称 | 功能描述 | | 名称 | 功能描述 |
| ---------------------------------------- | ---------------------------------------- | | ------------------------------------------------------------ | ------------------------------------------------------------ |
| onStart(event:()&nbsp;=&gt;&nbsp;void) | 播放时触发该事件。 | | onStart(event:()&nbsp;=&gt;&nbsp;void) | 播放时触发该事件。 |
| onPause(event:()&nbsp;=&gt;&nbsp;void) | 暂停时触发该事件。 | | onPause(event:()&nbsp;=&gt;&nbsp;void) | 暂停时触发该事件。 |
| onFinish(event:()&nbsp;=&gt;&nbsp;void) | 播放结束时触发该事件。 | | onFinish(event:()&nbsp;=&gt;&nbsp;void) | 播放结束时触发该事件。 |
| onError(event:()&nbsp;=&gt;&nbsp;void) | 播放失败时触发该事件。 | | onError(event:()&nbsp;=&gt;&nbsp;void) | 播放失败时触发该事件。 |
| onPrepared(callBack:(event?:&nbsp;{&nbsp;duration:&nbsp;number&nbsp;})&nbsp;=&gt;&nbsp;void) | 视频准备完成时触发该事件,通过duration可以获取视频时长,单位为s。<br/>- duration: 视频的时长。 | | onPrepared(callback:(event?:&nbsp;{&nbsp;duration:&nbsp;number&nbsp;})&nbsp;=&gt;&nbsp;void) | 视频准备完成时触发该事件,通过duration可以获取视频时长,单位为s。<br/>- duration: 视频的时长。 |
| onSeeking(callBack:(event?:&nbsp;{&nbsp;time:&nbsp;number&nbsp;})&nbsp;=&gt;&nbsp;void) | 操作进度条过程时上报时间信息,单位为s。 | | onSeeking(callback:(event?:&nbsp;{&nbsp;time:&nbsp;number&nbsp;})&nbsp;=&gt;&nbsp;void) | 操作进度条过程时上报时间信息,单位为s。 |
| onSeeked(callBack:(event?:&nbsp;{&nbsp;time:&nbsp;number&nbsp;})&nbsp;=&gt;&nbsp;void) | 操作进度条完成后,上报播放时间信息,单位为s。 | | onSeeked(callback:(event?:&nbsp;{&nbsp;time:&nbsp;number&nbsp;})&nbsp;=&gt;&nbsp;void) | 操作进度条完成后,上报播放时间信息,单位为s。 |
| onUpdate(callBack:(event?:&nbsp;{&nbsp;time:&nbsp;number&nbsp;})&nbsp;=&gt;&nbsp;void) | 播放进度变化时触发该事件,单位为s,更新时间间隔为250ms。 | | onUpdate(callback:(event?:&nbsp;{&nbsp;time:&nbsp;number&nbsp;})&nbsp;=&gt;&nbsp;void) | 播放进度变化时触发该事件,单位为s,更新时间间隔为250ms。 |
## VideoController ## VideoController
......
...@@ -21,7 +21,7 @@ show(options: TextPickerDialogOptions) ...@@ -21,7 +21,7 @@ show(options: TextPickerDialogOptions)
| range | string[] | 是 | - | 选择器的数据选择范围。 | | range | string[] | 是 | - | 选择器的数据选择范围。 |
| selected | number | 否 | 0 | 选中项在数组中的index值。 | | selected | number | 否 | 0 | 选中项在数组中的index值。 |
| value | string | 否 | 第一个元素值 | 选中项的值,优先级低于selected。 | | value | string | 否 | 第一个元素值 | 选中项的值,优先级低于selected。 |
| defaultPickerItemHeight | number | 否 | - | 默认Picker内容项元素高度。 | | defaultPickerItemHeight | number \| string | 否 | - | 默认Picker内容项元素高度。 |
| onAccept | (value: TextPickerResult) => void | 否 | - | 点击弹窗中确定按钮时触发。 | | onAccept | (value: TextPickerResult) => void | 否 | - | 点击弹窗中确定按钮时触发。 |
| onCancel | () => void | 否 | - | 点击弹窗中取消按钮时触发。 | | onCancel | () => void | 否 | - | 点击弹窗中取消按钮时触发。 |
| onChange | (value: TextPickerResult) => void | 否 | - | 滑动选择器,当前选择项改变时触发。 | | onChange | (value: TextPickerResult) => void | 否 | - | 滑动选择器,当前选择项改变时触发。 |
......
...@@ -11,39 +11,40 @@ ...@@ -11,39 +11,40 @@
OffscreenCanvasRenderingContext2D(width: number, height: number, setting: RenderingContextSettings) OffscreenCanvasRenderingContext2D(width: number, height: number, setting: RenderingContextSettings)
- 参数 **参数:**
| 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 |
| ------- | ---------------------------------------- | ---- | ---- | ------------------------------ |
| width | number | 是 | - | 离屏画布的宽度 |
| height | number | 是 | - | 离屏画布的高度 |
| setting | [RenderingContextSettings](ts-canvasrenderingcontext2d.md#renderingcontextsettings) | 是 | - | 见RenderingContextSettings接口描述。 |
| 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 |
| ------- | ---------------------------------------- | ---- | ---- | ------------------------------ |
| width | number | 是 | - | 离屏画布的宽度 |
| height | number | 是 | - | 离屏画布的高度 |
| setting | [RenderingContextSettings](ts-canvasrenderingcontext2d.md#renderingcontextsettings) | 是 | - | 见RenderingContextSettings接口描述。 |
## 属性
| 名称 | 类型 | 默认值 | 描述 | ## 属性
| ---------------------------------------- | ---------------------------------------- | ---------------------------------------- | ---------------------------------------- |
| [fillStyle](#fillstyle) | &lt;color&gt;&nbsp;\|&nbsp;[CanvasGradient](ts-components-canvas-canvasgradient.md)&nbsp;\|&nbsp;[CanvasPattern](#canvaspattern) | - | 指定绘制的填充色。<br/>-&nbsp;类型为&lt;color&gt;时,表示设置填充区域的颜色。<br/>-&nbsp;类型为CanvasGradient时,表示渐变对象,使用&nbsp;[createLinearGradient](#createlineargradient)方法创建。<br/>-&nbsp;类型为CanvasPattern时,使用[createPattern](#createpattern)方法创建。 |
| [lineWidth](#linewidth) | number | - | 设置绘制线条的宽度。 |
| [strokeStyle](#strokestyle) | &lt;color&gt;&nbsp;\|&nbsp;[CanvasGradient](ts-components-canvas-canvasgradient.md)&nbsp;\|&nbsp;[CanvasPattern](#canvaspattern) | - | 设置描边的颜色。<br/>-&nbsp;类型为&lt;color&gt;时,表示设置描边使用的颜色。<br/>-&nbsp;类型为CanvasGradient时,表示渐变对象,使用[createLinearGradient](#createlineargradient)方法创建。<br/>-&nbsp;类型为CanvasPattern时,使用[createPattern](#createpattern)方法创建。 |
| [lineCap](#linecap) | string | 'butt' | 指定线端点的样式,可选值为:<br/>-&nbsp;'butt':线端点以方形结束。<br/>-&nbsp;'round':线端点以圆形结束。<br/>-&nbsp;'square':线端点以方形结束,该样式下会增加一个长度和线段厚度相同,宽度是线段厚度一半的矩形。 |
| [lineJoin](#linejoin) | string | 'miter' | 指定线段间相交的交点样式,可选值为:<br/>-&nbsp;'round':在线段相连处绘制一个扇形,扇形的圆角半径是线段的宽度。<br/>-&nbsp;'bevel':在线段相连处使用三角形为底填充,&nbsp;每个部分矩形拐角独立。<br/>-&nbsp;'miter':在相连部分的外边缘处进行延伸,使其相交于一点,形成一个菱形区域,该属性可以通过设置miterLimit属性展现效果。 |
| [miterLimit](#miterlimit) | number | 10 | 设置斜接面限制值,该值指定了线条相交处内角和外角的距离。 |
| [font](#font) | string | 'normal&nbsp;normal&nbsp;14px&nbsp;sans-serif' | 设置文本绘制中的字体样式。<br/>语法:ctx.font='font-size&nbsp;font-family'<br/>-&nbsp;font-size(可选),指定字号和行高,单位只支持px。<br/>-&nbsp;font-family(可选),指定字体系列。<br/>语法:ctx.font='font-style&nbsp;font-weight&nbsp;font-size&nbsp;font-family'<br/>-&nbsp;font-style(可选),用于指定字体样式,支持如下几种样式:'normal',&nbsp;'italic'。<br/>-&nbsp;font-weight(可选),用于指定字体的粗细,支持如下几种类型:'normal',&nbsp;'bold',&nbsp;'bolder',&nbsp;'lighter',&nbsp;100,&nbsp;200,&nbsp;300,&nbsp;400,&nbsp;500,&nbsp;600,&nbsp;700,&nbsp;800,&nbsp;900。<br/>-&nbsp;font-size(可选),指定字号和行高,单位只支持px。<br/>-&nbsp;font-family(可选),指定字体系列,支持如下几种类型:'sans-serif',&nbsp;'serif',&nbsp;'monospace'。 |
| [textAlign](#textalign) | string | 'left' | 设置文本绘制中的文本对齐方式,可选值为:<br/>-&nbsp;'left':文本左对齐。<br/>-&nbsp;'right':文本右对齐。<br/>-&nbsp;'center':文本居中对齐。<br/>-&nbsp;'start':文本对齐界线开始的地方。<br/>-&nbsp;'end':文本对齐界线结束的地方。<br/>>&nbsp;&nbsp;**说明:**<br/>>&nbsp;ltr布局模式下start和left一致,rtl布局模式下start和right一致·。 |
| [textBaseline](#textbaseline) | string | 'alphabetic' | 设置文本绘制中的水平对齐方式,可选值为:<br/>-&nbsp;'alphabetic':文本基线是标准的字母基线。<br/>-&nbsp;'top':文本基线在文本块的顶部。<br/>-&nbsp;'hanging':文本基线是悬挂基线。<br/>-&nbsp;'middle':文本基线在文本块的中间。<br/>-&nbsp;'ideographic':文字基线是表意字基线;如果字符本身超出了alphabetic基线,那么ideograhpic基线位置在字符本身的底部。<br/>-&nbsp;'bottom':文本基线在文本块的底部。&nbsp;与ideographic基线的区别在于ideographic&nbsp;基线不需要考虑下行字母。 |
| [globalAlpha](#globalalpha) | number | - | 设置透明度,0.0为完全透明,1.0为完全不透明。 |
| [lineDashOffset](#linedashoffset) | number | 0.0 | 设置画布的虚线偏移量,精度为float。 |
| [globalCompositeOperation](#globalcompositeoperation) | string | 'source-over' | 设置合成操作的方式。类型字段可选值有'source-over','source-atop','source-in','source-out','destination-over','destination-atop','destination-in','destination-out','lighter','copy','xor'。 |
| [shadowBlur](#shadowblur) | number | 0.0 | 设置绘制阴影时的模糊级别,值越大越模糊,精度为float。 |
| [shadowColor](#shadowcolor) | &lt;color&gt; | - | 设置绘制阴影时的阴影颜色。 |
| [shadowOffsetX](#shadowoffsetx) | number | - | 设置绘制阴影时和原有对象的水平偏移值。 |
| [shadowOffsetY](#shadowoffsety) | number | - | 设置绘制阴影时和原有对象的垂直偏移值。 |
| [imageSmoothingEnabled](#imagesmoothingenabled) | boolean | true | 用于设置绘制图片时是否进行图像平滑度调整,true为启用,false为不启用。 |
| imageSmoothingQuality | string | 'low' | 用于设置图像平滑度,支持如下三种类型:'low',&nbsp;'medium',&nbsp;'high'。 |
> **说明:** | 名称 | 类型 | 描述 |
> &lt;color&gt;类型格式为 'rgb(255, 255, 255)','rgba(255, 255, 255, 1.0)','\#FFFFFF'。 | ---------------------------------------- | ---------------------------------------- | ---------------------------------------- |
| [fillStyle](#fillstyle) | string&nbsp;\|&nbsp;[CanvasGradient](ts-components-canvas-canvasgradient.md)&nbsp;\|&nbsp;[CanvasPattern](#canvaspattern) | 指定绘制的填充色。<br/>-&nbsp;类型为string时,表示设置填充区域的颜色。<br/>-&nbsp;类型为CanvasGradient时,表示渐变对象,使用[createLinearGradient](#createlineargradient)方法创建。<br/>-&nbsp;类型为CanvasPattern时,使用[createPattern](#createpattern)方法创建。 |
| [lineWidth](#linewidth) | number | 设置绘制线条的宽度。 |
| [strokeStyle](#strokestyle) | string&nbsp;\|&nbsp;[CanvasGradient](ts-components-canvas-canvasgradient.md)&nbsp;\|&nbsp;[CanvasPattern](#canvaspattern) | 设置描边的颜色。<br/>-&nbsp;类型为string时,表示设置描边使用的颜色。<br/>-&nbsp;类型为CanvasGradient时,表示渐变对象,使用[createLinearGradient](#createlineargradient)方法创建。<br/>-&nbsp;类型为CanvasPattern时,使用[createPattern](#createpattern)方法创建。 |
| [lineCap](#linecap) | CanvasLineCap | 指定线端点的样式,可选值为:<br/>-&nbsp;'butt':线端点以方形结束。<br/>-&nbsp;'round':线端点以圆形结束。<br/>-&nbsp;'square':线端点以方形结束,该样式下会增加一个长度和线段厚度相同,宽度是线段厚度一半的矩形。<br/>-&nbsp;默认值:'butt'。 |
| [lineJoin](#linejoin) | CanvasLineJoin | 指定线段间相交的交点样式,可选值为:<br/>-&nbsp;'round':在线段相连处绘制一个扇形,扇形的圆角半径是线段的宽度。<br/>-&nbsp;'bevel':在线段相连处使用三角形为底填充,&nbsp;每个部分矩形拐角独立。<br/>-&nbsp;'miter':在相连部分的外边缘处进行延伸,使其相交于一点,形成一个菱形区域,该属性可以通过设置miterLimit属性展现效果。<br/>-&nbsp;默认值:'miter'。 |
| [miterLimit](#miterlimit) | number | 设置斜接面限制值,该值指定了线条相交处内角和外角的距离。 <br/>-&nbsp;默认值:10。 |
| [font](#font) | string | 设置文本绘制中的字体样式。<br/>语法:ctx.font='font-size&nbsp;font-family'<br/>-&nbsp;font-size(可选),指定字号和行高,单位只支持px。<br/>-&nbsp;font-family(可选),指定字体系列。<br/>语法:ctx.font='font-style&nbsp;font-weight&nbsp;font-size&nbsp;font-family'<br/>-&nbsp;font-style(可选),用于指定字体样式,支持如下几种样式:'normal','italic'。<br/>-&nbsp;font-weight(可选),用于指定字体的粗细,支持如下几种类型:'normal',&nbsp;'bold',&nbsp;'bolder',&nbsp;'lighter',&nbsp;100,&nbsp;200,&nbsp;300,&nbsp;400,&nbsp;500,&nbsp;600,&nbsp;700,&nbsp;800,&nbsp;900。<br/>-&nbsp;font-size(可选),指定字号和行高,单位只支持px。<br/>-&nbsp;font-family(可选),指定字体系列,支持如下几种类型:'sans-serif',&nbsp;'serif',&nbsp;'monospace'。<br/>-&nbsp;默认值:'normal normal 14px sans-serif'。 |
| [textAlign](#textalign) | CanvasTextAlign | 设置文本绘制中的文本对齐方式,可选值为:<br/>-&nbsp;'left':文本左对齐。<br/>-&nbsp;'right':文本右对齐。<br/>-&nbsp;'center':文本居中对齐。<br/>-&nbsp;'start':文本对齐界线开始的地方。<br/>-&nbsp;'end':文本对齐界线结束的地方。<br/>>&nbsp;![icon-note.gif](public_sys-resources/icon-note.gif)&nbsp;**说明:**<br/>>&nbsp;ltr布局模式下'start'和'left'一致,rtl布局模式下'start'和'right'一致·。<br/>-&nbsp;默认值:'left'。 |
| [textBaseline](#textbaseline) | CanvasTextBaseline | 设置文本绘制中的水平对齐方式,可选值为:<br/>-&nbsp;'alphabetic':文本基线是标准的字母基线。<br/>-&nbsp;'top':文本基线在文本块的顶部。<br/>-&nbsp;'hanging':文本基线是悬挂基线。<br/>-&nbsp;'middle':文本基线在文本块的中间。<br/>-&nbsp;'ideographic':文字基线是表意字基线;如果字符本身超出了alphabetic基线,那么ideograhpic基线位置在字符本身的底部。<br/>-&nbsp;'bottom':文本基线在文本块的底部。&nbsp;与ideographic基线的区别在于ideographic基线不需要考虑下行字母。<br/>-&nbsp;默认值:'alphabetic'。 |
| [globalAlpha](#globalalpha) | number | 设置透明度,0.0为完全透明,1.0为完全不透明。 |
| [lineDashOffset](#linedashoffset) | number | 设置画布的虚线偏移量,精度为float。 <br/>-&nbsp;默认值:0.0。 |
| [globalCompositeOperation](#globalcompositeoperation) | string | 设置合成操作的方式。类型字段可选值有'source-over','source-atop','source-in','source-out','destination-over','destination-atop','destination-in','destination-out','lighter','copy','xor'。<br/>-&nbsp;默认值:'source-over'。 |
| [shadowBlur](#shadowblur) | number | 设置绘制阴影时的模糊级别,值越大越模糊,精度为float。 <br/>-&nbsp;默认值:0.0。 |
| [shadowColor](#shadowcolor) | string | 设置绘制阴影时的阴影颜色。 |
| [shadowOffsetX](#shadowoffsetx) | number | 设置绘制阴影时和原有对象的水平偏移值。 |
| [shadowOffsetY](#shadowoffsety) | number | 设置绘制阴影时和原有对象的垂直偏移值。 |
| [imageSmoothingEnabled](#imagesmoothingenabled) | boolean | 用于设置绘制图片时是否进行图像平滑度调整,true为启用,false为不启用。 <br/>-&nbsp;默认值:true。 |
| imageSmoothingQuality | string | 用于设置图像平滑度,支持如下三种类型:'low',&nbsp;'medium',&nbsp;'high'。<br/>-&nbsp;默认值:'low'。 |
> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
>fillStyle、shadowColor与 strokeStyle 中string类型格式为 'rgb(255, 255, 255)','rgba(255, 255, 255, 1.0)','\#FFFFFF'。
### fillStyle ### fillStyle
...@@ -143,7 +144,6 @@ struct StrokeStyleExample { ...@@ -143,7 +144,6 @@ struct StrokeStyleExample {
} }
``` ```
![zh-cn_image_0000001238712437](figures/zh-cn_image_0000001238712437.png) ![zh-cn_image_0000001238712437](figures/zh-cn_image_0000001238712437.png)
...@@ -445,6 +445,7 @@ struct LineDashOffset { ...@@ -445,6 +445,7 @@ struct LineDashOffset {
.onReady(() =>{ .onReady(() =>{
this.offContext.arc(100, 75, 50, 0, 6.28) this.offContext.arc(100, 75, 50, 0, 6.28)
this.offContext.setLineDash([10,20]) this.offContext.setLineDash([10,20])
this.offContext.lineDashOffset = 10.0;
this.offContext.stroke(); this.offContext.stroke();
var image = this.offContext.transferToImageBitmap() var image = this.offContext.transferToImageBitmap()
this.context.transferFromImageBitmap(image) this.context.transferFromImageBitmap(image)
...@@ -454,8 +455,8 @@ struct LineDashOffset { ...@@ -454,8 +455,8 @@ struct LineDashOffset {
.height('100%') .height('100%')
} }
} }
```
```
![zh-cn_image_0000001238712439](figures/zh-cn_image_0000001238712439.png) ![zh-cn_image_0000001238712439](figures/zh-cn_image_0000001238712439.png)
...@@ -700,7 +701,8 @@ fillRect(x: number, y: number, w: number, h: number): void ...@@ -700,7 +701,8 @@ fillRect(x: number, y: number, w: number, h: number): void
填充一个矩形。 填充一个矩形。
- 参数 **参数:**
| 参数 | 类型 | 必填 | 默认值 | 说明 | | 参数 | 类型 | 必填 | 默认值 | 说明 |
| ------ | ------ | ---- | ---- | ------------- | | ------ | ------ | ---- | ---- | ------------- |
| x | number | 是 | 0 | 指定矩形左上角点的x坐标。 | | x | number | 是 | 0 | 指定矩形左上角点的x坐标。 |
...@@ -708,8 +710,10 @@ fillRect(x: number, y: number, w: number, h: number): void ...@@ -708,8 +710,10 @@ fillRect(x: number, y: number, w: number, h: number): void
| width | number | 是 | 0 | 指定矩形的宽度。 | | width | number | 是 | 0 | 指定矩形的宽度。 |
| height | number | 是 | 0 | 指定矩形的高度。 | | height | number | 是 | 0 | 指定矩形的高度。 |
- 示例 **示例:**
```
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct FillRect { struct FillRect {
...@@ -744,7 +748,8 @@ strokeRect(x: number, y: number, w: number, h: number): void ...@@ -744,7 +748,8 @@ strokeRect(x: number, y: number, w: number, h: number): void
绘制具有边框的矩形,矩形内部不填充。 绘制具有边框的矩形,矩形内部不填充。
- 参数 **参数:**
| 参数 | 类型 | 必填 | 默认值 | 说明 | | 参数 | 类型 | 必填 | 默认值 | 说明 |
| ------ | ------ | ---- | ---- | ------------ | | ------ | ------ | ---- | ---- | ------------ |
| x | number | 是 | 0 | 指定矩形的左上角x坐标。 | | x | number | 是 | 0 | 指定矩形的左上角x坐标。 |
...@@ -752,8 +757,10 @@ strokeRect(x: number, y: number, w: number, h: number): void ...@@ -752,8 +757,10 @@ strokeRect(x: number, y: number, w: number, h: number): void
| width | number | 是 | 0 | 指定矩形的宽度。 | | width | number | 是 | 0 | 指定矩形的宽度。 |
| height | number | 是 | 0 | 指定矩形的高度。 | | height | number | 是 | 0 | 指定矩形的高度。 |
- 示例 **示例:**
```
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct StrokeRect { struct StrokeRect {
...@@ -787,7 +794,8 @@ clearRect(x: number, y: number, w: number, h: number): void ...@@ -787,7 +794,8 @@ clearRect(x: number, y: number, w: number, h: number): void
删除指定区域内的绘制内容。 删除指定区域内的绘制内容。
- 参数 **参数:**
| 参数 | 类型 | 必填 | 默认值 | 描述 | | 参数 | 类型 | 必填 | 默认值 | 描述 |
| ------ | ------ | ---- | ---- | ------------- | | ------ | ------ | ---- | ---- | ------------- |
| x | number | 是 | 0 | 指定矩形上的左上角x坐标。 | | x | number | 是 | 0 | 指定矩形上的左上角x坐标。 |
...@@ -795,8 +803,10 @@ clearRect(x: number, y: number, w: number, h: number): void ...@@ -795,8 +803,10 @@ clearRect(x: number, y: number, w: number, h: number): void
| width | number | 是 | 0 | 指定矩形的宽度。 | | width | number | 是 | 0 | 指定矩形的宽度。 |
| height | number | 是 | 0 | 指定矩形的高度。 | | height | number | 是 | 0 | 指定矩形的高度。 |
- 示例 **示例:**
```
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct ClearRect { struct ClearRect {
...@@ -828,19 +838,23 @@ clearRect(x: number, y: number, w: number, h: number): void ...@@ -828,19 +838,23 @@ clearRect(x: number, y: number, w: number, h: number): void
### fillText ### fillText
fillText(text: string, x: number, y: number): void fillText(text: string, x: number, y: number, maxWidth?: number): void
绘制填充类文本。 绘制填充类文本。
- 参数 **参数:**
| 参数 | 类型 | 必填 | 默认值 | 说明 | | 参数 | 类型 | 必填 | 默认值 | 说明 |
| ---- | ------ | ---- | ---- | --------------- | | ---- | ------ | ---- | ---- | --------------- |
| text | string | 是 | “” | 需要绘制的文本内容。 | | text | string | 是 | “” | 需要绘制的文本内容。 |
| x | number | 是 | 0 | 需要绘制的文本的左下角x坐标。 | | x | number | 是 | 0 | 需要绘制的文本的左下角x坐标。 |
| y | number | 是 | 0 | 需要绘制的文本的左下角y坐标。 | | y | number | 是 | 0 | 需要绘制的文本的左下角y坐标。 |
| maxWidth | number | 否 | - | 指定文本允许的最大宽度。 |
- 示例 **示例:**
```
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct FillText { struct FillText {
...@@ -875,15 +889,19 @@ strokeText(text: string, x: number, y: number): void ...@@ -875,15 +889,19 @@ strokeText(text: string, x: number, y: number): void
绘制描边类文本。 绘制描边类文本。
- 参数 **参数:**
| 参数 | 类型 | 必填 | 默认值 | 描述 | | 参数 | 类型 | 必填 | 默认值 | 描述 |
| ---- | ------ | ---- | ---- | --------------- | | ---- | ------ | ---- | ---- | --------------- |
| text | string | 是 | “” | 需要绘制的文本内容。 | | text | string | 是 | “” | 需要绘制的文本内容。 |
| x | number | 是 | 0 | 需要绘制的文本的左下角x坐标。 | | x | number | 是 | 0 | 需要绘制的文本的左下角x坐标。 |
| y | number | 是 | 0 | 需要绘制的文本的左下角y坐标。 | | y | number | 是 | 0 | 需要绘制的文本的左下角y坐标。 |
| maxWidth | number | 否 | - | 需要绘制的文本的最大宽度 。|
- 示例 **示例:**
```
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct StrokeText { struct StrokeText {
...@@ -918,23 +936,40 @@ measureText(text: string): TextMetrics ...@@ -918,23 +936,40 @@ measureText(text: string): TextMetrics
该方法返回一个文本测算的对象,通过该对象可以获取指定文本的宽度值。 该方法返回一个文本测算的对象,通过该对象可以获取指定文本的宽度值。
- 参数 **参数:**
| 参数 | 类型 | 必填 | 默认值 | 说明 | | 参数 | 类型 | 必填 | 默认值 | 说明 |
| ---- | ------ | ---- | ---- | ---------- | | ---- | ------ | ---- | ---- | ---------- |
| text | string | 是 | "" | 需要进行测量的文本。 | | text | string | 是 | "" | 需要进行测量的文本。 |
- 返回值 **返回值:**
| 类型 | 说明 | | 类型 | 说明 |
| ----------- | ------- | | ----------- | ------- |
| TextMetrics | 文本的尺寸信息 | | TextMetrics | 文本的尺寸信息 |
- TextMetrics类型描述 **TextMetrics类型描述:**
| 属性 | 类型 | 描述 |
| ----- | ------ | ------- | | 属性 | 类型 | 描述 |
| width | number | 字符串的宽度。 | | ----- | ------ | ------- |
| width | number | 字符串的宽度。 |
- 示例 | height | number | 字符串的高度。 |
``` | actualBoundingBoxAscent | number | 从CanvasRenderingContext2D.textBaseline 属性标明的水平线到渲染文本的矩形边界顶部的距离,当前值为0。 |
| actualBoundingBoxDescent | number | 从CanvasRenderingContext2D.textBaseline 属性标明的水平线到渲染文本的矩形边界底部的距离,当前值为0。 |
| actualBoundingBoxLeft | number | 平行于基线,从CanvasRenderingContext2D.textAlign 属性确定的对齐点到文本矩形边界左侧的距离,当前值为0。 |
| actualBoundingBoxRight | number | 平行于基线,从CanvasRenderingContext2D.textAlign 属性确定的对齐点到文本矩形边界右侧的距离,当前值为0。|
| alphabeticBaseline | number | 从CanvasRenderingContext2D.textBaseline 属性标明的水平线到线框的 alphabetic 基线的距离,当前值为0。|
| emHeightAscent | number | 从CanvasRenderingContext2D.textBaseline 属性标明的水平线到线框中 em 方块顶部的距离,当前值为0。|
| emHeightDescent | number | 从CanvasRenderingContext2D.textBaseline 属性标明的水平线到线框中 em 方块底部的距离,当前值为0。|
| fontBoundingBoxAscent | number | 从CanvasRenderingContext2D.textBaseline 属性标明的水平线到渲染文本的所有字体的矩形最高边界顶部的距离,当前值为0。|
| fontBoundingBoxDescent | number | 从CanvasRenderingContext2D.textBaseline 属性标明的水平线到渲染文本的所有字体的矩形边界最底部的距离,当前值为0。|
| hangingBaseline | number | 从CanvasRenderingContext2D.textBaseline 属性标明的水平线到线框的 hanging 基线的距离,当前值为0。|
| ideographicBaseline | number | 从CanvasRenderingContext2D.textBaseline 属性标明的水平线到线框的 ideographic 基线的距离,当前值为0。|
**示例:**
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct MeasureText { struct MeasureText {
...@@ -970,13 +1005,16 @@ stroke(path?: Path2D): void ...@@ -970,13 +1005,16 @@ stroke(path?: Path2D): void
进行边框绘制操作。 进行边框绘制操作。
- 参数 **参数:**
| 参数 | 类型 | 必填 | 默认值 | 描述 | | 参数 | 类型 | 必填 | 默认值 | 描述 |
| ---- | ---------------------------------------- | ---- | ---- | ------------ | | ---- | ---------------------------------------- | ---- | ---- | ------------ |
| path | [Path2D](ts-components-canvas-path2d.md) | 否 | null | 需要绘制的Path2D。 | | path | [Path2D](ts-components-canvas-path2d.md) | 否 | null | 需要绘制的Path2D。 |
- 示例 **示例:**
```
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct Stroke { struct Stroke {
...@@ -1013,8 +1051,10 @@ beginPath(): void ...@@ -1013,8 +1051,10 @@ beginPath(): void
创建一个新的绘制路径。 创建一个新的绘制路径。
- 示例 **示例:**
```
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct BeginPath { struct BeginPath {
...@@ -1053,14 +1093,17 @@ moveTo(x: number, y: number): void ...@@ -1053,14 +1093,17 @@ moveTo(x: number, y: number): void
路径从当前点移动到指定点。 路径从当前点移动到指定点。
- 参数 **参数:**
| 参数 | 类型 | 必填 | 默认值 | 说明 | | 参数 | 类型 | 必填 | 默认值 | 说明 |
| ---- | ------ | ---- | ---- | --------- | | ---- | ------ | ---- | ---- | --------- |
| x | number | 是 | 0 | 指定位置的x坐标。 | | x | number | 是 | 0 | 指定位置的x坐标。 |
| y | number | 是 | 0 | 指定位置的y坐标。 | | y | number | 是 | 0 | 指定位置的y坐标。 |
- 示例 **示例:**
```
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct MoveTo { struct MoveTo {
...@@ -1097,14 +1140,17 @@ lineTo(x: number, y: number): void ...@@ -1097,14 +1140,17 @@ lineTo(x: number, y: number): void
从当前点到指定点进行路径连接。 从当前点到指定点进行路径连接。
- 参数 **参数:**
| 参数 | 类型 | 必填 | 默认值 | 描述 | | 参数 | 类型 | 必填 | 默认值 | 描述 |
| ---- | ------ | ---- | ---- | --------- | | ---- | ------ | ---- | ---- | --------- |
| x | number | 是 | 0 | 指定位置的x坐标。 | | x | number | 是 | 0 | 指定位置的x坐标。 |
| y | number | 是 | 0 | 指定位置的y坐标。 | | y | number | 是 | 0 | 指定位置的y坐标。 |
- 示例 **示例:**
```
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct LineTo { struct LineTo {
...@@ -1141,8 +1187,10 @@ closePath(): void ...@@ -1141,8 +1187,10 @@ closePath(): void
结束当前路径形成一个封闭路径。 结束当前路径形成一个封闭路径。
- 示例 **示例:**
```
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct ClosePath { struct ClosePath {
...@@ -1177,18 +1225,27 @@ closePath(): void ...@@ -1177,18 +1225,27 @@ closePath(): void
### createPattern ### createPattern
createPattern(image: ImageBitmap, repetition: string): CanvasPattern createPattern(image: ImageBitmap, repetition: string | null): CanvasPattern | null
通过指定图像和重复方式创建图片填充的模板。 通过指定图像和重复方式创建图片填充的模板。
- 参数 **参数:**
| 参数 | 类型 | 必填 | 默认值 | 描述 | | 参数 | 类型 | 必填 | 默认值 | 描述 |
| ---------- | ---------------------------------------- | ---- | ---- | ---------------------------------------- | | ---------- | ---------------------------------------- | ---- | ---- | ---------------------------------------- |
| image | [ImageBitmap](ts-components-canvas-imagebitmap.md) | 是 | null | 图源对象,具体参考ImageBitmap对象。 | | image | [ImageBitmap](ts-components-canvas-imagebitmap.md) | 是 | null | 图源对象,具体参考ImageBitmap对象。 |
| repetition | string | 是 | “” | 设置图像重复的方式,取值为:'repeat'、'repeat-x'、&nbsp;'repeat-y'、'no-repeat'。 | | repetition | string | 是 | “” | 设置图像重复的方式,取值为:'repeat'、'repeat-x'、&nbsp;'repeat-y'、'no-repeat'。 |
- 示例 **返回值:**
```
| 类型 | 说明 |
| ---------- | ---------------------------------------- |
| [CanvasPattern](#canvaspattern) | 通过指定图像和重复方式创建图片填充的模板对象。 |
**示例:**
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct CreatePattern { struct CreatePattern {
...@@ -1225,7 +1282,8 @@ bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number, ...@@ -1225,7 +1282,8 @@ bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number,
创建三次贝赛尔曲线的路径。 创建三次贝赛尔曲线的路径。
- 参数 **参数:**
| 参数 | 类型 | 必填 | 默认值 | 描述 | | 参数 | 类型 | 必填 | 默认值 | 描述 |
| ---- | ------ | ---- | ---- | -------------- | | ---- | ------ | ---- | ---- | -------------- |
| cp1x | number | 是 | 0 | 第一个贝塞尔参数的x坐标值。 | | cp1x | number | 是 | 0 | 第一个贝塞尔参数的x坐标值。 |
...@@ -1235,8 +1293,10 @@ bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number, ...@@ -1235,8 +1293,10 @@ bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number,
| x | number | 是 | 0 | 路径结束时的x坐标值。 | | x | number | 是 | 0 | 路径结束时的x坐标值。 |
| y | number | 是 | 0 | 路径结束时的y坐标值。 | | y | number | 是 | 0 | 路径结束时的y坐标值。 |
- 示例 **示例:**
```
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct BezierCurveTo { struct BezierCurveTo {
...@@ -1273,7 +1333,8 @@ quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void ...@@ -1273,7 +1333,8 @@ quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void
创建二次贝赛尔曲线的路径。 创建二次贝赛尔曲线的路径。
- 参数 **参数:**
| 参数 | 类型 | 必填 | 默认值 | 描述 | | 参数 | 类型 | 必填 | 默认值 | 描述 |
| ---- | ------ | ---- | ---- | ----------- | | ---- | ------ | ---- | ---- | ----------- |
| cpx | number | 是 | 0 | 贝塞尔参数的x坐标值。 | | cpx | number | 是 | 0 | 贝塞尔参数的x坐标值。 |
...@@ -1281,8 +1342,10 @@ quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void ...@@ -1281,8 +1342,10 @@ quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void
| x | number | 是 | 0 | 路径结束时的x坐标值。 | | x | number | 是 | 0 | 路径结束时的x坐标值。 |
| y | number | 是 | 0 | 路径结束时的y坐标值。 | | y | number | 是 | 0 | 路径结束时的y坐标值。 |
- 示例 **示例:**
```
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct QuadraticCurveTo { struct QuadraticCurveTo {
...@@ -1315,11 +1378,12 @@ quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void ...@@ -1315,11 +1378,12 @@ quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void
### arc ### arc
arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, anticlockwise?: boolean): void arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, counterclockwise?: boolean): void
绘制弧线路径。 绘制弧线路径。
- 参数 **参数:**
| 参数 | 类型 | 必填 | 默认值 | 描述 | | 参数 | 类型 | 必填 | 默认值 | 描述 |
| ------------- | ------- | ---- | ----- | ---------- | | ------------- | ------- | ---- | ----- | ---------- |
| x | number | 是 | 0 | 弧线圆心的x坐标值。 | | x | number | 是 | 0 | 弧线圆心的x坐标值。 |
...@@ -1327,10 +1391,12 @@ arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, ...@@ -1327,10 +1391,12 @@ arc(x: number, y: number, radius: number, startAngle: number, endAngle: number,
| radius | number | 是 | 0 | 弧线的圆半径。 | | radius | number | 是 | 0 | 弧线的圆半径。 |
| startAngle | number | 是 | 0 | 弧线的起始弧度。 | | startAngle | number | 是 | 0 | 弧线的起始弧度。 |
| endAngle | number | 是 | 0 | 弧线的终止弧度。 | | endAngle | number | 是 | 0 | 弧线的终止弧度。 |
| anticlockwise | boolean | 否 | false | 是否逆时针绘制圆弧。 | | counterclockwise | boolean | 否 | false | 是否逆时针绘制圆弧。 |
- 示例 **示例:**
```
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct Arc { struct Arc {
...@@ -1366,7 +1432,8 @@ arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void ...@@ -1366,7 +1432,8 @@ arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void
依据圆弧经过的点和圆弧半径创建圆弧路径。 依据圆弧经过的点和圆弧半径创建圆弧路径。
- 参数 **参数:**
| 参数 | 类型 | 必填 | 默认值 | 描述 | | 参数 | 类型 | 必填 | 默认值 | 描述 |
| ------ | ------ | ---- | ---- | --------------- | | ------ | ------ | ---- | ---- | --------------- |
| x1 | number | 是 | 0 | 圆弧经过的第一个点的x坐标值。 | | x1 | number | 是 | 0 | 圆弧经过的第一个点的x坐标值。 |
...@@ -1375,8 +1442,10 @@ arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void ...@@ -1375,8 +1442,10 @@ arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void
| y2 | number | 是 | 0 | 圆弧经过的第二个点的y坐标值。 | | y2 | number | 是 | 0 | 圆弧经过的第二个点的y坐标值。 |
| radius | number | 是 | 0 | 圆弧的圆半径值。 | | radius | number | 是 | 0 | 圆弧的圆半径值。 |
- 示例 **示例:**
```
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct ArcTo { struct ArcTo {
...@@ -1408,11 +1477,12 @@ arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void ...@@ -1408,11 +1477,12 @@ arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void
### ellipse ### ellipse
ellipse(x: number, y: number, radiusX: number, radiusY: number, rotation: number, startAngle: number, endAngle: number, anticlockwise?: boolean): void ellipse(x: number, y: number, radiusX: number, radiusY: number, rotation: number, startAngle: number, endAngle: number, counterclockwise?: boolean): void
在规定的矩形区域绘制一个椭圆。 在规定的矩形区域绘制一个椭圆。
- 参数 **参数:**
| 参数 | 类型 | 必填 | 默认值 | 说明 | | 参数 | 类型 | 必填 | 默认值 | 说明 |
| ------------- | ------- | ---- | ----- | ----------------- | | ------------- | ------- | ---- | ----- | ----------------- |
| x | number | 是 | 0 | 椭圆圆心的x轴坐标。 | | x | number | 是 | 0 | 椭圆圆心的x轴坐标。 |
...@@ -1422,11 +1492,12 @@ ellipse(x: number, y: number, radiusX: number, radiusY: number, rotation: number ...@@ -1422,11 +1492,12 @@ ellipse(x: number, y: number, radiusX: number, radiusY: number, rotation: number
| rotation | number | 是 | 0 | 椭圆的旋转角度,单位为弧度。 | | rotation | number | 是 | 0 | 椭圆的旋转角度,单位为弧度。 |
| startAngle | number | 是 | 0 | 椭圆绘制的起始点角度,以弧度表示。 | | startAngle | number | 是 | 0 | 椭圆绘制的起始点角度,以弧度表示。 |
| endAngle | number | 是 | 0 | 椭圆绘制的结束点角度,以弧度表示。 | | endAngle | number | 是 | 0 | 椭圆绘制的结束点角度,以弧度表示。 |
| anticlockwise | boolean | 否 | false | 是否以逆时针方向绘制椭圆。 | | counterclockwise | boolean | 否 | false | 是否以逆时针方向绘制椭圆。 |
- 示例 **示例:**
``` ```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct CanvasExample { struct CanvasExample {
...@@ -1458,20 +1529,23 @@ ellipse(x: number, y: number, radiusX: number, radiusY: number, rotation: number ...@@ -1458,20 +1529,23 @@ ellipse(x: number, y: number, radiusX: number, radiusY: number, rotation: number
### rect ### rect
rect(x: number, y: number, width: number, height: number): void rect(x: number, y: number, w: number, h: number): void
创建矩形路径。 创建矩形路径。
- 参数 **参数:**
| 参数 | 类型 | 必填 | 默认值 | 描述 | | 参数 | 类型 | 必填 | 默认值 | 描述 |
| ------ | ------ | ---- | ---- | ------------- | | ------ | ------ | ---- | ---- | ------------- |
| x | number | 是 | 0 | 指定矩形的左上角x坐标值。 | | x | number | 是 | 0 | 指定矩形的左上角x坐标值。 |
| y | number | 是 | 0 | 指定矩形的左上角y坐标值。 | | y | number | 是 | 0 | 指定矩形的左上角y坐标值。 |
| width | number | 是 | 0 | 指定矩形的宽度。 | | w | number | 是 | 0 | 指定矩形的宽度。 |
| height | number | 是 | 0 | 指定矩形的高度。 | | h | number | 是 | 0 | 指定矩形的高度。 |
- 示例 **示例:**
```
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct CanvasExample { struct CanvasExample {
...@@ -1506,8 +1580,10 @@ fill(): void ...@@ -1506,8 +1580,10 @@ fill(): void
对封闭路径进行填充。 对封闭路径进行填充。
- 示例 **示例:**
```
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct Fill { struct Fill {
...@@ -1542,8 +1618,10 @@ clip(): void ...@@ -1542,8 +1618,10 @@ clip(): void
设置当前路径为剪切路径。 设置当前路径为剪切路径。
- 示例 **示例:**
```
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct Clip { struct Clip {
...@@ -1577,17 +1655,20 @@ clip(): void ...@@ -1577,17 +1655,20 @@ clip(): void
### rotate ### rotate
rotate(rotate: number): void rotate(angle: number): void
针对当前坐标轴进行顺时针旋转。 针对当前坐标轴进行顺时针旋转。
- 参数 **参数:**
| 参数 | 类型 | 必填 | 默认值 | 描述 | | 参数 | 类型 | 必填 | 默认值 | 描述 |
| ------ | ------ | ---- | ---- | ---------------------------------------- | | ------ | ------ | ---- | ---- | ---------------------------------------- |
| rotate | number | 是 | 0 | 设置顺时针旋转的弧度值,可以通过Math.PI&nbsp;/&nbsp;180将角度转换为弧度值。 | | angle | number | 是 | 0 | 设置顺时针旋转的弧度值,可以通过Math.PI&nbsp;/&nbsp;180将角度转换为弧度值。 |
- 示例 **示例:**
```
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct Rotate { struct Rotate {
...@@ -1622,14 +1703,17 @@ scale(x: number, y: number): void ...@@ -1622,14 +1703,17 @@ scale(x: number, y: number): void
设置canvas画布的缩放变换属性,后续的绘制操作将按照缩放比例进行缩放。 设置canvas画布的缩放变换属性,后续的绘制操作将按照缩放比例进行缩放。
- 参数 **参数:**
| 参数 | 类型 | 必填 | 默认值 | 描述 | | 参数 | 类型 | 必填 | 默认值 | 描述 |
| ---- | ------ | ---- | ---- | ----------- | | ---- | ------ | ---- | ---- | ----------- |
| x | number | 是 | 0 | 设置水平方向的缩放值。 | | x | number | 是 | 0 | 设置水平方向的缩放值。 |
| y | number | 是 | 0 | 设置垂直方向的缩放值。 | | y | number | 是 | 0 | 设置垂直方向的缩放值。 |
- 示例 **示例:**
```
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct Scale { struct Scale {
...@@ -1661,29 +1745,32 @@ scale(x: number, y: number): void ...@@ -1661,29 +1745,32 @@ scale(x: number, y: number): void
### transform ### transform
transform(scaleX: number, skewX: number, skewY: number, scaleY: number, translateX: number, translateY: number): void transform(a: number, b: number, c: number, d: number, e: number, f: number): void
transform方法对应一个变换矩阵,想对一个图形进行变化的时候,只要设置此变换矩阵相应的参数,对图形的各个定点的坐标分别乘以这个矩阵,就能得到新的定点的坐标。矩阵变换效果可叠加。 transform方法对应一个变换矩阵,想对一个图形进行变化的时候,只要设置此变换矩阵相应的参数,对图形的各个定点的坐标分别乘以这个矩阵,就能得到新的定点的坐标。矩阵变换效果可叠加。
> **说明:** > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
> 变换后的坐标计算方式(x和y为变换前坐标,x'和y'为变换后坐标): > 变换后的坐标计算方式(x和y为变换前坐标,x'和y'为变换后坐标):
> >
> - x' = scaleX \* x + skewY \* y + translateX > - x' = scaleX \* x + skewY \* y + translateX
> >
> - y' = skewX \* x + scaleY \* y + translateY > - y' = skewX \* x + scaleY \* y + translateY
- 参数 **参数:**
| 参数 | 类型 | 必填 | 默认值 | 描述 | | 参数 | 类型 | 必填 | 默认值 | 描述 |
| ---------- | ------ | ---- | ---- | -------- | | ---------- | ------ | ---- | ---- | -------- |
| scaleX | number | 是 | 0 | 指定水平缩放值。 | | a | number | 是 | 0 |scaleX: 指定水平缩放值。 |
| skewX | number | 是 | 0 | 指定水平倾斜值。 | | b | number | 是 | 0 |skewX: 指定水平倾斜值。 |
| skewY | number | 是 | 0 | 指定垂直倾斜值。 | | c | number | 是 | 0 |skewY: 指定垂直倾斜值。 |
| scaleY | number | 是 | 0 | 指定垂直缩放值。 | | d | number | 是 | 0 |scaleY: 指定垂直缩放值。 |
| translateX | number | 是 | 0 | 指定水平移动值。 | | e | number | 是 | 0 |translateX: 指定水平移动值。 |
| translateY | number | 是 | 0 | 指定垂直移动值。 | | f | number | 是 | 0 |translateY: 指定垂直移动值。 |
- 示例 **示例:**
```
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct Transform { struct Transform {
...@@ -1720,22 +1807,25 @@ transform方法对应一个变换矩阵,想对一个图形进行变化的时 ...@@ -1720,22 +1807,25 @@ transform方法对应一个变换矩阵,想对一个图形进行变化的时
### setTransform ### setTransform
setTransform(scaleX: number, skewX: number, skewY: number, scale: number, translateX: number, translateY: number): void setTransform(a: number, b: number, c: number, d: number, e: number, f: number): void
setTransfrom方法使用的参数和transform()方法相同,但setTransform()方法会重置现有的变换矩阵并创建新的变换矩阵。 setTransfrom方法使用的参数和transform()方法相同,但setTransform()方法会重置现有的变换矩阵并创建新的变换矩阵。
- 参数 **参数:**
| 参数 | 类型 | 必填 | 默认值 | 描述 | | 参数 | 类型 | 必填 | 默认值 | 描述 |
| ---------- | ------ | ---- | ---- | -------- | | ---------- | ------ | ---- | ---- | -------- |
| scaleX | number | 是 | 0 | 指定水平缩放值。 | | a | number | 是 | 0 |scaleX: 指定水平缩放值。 |
| skewX | number | 是 | 0 | 指定水平倾斜值。 | | b | number | 是 | 0 |skewX: 指定水平倾斜值。 |
| skewY | number | 是 | 0 | 指定垂直倾斜值。 | | c | number | 是 | 0 |skewY: 指定垂直倾斜值。 |
| scaleY | number | 是 | 0 | 指定垂直缩放值。 | | d | number | 是 | 0 |scaleY: 指定垂直缩放值。 |
| translateX | number | 是 | 0 | 指定水平移动值。 | | e | number | 是 | 0 |translateX: 指定水平移动值。 |
| translateY | number | 是 | 0 | 指定垂直移动值。 | | f | number | 是 | 0 |translateY: 指定垂直移动值。 |
- 示例 **示例:**
```
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct SetTransform { struct SetTransform {
...@@ -1773,14 +1863,17 @@ translate(x: number, y: number): void ...@@ -1773,14 +1863,17 @@ translate(x: number, y: number): void
移动当前坐标系的原点。 移动当前坐标系的原点。
- 参数 **参数:**
| 参数 | 类型 | 必填 | 默认值 | 描述 | | 参数 | 类型 | 必填 | 默认值 | 描述 |
| ---- | ------ | ---- | ---- | -------- | | ---- | ------ | ---- | ---- | -------- |
| x | number | 是 | 0 | 设置水平平移量。 | | x | number | 是 | 0 | 设置水平平移量。 |
| y | number | 是 | 0 | 设置竖直平移量。 | | y | number | 是 | 0 | 设置竖直平移量。 |
- 示例 **示例:**
```
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct Translate { struct Translate {
...@@ -1814,28 +1907,31 @@ translate(x: number, y: number): void ...@@ -1814,28 +1907,31 @@ translate(x: number, y: number): void
drawImage(image: ImageBitmap | PixelMap, dx: number, dy: number): void drawImage(image: ImageBitmap | PixelMap, dx: number, dy: number): void
drawImage(image: ImageBitmap | PixelMap, dx: number, dy: number, dWidth: number, dHeight: number): void drawImage(image: ImageBitmap | PixelMap, dx: number, dy: number, dw: number, dh: number): void
drawImage(image: ImageBitmap | PixelMap, sx: number, sy: number, sWidth: number, sHeight: number, dx: number, dy: number, dWidth: number, dHeight: number):void drawImage(image: ImageBitmap | PixelMap, sx: number, sy: number, sw: number, sh: number, dx: number, dy: number, dw: number, dh: number):void
进行图像绘制。 进行图像绘制。
- 参数 **参数:**
| 参数 | 类型 | 必填 | 默认值 | 描述 | | 参数 | 类型 | 必填 | 默认值 | 描述 |
| ------- | ---------------------------------------- | ---- | ---- | -------------------- | | ------- | ---------------------------------------- | ---- | ---- | -------------------- |
| image | [ImageBitmap](ts-components-canvas-imagebitmap.md)[PixelMap](../apis/js-apis-image.md#pixelmap7)| 是 | null | 图片资源,请参考ImageBitmap或PixelMap。 | | image | [ImageBitmap](ts-components-canvas-imagebitmap.md)[PixelMap](../apis/js-apis-image.md#pixelmap7)| 是 | null | 图片资源,请参考ImageBitmap或PixelMap。 |
| sx | number | 否 | 0 | 裁切源图像时距离源图像左上角的x坐标值。 | | sx | number | 否 | 0 | 裁切源图像时距离源图像左上角的x坐标值。 |
| sy | number | 否 | 0 | 裁切源图像时距离源图像左上角的y坐标值。 | | sy | number | 否 | 0 | 裁切源图像时距离源图像左上角的y坐标值。 |
| sWidth | number | 否 | 0 | 裁切源图像时需要裁切的宽度。 | | sw | number | 否 | 0 | 裁切源图像时需要裁切的宽度。 |
| sHeight | number | 否 | 0 | 裁切源图像时需要裁切的高度。 | | sh | number | 否 | 0 | 裁切源图像时需要裁切的高度。 |
| dx | number | 是 | 0 | 绘制区域左上角在x轴的位置。 | | dx | number | 是 | 0 | 绘制区域左上角在x轴的位置。 |
| dy | number | 是 | 0 | 绘制区域左上角在y&nbsp;轴的位置。 | | dy | number | 是 | 0 | 绘制区域左上角在y&nbsp;轴的位置。 |
| dWidth | number | 否 | 0 | 绘制区域的宽度。 | | dw | number | 否 | 0 | 绘制区域的宽度。 |
| dHeight | number | 否 | 0 | 绘制区域的高度。 | | dh | number | 否 | 0 | 绘制区域的高度。 |
- 示例 **示例:**
```
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct Index { struct Index {
...@@ -1866,34 +1962,44 @@ drawImage(image: ImageBitmap | PixelMap, sx: number, sy: number, sWidth: number, ...@@ -1866,34 +1962,44 @@ drawImage(image: ImageBitmap | PixelMap, sx: number, sy: number, sWidth: number,
### createImageData ### createImageData
createImageData(width: number, height: number): Object createImageData(sw: number, sh: number): ImageData
根据宽高创建ImageData对象,请参考[ImageData](ts-components-canvas-imagebitmap.md) 根据宽高创建ImageData对象,请参考[ImageData](ts-components-canvas-imagebitmap.md)
- 参数 **参数:**
| 参数 | 类型 | 必填 | 默认 | 描述 | | 参数 | 类型 | 必填 | 默认 | 描述 |
| ------ | ------ | ---- | ---- | ------------- | | ------ | ------ | ---- | ---- | ------------- |
| width | number | 是 | 0 | ImageData的宽度。 | | sw | number | 是 | 0 | ImageData的宽度。 |
| height | number | 是 | 0 | ImageData的高度。 | | sh | number | 是 | 0 | ImageData的高度。 |
### createImageData ### createImageData
createImageData(imageData: ImageData): Object createImageData(imageData: ImageData): ImageData
根据已创建的ImageData对象创建新的ImageData对象,请参考[ImageData](ts-components-canvas-imagebitmap.md) 根据已创建的ImageData对象创建新的ImageData对象,请参考[ImageData](ts-components-canvas-imagebitmap.md)
- 参数 **参数:**
| 参数 | 类型 | 必填 | 默认 | 描述 | | 参数 | 类型 | 必填 | 默认 | 描述 |
| --------- | ---------------------------------------- | ---- | ---- | ---------------- | | --------- | ---------------------------------------- | ---- | ---- | ---------------- |
| imagedata | [ImageData](ts-components-canvas-imagebitmap.md) | 是 | null | 被复制的ImageData对象。 | | imagedata | [ImageData](ts-components-canvas-imagebitmap.md) | 是 | null | 被复制的ImageData对象。 |
**返回值:**
| 类型 | 说明 |
| ---------- | ---------------------------------------- |
| [ImageData](ts-components-canvas-imagebitmap.md) | 新的ImageData对象 |
### getPixelMap ### getPixelMap
getPixelMap(sx: number, sy: number, sw: number, sh: number): PixelMap getPixelMap(sx: number, sy: number, sw: number, sh: number): PixelMap
以当前canvas指定区域内的像素创建[PixelMap](../apis/js-apis-image.md#pixelmap7)对象。 以当前canvas指定区域内的像素创建[PixelMap](../apis/js-apis-image.md#pixelmap7)对象。
- 参数
**参数:**
| 参数 | 类型 | 必填 | 默认值 | 描述 | | 参数 | 类型 | 必填 | 默认值 | 描述 |
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| sx | number | 是 | 0 | 需要输出的区域的左上角x坐标。 | | sx | number | 是 | 0 | 需要输出的区域的左上角x坐标。 |
...@@ -1901,13 +2007,21 @@ getPixelMap(sx: number, sy: number, sw: number, sh: number): PixelMap ...@@ -1901,13 +2007,21 @@ getPixelMap(sx: number, sy: number, sw: number, sh: number): PixelMap
| sw | number | 是 | 0 | 需要输出的区域的宽度。 | | sw | number | 是 | 0 | 需要输出的区域的宽度。 |
| sh | number | 是 | 0 | 需要输出的区域的高度。 | | sh | number | 是 | 0 | 需要输出的区域的高度。 |
**返回值:**
| 类型 | 说明 |
| ---------- | ---------------------------------------- |
| [PixelMap](../apis/js-apis-image.md#pixelmap7) | 新的PixelMap对象 |
### getImageData ### getImageData
getImageData(sx: number, sy: number, sw: number, sh: number): Object getImageData(sx: number, sy: number, sw: number, sh: number): ImageData
以当前canvas指定区域内的像素创建[ImageData](ts-components-canvas-imagebitmap.md)对象。 以当前canvas指定区域内的像素创建[ImageData](ts-components-canvas-imagebitmap.md)对象。
- 参数 **参数:**
| 参数 | 类型 | 必填 | 默认值 | 描述 | | 参数 | 类型 | 必填 | 默认值 | 描述 |
| ---- | ------ | ---- | ---- | --------------- | | ---- | ------ | ---- | ---- | --------------- |
| sx | number | 是 | 0 | 需要输出的区域的左上角x坐标。 | | sx | number | 是 | 0 | 需要输出的区域的左上角x坐标。 |
...@@ -1915,14 +2029,23 @@ getImageData(sx: number, sy: number, sw: number, sh: number): Object ...@@ -1915,14 +2029,23 @@ getImageData(sx: number, sy: number, sw: number, sh: number): Object
| sw | number | 是 | 0 | 需要输出的区域的宽度。 | | sw | number | 是 | 0 | 需要输出的区域的宽度。 |
| sh | number | 是 | 0 | 需要输出的区域的高度。 | | sh | number | 是 | 0 | 需要输出的区域的高度。 |
**返回值:**
| 类型 | 说明 |
| ---------- | ---------------------------------------- |
| [ImageData](ts-components-canvas-imagebitmap.md) | 新的ImageData对象 |
### putImageData ### putImageData
putImageData(imageData: Object, dx: number, dy: number, dirtyX?: number, dirtyY?: number, dirtyWidth?: number, dirtyHeight?: number): void putImageData(imageData: Object, dx: number, dy: number): void
putImageData(imageData: Object, dx: number, dy: number, dirtyX: number, dirtyY: number, dirtyWidth?: number, dirtyHeight: number): void
使用[ImageData](ts-components-canvas-imagebitmap.md)数据填充新的矩形区域。 使用[ImageData](ts-components-canvas-imagebitmap.md)数据填充新的矩形区域。
- 参数 **参数:**
| 参数 | 类型 | 必填 | 默认值 | 描述 | | 参数 | 类型 | 必填 | 默认值 | 描述 |
| ----------- | ------ | ---- | ------------ | ----------------------------- | | ----------- | ------ | ---- | ------------ | ----------------------------- |
| imagedata | Object | 是 | null | 包含像素值的ImageData对象。 | | imagedata | Object | 是 | null | 包含像素值的ImageData对象。 |
...@@ -1933,8 +2056,10 @@ putImageData(imageData: Object, dx: number, dy: number, dirtyX?: number, dirtyY? ...@@ -1933,8 +2056,10 @@ putImageData(imageData: Object, dx: number, dy: number, dirtyX?: number, dirtyY?
| dirtyWidth | number | 否 | imagedata的宽度 | 源图像数据矩形裁切范围的宽度。 | | dirtyWidth | number | 否 | imagedata的宽度 | 源图像数据矩形裁切范围的宽度。 |
| dirtyHeight | number | 否 | imagedata的高度 | 源图像数据矩形裁切范围的高度。 | | dirtyHeight | number | 否 | imagedata的高度 | 源图像数据矩形裁切范围的高度。 |
- 示例 **示例:**
```
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct PutImageData { struct PutImageData {
...@@ -1968,6 +2093,225 @@ putImageData(imageData: Object, dx: number, dy: number, dirtyX?: number, dirtyY? ...@@ -1968,6 +2093,225 @@ putImageData(imageData: Object, dx: number, dy: number, dirtyX?: number, dirtyY?
![zh-cn_image_0000001194192464](figures/zh-cn_image_0000001194192464.png) ![zh-cn_image_0000001194192464](figures/zh-cn_image_0000001194192464.png)
### setLineDash
setLineDash(segments: number[]): void
设置画布的虚线样式。
**参数:**
| 参数 | 类型 | 描述 |
| -------- | ----- | -------------------- |
| segments | number[] | 描述线段如何交替和线段间距长度的数组。 |
**示例:**
```ts
@Entry
@Component
struct SetLineDash {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings)
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context)
.width('100%')
.height('100%')
.backgroundColor('#ffff00')
.onReady(() =>{
this.offContext.arc(100, 75, 50, 0, 6.28)
this.offContext.setLineDash([10,20])
this.offContext.stroke();
var image = this.offContext.transferToImageBitmap()
this.context.transferFromImageBitmap(image)
})
}
.width('100%')
.height('100%')
}
}
```
![zh-cn_image_000000127777772](figures/zh-cn_image_000000127777772.png)
### getLineDash
getLineDash(): number[]
获得当前画布的虚线样式。
**返回值:**
| 类型 | 说明 |
| ----- | ------------------------ |
| number[] | 返回数组,该数组用来描述线段如何交替和间距长度。 |
**示例:**
```ts
// xxx.ets
@Entry
@Component
struct GetLineDash {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings)
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context)
.width('100%')
.height('100%')
.backgroundColor('#ffff00')
.onReady(() =>{
var grad = this.context.createLinearGradient(50,0, 300,100)
this.offContext.arc(100, 75, 50, 0, 6.28)
this.offContext.setLineDash([10,20])
this.offContext.stroke();
let res = this.offContext.getLineDash()
var image = this.offContext.transferToImageBitmap()
this.context.transferFromImageBitmap(image)
})
}
.width('100%')
.height('100%')
}
}
```
### transferFromImageBitmap
transferFromImageBitmap(bitmap: ImageBitmap): void
显示给定的ImageBitmap对象。
**参数:**
| 参数 | 类型 | 描述 |
| ------ | ----------- | ------------------ |
| bitmap | [ImageData](ts-components-canvas-imagebitmap.md) | 待显示的ImageBitmap对象。 |
**示例:**
```ts
// xxx.ets
@Entry
@Component
struct GetLineDash {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings)
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context)
.width('100%')
.height('100%')
.backgroundColor('#ffff00')
.onReady(() =>{
this.offContext.fillRect(0, 0, 200, 200)
var image = this.offContext.transferToImageBitmap()
this.context.transferFromImageBitmap(image)
})
}
.width('100%')
.height('100%')
}
}
```
![zh-cn_image_000000127777773](figures/zh-cn_image_000000127777773.png)
### toDataURL
toDataURL(type?: string, quality?: number): string
生成一个包含图片展示的URL。
**参数:**
| 参数名 | 参数类型 | 必填 | 描述 |
| ------- | ------ | ---- | ---------------------------------------- |
| type | string | 否 | 可选参数,用于指定图像格式,默认格式为image/png。 |
| quality | number | 否 | 在指定图片格式为image/jpeg或image/webp的情况下,可以从0到1的区间内选择图片的质量。如果超出取值范围,将会使用默认值0.92。 |
**返回值:**
| 类型 | 说明 |
| ------ | --------- |
| string | 图像的URL地址。 |
**示例:**
```ts
// xxx.ets
@Entry
@Component
struct ToDataURL {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings)
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context)
.width('100%')
.height('100%')
.backgroundColor('#ffff00')
.onReady(() =>{
var dataURL = this.offContext.toDataURL();
})
}
.width('100%')
.height('100%')
}
}
```
### transferToImageBitmap
transferToImageBitmap(): ImageBitmap
在离屏画布最近渲染的图像上创建一个ImageBitmap对象。
**返回值:**
| 类型 | 说明 |
| ---------------------------------------- | --------------- |
| [ImageData](ts-components-canvas-imagebitmap.md)| 存储离屏画布上渲染的像素数据。 |
**示例:**
```ts
// xxx.ets
@Entry
@Component
struct CanvasExample {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings)
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context)
.width('100%')
.height('100%')
.backgroundColor('#ffff00')
.onReady(() =>{
this.offContext.restore()
var image = this.offContext.transferToImageBitmap()
this.context.transferFromImageBitmap(image)
})
}
.width('100%')
.height('100%')
}
}
```
### restore ### restore
...@@ -1975,8 +2319,10 @@ restore(): void ...@@ -1975,8 +2319,10 @@ restore(): void
对保存的绘图上下文进行恢复。 对保存的绘图上下文进行恢复。
- 示例 **示例:**
```
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct CanvasExample { struct CanvasExample {
...@@ -2008,8 +2354,10 @@ save(): void ...@@ -2008,8 +2354,10 @@ save(): void
对当前的绘图上下文进行保存。 对当前的绘图上下文进行保存。
- 示例 **示例:**
```
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct CanvasExample { struct CanvasExample {
...@@ -2041,7 +2389,8 @@ createLinearGradient(x0: number, y0: number, x1: number, y1: number): void ...@@ -2041,7 +2389,8 @@ createLinearGradient(x0: number, y0: number, x1: number, y1: number): void
创建一个线性渐变色。 创建一个线性渐变色。
- 参数 **参数:**
| 参数 | 类型 | 必填 | 默认值 | 描述 | | 参数 | 类型 | 必填 | 默认值 | 描述 |
| ---- | ------ | ---- | ---- | -------- | | ---- | ------ | ---- | ---- | -------- |
| x0 | number | 是 | 0 | 起点的x轴坐标。 | | x0 | number | 是 | 0 | 起点的x轴坐标。 |
...@@ -2049,8 +2398,10 @@ createLinearGradient(x0: number, y0: number, x1: number, y1: number): void ...@@ -2049,8 +2398,10 @@ createLinearGradient(x0: number, y0: number, x1: number, y1: number): void
| x1 | number | 是 | 0 | 终点的x轴坐标。 | | x1 | number | 是 | 0 | 终点的x轴坐标。 |
| y1 | number | 是 | 0 | 终点的y轴坐标。 | | y1 | number | 是 | 0 | 终点的y轴坐标。 |
- 示例 **示例:**
```
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct CreateLinearGradient { struct CreateLinearGradient {
...@@ -2090,7 +2441,8 @@ createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number, ...@@ -2090,7 +2441,8 @@ createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number,
创建一个径向渐变色。 创建一个径向渐变色。
- 参数 **参数:**
| 参数 | 类型 | 必填 | 默认值 | 描述 | | 参数 | 类型 | 必填 | 默认值 | 描述 |
| ---- | ------ | ---- | ---- | ----------------- | | ---- | ------ | ---- | ---- | ----------------- |
| x0 | number | 是 | 0 | 起始圆的x轴坐标。 | | x0 | number | 是 | 0 | 起始圆的x轴坐标。 |
...@@ -2100,8 +2452,10 @@ createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number, ...@@ -2100,8 +2452,10 @@ createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number,
| y1 | number | 是 | 0 | 终点圆的y轴坐标。 | | y1 | number | 是 | 0 | 终点圆的y轴坐标。 |
| r1 | number | 是 | 0 | 终点圆的半径。必须为非负且有限的。 | | r1 | number | 是 | 0 | 终点圆的半径。必须为非负且有限的。 |
- 示例 **示例:**
```
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct CreateRadialGradient { struct CreateRadialGradient {
......
# 背景设置 # 背景设置
> **说明:**
> 从API Version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
设置组件的背景色。 设置组件的背景色。
> **说明:**
## 权限列表 >
> 从API Version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
## 属性 ## 属性
| 名称 | 参数类型 | 默认值 | 描述 | | 名称 | 参数类型 | 描述 |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- |
| backgroundColor | Color | - | 设置组件的背景色。 | | backgroundColor | [ResourceColor](ts-types.md#resourcecolor) | 设置组件的背景色。 |
| backgroundImage | src:&nbsp;string,<br/>repeat?:&nbsp;[ImageRepeat](ts-appendix-enums.md#imagerepeat) | - | src参数:图片地址,支持网络图片资源和本地图片资源地址(不支持svg类型的图片)。<br/>repeat参数:设置背景图片的重复样式,默认不重复。 | | backgroundImage | src:&nbsp;[ResourceStr](ts-types.md#resourcestr),<br/>repeat?:&nbsp;[ImageRepeat](ts-appendix-enums.md#imagerepeat) | src:图片地址,支持网络图片资源和本地图片资源地址(不支持svg类型的图片)。<br/>repeat:设置背景图片的重复样式,默认不重复。 |
| backgroundImageSize | {<br/>width?:&nbsp;Length,<br/>height?:&nbsp;Length<br/>}&nbsp;\|&nbsp;[ImageSize](ts-appendix-enums.md#imagesize) | Auto | 设置背景图像的高度和宽度。当输入为{width:&nbsp;Length,&nbsp;height:&nbsp;Length}对象时,如果只设置一个属性,则第二个属性保持图片原始宽高比进行调整。默认保持原图的比例不变。 | | 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:&nbsp;Length,&nbsp;height:&nbsp;Length}对象时,如果只设置一个属性,则第二个属性保持图片原始宽高比进行调整。默认保持原图的比例不变。<br/>默认值:ImageSize.Auto |
| backgroundImagePosition | {<br/>x?:&nbsp;Length,<br/>y?:&nbsp;Length<br/>}&nbsp;\|&nbsp;[Alignment](ts-appendix-enums.md#alignment) | {<br/>x:&nbsp;0,<br/>y:&nbsp;0<br/>} | 设置背景图在组件中显示位置。 | | 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) | 设置背景图在组件中显示位置。<br/>{<br/>x:&nbsp;0,<br/>y:&nbsp;0<br/>} |
## 示例 ## 示例
......
# 边框设置 # 边框设置
> **说明:**
> 从API Version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
设置组件边框样式。 设置组件边框样式。
> **说明:**
## 权限列表 >
> 从API Version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
## 属性 ## 属性
| 名称 | 参数类型 | 默认值 | 描述 | | 名称 | 参数类型 | 描述 |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- |
| border | {<br/>width?:&nbsp;Length,<br/>color?:&nbsp;Color,<br/>radius?:&nbsp;Length,<br/>style?:&nbsp;[BorderStyle](ts-appendix-enums.md#borderstyle)<br/>} | - | 统一边框样式设置接口。 | | 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/>} | 统一边框样式设置接口。 |
| borderStyle | [BorderStyle](ts-appendix-enums.md#borderstyle) | &nbsp;BorderStyle.Solid | 设置元素的边框样式。 | | borderStyle | [BorderStyle](ts-appendix-enums.md#borderstyle) | 设置元素的边框样式。<br/>默认值:BorderStyle.Solid |
| borderWidth | Length | 0 | 设置元素的边框宽度。 | | borderWidth | [Length](ts-types.md#length) | 设置元素的边框宽度。 |
| borderColor | Color | - | 设置元素的边框颜色。 | | borderColor | [ResourceColor](ts-types.md#resourcecolor) | 设置元素的边框颜色。 |
| borderRadius | Length | 0 | 设置元素的边框圆角半径。 | | borderRadius | [Length](ts-types.md#length) | 设置元素的边框圆角半径。 |
......
...@@ -5,24 +5,19 @@ ...@@ -5,24 +5,19 @@
> 从API Version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 > 从API Version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
## 权限列表
## 属性 ## 属性
| 名称 | 参数类型 | 默认值 | 描述 | | 名称 | 参数类型 | 描述 |
| ---------------------------- | ------------------------------------------------------------ | ------ | ------------------------------------------------------------ | | ---------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| bindMenu | Array<MenuItem&gt;&nbsp;\|&nbsp;[CustomBuilder](ts-types.md#custombuilder8)<sup>8+</sup> | - | 给组件绑定菜单,点击后弹出菜单。弹出菜单项支持文本和自定义两种功能。 | | bindMenu | Array<MenuItem&gt;&nbsp;\|&nbsp;[CustomBuilder](ts-types.md#custombuilder8) | 给组件绑定菜单,点击后弹出菜单。弹出菜单项支持文本和自定义两种功能。 |
| bindContextMenu<sup>8+</sup> | content:&nbsp;[CustomBuilder](ts-types.md#custombuilder8)<br>responseType:&nbsp;[ResponseType](ts-appendix-enums.md#responsetype8) | - | 给组件绑定菜单,触发方式为长按或者右键点击,弹出菜单项需要自定义。 | | bindContextMenu<sup>8+</sup> | content:&nbsp;[CustomBuilder](ts-types.md#custombuilder8)<br>responseType:&nbsp;[ResponseType](ts-appendix-enums.md#responsetype8) | 给组件绑定菜单,触发方式为长按或者右键点击,弹出菜单项需要自定义。 |
## MenuItem ## MenuItem
| 名称 | 类型 | 描述 | | 名称 | 类型 | 描述 |
| ------ | ----------------------- | ----------- | | ------ | ----------------------- | ---------------------- |
| value | string | 菜单项文本。 | | value | string | 菜单项文本。 |
| action | ()&nbsp;=&gt;&nbsp;void | 点击菜单项的事件回调。 | | action | ()&nbsp;=&gt;&nbsp;void | 点击菜单项的事件回调。 |
......
...@@ -7,17 +7,12 @@ ...@@ -7,17 +7,12 @@
> 从API Version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 > 从API Version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
## 权限列表
## 属性 ## 属性
| 名称 | 参数类型 | 默认值 | 描述 | | 名称 | 参数类型 | 描述 |
| ------- | ------ | ---- | ---------------------------------- | | ------- | ---------------------------------------------------- | ------------------------------------------------------------ |
| opacity | number | 1 | 元素的不透明度,取值范围为0到1,1表示为不透明,0表示为完全透明。 | | opacity | number&nbsp;\|&nbsp;[Resource](ts-types.md#resource) | 元素的不透明度,取值范围为0到1,1表示为不透明,0表示为完全透明。<br/>默认值:1 |
## 示例 ## 示例
......
# 多态样式 # 多态样式
> **说明:**
> 从API Version 8开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
设置组件不同状态下的样式。 设置组件不同状态下的样式。
> **说明:**
## 权限列表 >
> 从API Version 8开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
## 属性 ## 属性
| 名称 | 参数类型 | 默认值 | 描述 | | 名称 | 参数类型 | 描述 |
| ----------- | ----------- | ---- | ------------ | | ----------- | ----------- | ------------------------ |
| stateStyles | StateStyles | - | 设置组件不同状态的样式。 | | stateStyles | StateStyles | 设置组件不同状态的样式。 |
## StateStyles接口说明 ## StateStyles接口说明
| 名称 | 类型 | 必填 | 默认值 | 描述 | | 名称 | 类型 | 必填 | 描述 |
| -------- | ----------- | ---- | ---- | ---------- | | -------- | ---- | ---- | -------------------- |
| normal | ()=&gt;void | 否 | - | 组件无状态时的样式。 | | normal | any | 否 | 组件无状态时的样式。 |
| pressed | ()=&gt;void | 否 | - | 组件按下状态的样式。 | | pressed | any | 否 | 组件按下状态的样式。 |
| disabled | ()=&gt;void | 否 | - | 组件禁用状态的样式。 | | disabled | any | 否 | 组件禁用状态的样式。 |
| focused | any | 否 | 组件获焦状态的样式。 |
| clicked | any | 否 | 组件点击状态的样式。 |
## 示例 ## 示例
......
...@@ -5,39 +5,34 @@ ...@@ -5,39 +5,34 @@
> 从API Version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 > 从API Version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
## 权限列表 ## 接口
| 名称 | 参数类型 | 描述 |
| --------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
## 属性 | bindPopup | show:&nbsp;boolean,<br/>popup:&nbsp;PopupOptions\|&nbsp;CustomPopupOptions<sup>8+</sup> | 给组件绑定Popup,点击弹出弹窗。<br/>show:&nbsp;创建页面弹窗提示是否默认显示,默认值为false。<br/>popup:&nbsp;配置当前弹窗提示的参数。 |
## PopupOptions类型说明
| 名称 | 参数类型 | 默认值 | 描述 |
| --------- | ---------------------------------------- | ---- | ---------------------------------------- | | 名称 | 类型 | 必填 | 描述 |
| bindPopup | show:&nbsp;boolean,<br/>popup:&nbsp;PopupOptions\|&nbsp;CustomPopupOptions | - | 给组件绑定Popup,点击弹出弹窗。<br/>show:&nbsp;创建页面弹窗提示是否默认显示,默认值为false。<br/>popup:&nbsp;配置当前弹窗提示的参数。 | | --------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| message | string | 是 | 弹窗信息内容。 |
## PopupOptions类型接口说明 | placementOnTop | boolean | 否 | 是否在组件上方显示,默认值为false。 |
| primaryButton | {<br/>value:&nbsp;string,<br/>action:&nbsp;()&nbsp;=&gt;&nbsp;void<br/>} | 否 | 第一个按钮。<br/>value:&nbsp;弹窗里主按钮的文本。<br/>action:&nbsp;点击主按钮的回调函数。 |
| 名称 | 类型 | 必填 | 默认值 | 描述 | | secondaryButton | {<br/>value:&nbsp;string,<br/>action:&nbsp;()&nbsp;=&gt;&nbsp;void<br/>} | 否 | 第二个按钮。<br/>value:&nbsp;弹窗里辅助按钮的文本。<br/>action:&nbsp;点击辅助按钮的回调函数。 |
| --------------- | ---------------------------------------- | ---- | ----- | ---------------------------------------- | | onStateChange | (event:{isVisible:&nbsp;boolean })&nbsp;=&gt;&nbsp;void | 否 | 弹窗状态变化事件回调,参数isVisible为弹窗当前的显示状态。 |
| message | string | 是 | - | 弹窗信息内容。 |
| placementOnTop | boolean | 否 | false | 是否在组件上方显示,默认值为false。 | ## CustomPopupOptions<sup>8+</sup>类型说明
| primaryButton | {<br/>value:&nbsp;string,<br/>action:&nbsp;()&nbsp;=&gt;&nbsp;void<br/>} | 否 | - | 第一个按钮。<br/>value:&nbsp;弹窗里主按钮的文本。<br/>action:&nbsp;点击主按钮的回调函数。 |
| secondaryButton | {<br/>value:&nbsp;string,<br/>action:&nbsp;()&nbsp;=&gt;&nbsp;void<br/>} | 否 | - | 第二个按钮。<br/>value:&nbsp;弹窗里辅助按钮的文本。<br/>action:&nbsp;点击辅助按钮的回调函数。 | | 名称 | 类型 | 必填 | 描述 |
| onStateChange | (isVisible:&nbsp;boolean)&nbsp;=&gt;&nbsp;void | 否 | - | 弹窗状态变化事件回调,参数isVisible为弹窗当前的显示状态。 | | ------------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ |
| builder | [CustomBuilder](ts-types.md#custombuilder8) | 是 | 提示气泡内容的构造器。 |
## CustomPopupOptions<sup>8+</sup>类型接口说明 | placement | [Placement](ts-appendix-enums.md#placement8) | 否 | 气泡组件优先显示的位置,当前位置显示不下时,会自动调整位置。<br/>默认值:Placement.Bottom |
| maskColor | [ResourceColor](ts-types.md#resourcecolor) | 否 | 提示气泡遮障层的颜色。 |
| 名称 | 类型 | 必填 | 默认值 | 描述 | | popupColor | [ResourceColor](ts-types.md#resourcecolor) | 否 | 提示气泡的颜色。 |
| ------------- | ---------------------------------------------- | ---- | ---------------- | ------------------------------------------------------------ | | enableArrow | boolean | 否 | 是否显示箭头,只有上、下方向的气泡会显示箭头。<br/>默认值:true |
| builder | ()&nbsp;=&gt;&nbsp;any | 是 | - | 提示气泡内容的构造器。 | | autoCancel | boolean | 否 | 页面有操作时,是否自动关闭气泡<br/>默认值:true |
| placement | [Placement](ts-appendix-enums.md#placement8) | 否 | Placement.Bottom | 气泡组件优先显示的位置,当前位置显示不下时,会自动调整位置。 | | onStateChange | (event:{isVisible:&nbsp;boolean })&nbsp;=&gt;&nbsp;void | 否 | 弹窗状态变化事件回调,参数为弹窗当前的显示状态。 |
| maskColor | [Color](ts-appendix-enums.md#color) | 否 | - | 提示气泡遮障层的颜色。 |
| popupColor | [Color](ts-appendix-enums.md#color) | 否 | - | 提示气泡的颜色。 |
| enableArrow | boolean | 否 | true | 是否显示箭头,只有上、下方向的气泡会显示箭头。 |
| autoCancel | boolean | 否 | true | 页面有操作时,是否自动关闭气泡 |
| onStateChange | (isVisible:&nbsp;boolean)&nbsp;=&gt;&nbsp;void | 否 | - | 弹窗状态变化事件回调,参数为弹窗当前的显示状态。 |
## 示例 ## 示例
......
...@@ -5,23 +5,18 @@ ...@@ -5,23 +5,18 @@
> 从API Version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 > 从API Version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
## 权限列表
## 属性 ## 属性
| 名称 | 参数说明 | 默认值 | 描述 | | 名称 | 参数说明 | 描述 |
| -------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | | -------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| width | Length | - | 设置组件自身的宽度,缺省时使用元素自身内容需要的宽度。 | | width | [Length](ts-types.md#length) | 设置组件自身的宽度,缺省时使用元素自身内容需要的宽度。 |
| height | Length | - | 设置组件自身的高度,缺省时使用元素自身内容需要的高度。 | | height | [Length](ts-types.md#length) | 设置组件自身的高度,缺省时使用元素自身内容需要的高度。 |
| size | {<br/>width?:&nbsp;Length,<br/>height?:&nbsp;Length<br/>} | - | 设置高宽尺寸。 | | size | {<br/>width?:&nbsp;[Length](ts-types.md#length),<br/>height?:&nbsp;[Length](ts-types.md#length)<br/>} | 设置高宽尺寸。 |
| padding | {<br/>top?:&nbsp;Length,<br/>right?:&nbsp;Length,<br/>bottom?:&nbsp;Length,<br/>left?:&nbsp;Length<br/>}&nbsp;\|&nbsp;Length | 0 | 设置内边距属性。<br/>参数为Length类型时,四个方向内边距同时生效。 | | padding | [Padding](ts-types.md#padding)&nbsp;\|&nbsp;[Length](ts-types.md#length) | 设置内边距属性。<br/>参数为Length类型时,四个方向内边距同时生效。<br/>默认值:0 |
| margin | {<br/>top?:&nbsp;Length,<br/>right?:&nbsp;Length,<br/>bottom?:&nbsp;Length,<br/>left?:&nbsp;Length<br/>}<br/>\|&nbsp;Length | 0 | 设置外边距属性。<br/>参数为Length类型时,四个方向外边距同时生效。 | | margin | [Margin](ts-types.md#margin)&nbsp;\|&nbsp;[Length](ts-types.md#length) | 设置外边距属性。<br/>参数为Length类型时,四个方向外边距同时生效。<br/>默认值:0 |
| constraintSize | {<br/>minWidth?:&nbsp;Length,<br/>maxWidth?:&nbsp;Length,<br/>minHeight?:&nbsp;Length,<br/>maxHeight?:&nbsp;Length<br/>} | {<br/>minWidth:&nbsp;0,<br/>maxWidth:&nbsp;Infinity,<br/>minHeight:&nbsp;0,<br/>maxHeight:&nbsp;Infinity<br/>} | 设置约束尺寸,组件布局时,进行尺寸范围限制。 | | constraintSize | {<br/>minWidth?:&nbsp;[Length](ts-types.md#length),<br/>maxWidth?:&nbsp;[Length](ts-types.md#length),<br/>minHeight?:&nbsp;[Length](ts-types.md#length),<br/>maxHeight?:&nbsp;[Length](ts-types.md#length)<br/>} | 设置约束尺寸,组件布局时,进行尺寸范围限制。<br/>默认值:<br/>{<br/>minWidth:&nbsp;0,<br/>maxWidth:&nbsp;Infinity,<br/>minHeight:&nbsp;0,<br/>maxHeight:&nbsp;Infinity<br/>} |
| layoutWeight | number | 0 | 容器尺寸确定时,元素与兄弟节点主轴布局尺寸按照权重进行分配,忽略本身尺寸设置,表示自适应占满剩余空间。<br/>>&nbsp;&nbsp;**说明:**<br/>>&nbsp;仅在Row/Column/Flex布局中生效。 | | layoutWeight | number&nbsp;\|&nbsp;string | 容器尺寸确定时,元素与兄弟节点主轴布局尺寸按照权重进行分配,忽略本身尺寸设置,表示自适应占满剩余空间。<br/>默认值:0<br/>**说明:**<br/>仅在Row/Column/Flex布局中生效。 |
## 示例 ## 示例
......
# 触摸热区设置 # 触摸热区设置
适用于支持通用点击事件、通用触摸事件、通用手势处理的组件。
> **说明:** > **说明:**
> >
> 从API Version 8开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 > 从API Version 8开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
适用于支持通用点击事件、通用触摸事件、通用手势处理的组件。
## 权限列表
## 属性 ## 属性
| 名称 | 参数类型 | 默认值 | 描述 | | 名称 | 参数类型 | 描述 |
| -------------- | ---------------------------------------- | ---------------------------------------- | ---------------------------------------- | | -------------- | --------------------------------------------- | ------------------------------------------------------------ |
| responseRegion | Array&lt;Rectangle&gt;&nbsp;\|&nbsp;Rectangle | {<br/>x:0,<br/>y:0,<br/>width:'100%',<br/>height:'100%'<br/>} | 设置一个或多个触摸热区,包括位置和大小。<br/>>&nbsp;&nbsp;**说明:**<br/>>&nbsp;-百分比是相对于组件本身来度量的。<br/>>&nbsp;-x和y可以设置正负值百分比。当x设置为'100%'时表示热区往右偏移组件本身宽度大小,当x设置为'-100%'时表示热区往左偏移组件本身宽度大小。当y设置为'100%'时表示热区往下偏移组件本身高度大小,当y设置为'-100%'时表示热区往上偏移组件本身高度大小。<br/>>&nbsp;-width和height只能设置正值百分比。width:'100%'表示热区宽度设置为该组件本身的宽度。比如组件本身宽度是100vp,那么'100%'表示热区宽度也为100vp。height:'100%'表示热区高度设置为该组件本身的高度。 | | responseRegion | Array&lt;Rectangle&gt;&nbsp;\|&nbsp;Rectangle | 设置一个或多个触摸热区,包括位置和大小。<br/>默认值:<br/>{<br/>x:0,<br/>y:0,<br/>width:'100%',<br/>height:'100%'<br/>} |
### Rectangle对象说明 ### Rectangle对象说明
| 名称 | 类型 | 必填 | 默认值 | 描述 | | 名称 | 类型 | 必填 | 默认值 | 描述 |
| ------ | ------ | ---- | ---- | ------------------ | | ------ | ---------------------------- | ---- | ------ | --------------------------------------------------- |
| x | Length | 否 | 0vp | 触摸点相对于组件本身左边沿的X坐标。 | | x | [Length](ts-types.md#length) | 否 | 0vp | 触摸点相对于组件本身左边沿的X坐标。<br/>默认值:0vp |
| y | Length | 否 | 0vp | 触摸点相对于组件本身左边沿的Y坐标。 | | y | [Length](ts-types.md#length) | 否 | 0vp | 触摸点相对于组件本身左边沿的Y坐标。<br/>默认值:0vp |
| width | Length | 否 | 100% | 触摸热区范围的宽度。 | | width | [Length](ts-types.md#length) | 否 | 100% | 触摸热区范围的宽度。<br/>默认值:100% |
| height | Length | 否 | 100% | 触摸热区范围的高度。 | | height | [Length](ts-types.md#length) | 否 | 100% | 触摸热区范围的高度。<br/>默认值:100% |
> **说明:** > **说明:**
> >
> 当x和y都设置为正值时,表示组件的触摸热区的范围整体往组件本身右下角偏移,偏移的大小可通过数值来设置。 > x和y可以设置正负值百分比。当x设置为'100%'时表示热区往右偏移组件本身宽度大小,当x设置为'-100%'时表示热区往左偏移组件本身宽度大小。当y设置为'100%'时表示热区往下偏移组件本身高度大小,当y设置为'-100%'时表示热区往上偏移组件本身高度大小。
>
> width和height只能设置正值百分比。width:'100%'表示热区宽度设置为该组件本身的宽度。比如组件本身宽度是100vp,那么'100%'表示热区宽度也为100vp。height:'100%'表示热区高度设置为该组件本身的高度。
>
> 百分比是相对于组件本身来度量的。
## 示例 ## 示例
......
...@@ -5,26 +5,22 @@ ...@@ -5,26 +5,22 @@
> 从API Version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 > 从API Version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
## 权限列表
## 事件 ## 事件
| 名称 | 支持冒泡 | 功能描述 | | 名称 | 支持冒泡 | 功能描述 |
| ---------------------------------------- | ---- | --------------------------------- | | ------------------------------------------------------------ | -------- | --------------------------------------------------- |
| onClick(callback:&nbsp;(event?:&nbsp;ClickEvent)&nbsp;=&gt;&nbsp;void) | 否 | 点击动作触发该方法调用,event参数见ClickEvent介绍。 | | onClick(event:&nbsp;(event?:&nbsp;ClickEvent)&nbsp;=&gt;&nbsp;void) | 否 | 点击动作触发该方法调用,event参数见ClickEvent介绍。 |
## ClickEvent对象说明 ## ClickEvent对象说明
| 属性名称 | 类型 | 描述 | | 属性名称 | 类型 | 描述 |
| ------------------- | -------------------------------- | ------------------- | | ---------------------- | ------------------------------------ | ------------------------------------- |
| screenX | number | 点击点相对于设备屏幕左边沿的X坐标。 | | screenX | number | 点击点相对于设备屏幕左边沿的X坐标。 |
| screenY | number | 点击点相对于设备屏幕上边沿的Y坐标。 | | screenY | number | 点击点相对于设备屏幕上边沿的Y坐标。 |
| x | number | 点击点相对于被点击元素左边沿的X坐标。 | | x | number | 点击点相对于被点击元素左边沿的X坐标。 |
| y | number | 点击点相对于被点击元素上边沿的Y坐标。 | | y | number | 点击点相对于被点击元素上边沿的Y坐标。 |
| target<sup>8+</sup> | [EventTarget](#eventtarget8对象说明) | 被点击元素对象。 | | target<sup>8+</sup> | [EventTarget](#eventtarget8对象说明) | 被点击元素对象。 |
| timestamp | number | 事件时间戳。 | | timestamp<sup>8+</sup> | number | 事件时间戳。 |
| source<sup>8+</sup> | [SourceType](ts-gesture-settings.md) | 事件输入设备。 |
## EventTarget<sup>8+</sup>对象说明 ## EventTarget<sup>8+</sup>对象说明
| 名称 | 参数类型 | 描述 | | 名称 | 参数类型 | 描述 |
......
...@@ -21,23 +21,16 @@ ...@@ -21,23 +21,16 @@
## KeyEvent对象说明 ## KeyEvent对象说明
### 属性 | 名称 | 类型 | 描述 |
| ------------------------------------- | --------------------------- | -------------------------- |
| 属性名称 | 类型 | 描述 | | type | [KeyType](ts-appendix-enums.md#keytype) | 按键的类型。 |
| ------------------------------------- | --------------------------- | -------------------------- | | [keyCode](../apis/js-apis-keycode.md) | number | 按键的键码。 |
| type | [KeyType](ts-appendix-enums.md#keytype) | 按键的类型。 | | keyText | string | 按键的键值。 |
| [keyCode](../apis/js-apis-keycode.md) | number | 按键的键码。 | | keySource | [KeySource](ts-appendix-enums.md#keysource) | 触发当前按键的输入设备类型。 |
| keyText | string | 按键的键值。 | | deviceId | number | 触发当前按键的输入设备ID。 |
| keySource | [KeySource](ts-appendix-enums.md#keysource) | 触发当前按键的输入设备类型。 | | metaKey | number | 按键发生时元键的状态,1表示按压态,0表示未按压态。 |
| deviceId | number | 触发当前按键的输入设备ID。 | | timestamp | number | 按键发生时的时间戳。 |
| metaKey | number | 按键发生时元键的状态,1表示按压态,0表示未按压态。 | | stopPropagation | () => void | 阻塞事件冒泡传递。 |
| timestamp | number | 按键发生时的时间戳。 |
### 接口
| 接口名称 | 功能描述 |
| ---------------------------- | --------- |
| stopPropagation():&nbsp;void | 阻塞事件冒泡传递。 |
## 示例 ## 示例
......
...@@ -5,38 +5,29 @@ ...@@ -5,38 +5,29 @@
> 从API Version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 > 从API Version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
## 权限列表
## 事件 ## 事件
| 名称 | 是否冒泡 | 功能描述 | | 名称 | 是否冒泡 | 功能描述 |
| ---------------------------------------- | ---- | ---------------------------------------- | | ------------------------------------------------------------ | -------- | ------------------------------------------------------------ |
| onTouch(callback:&nbsp;(event?:&nbsp;TouchEvent)&nbsp;=&gt;&nbsp;void) | 是 | 触摸动作触发该方法调用,event参数见[TouchEvent](#touchevent对象说明)介绍。 | | onTouch(event:&nbsp;(event?:&nbsp;TouchEvent)&nbsp;=&gt;&nbsp;void) | 是 | 触摸动作触发该方法调用,event参数见[TouchEvent](#touchevent对象说明)介绍。 |
## TouchEvent对象说明 ## TouchEvent对象说明
### 属性 | 名称 | 类型 | 描述 |
| ------------------- | ---------------------------------------- | ------------ |
| type | [TouchType](ts-appendix-enums.md#touchtype) | 触摸事件的类型。 |
| touches | Array&lt;[TouchObject](#touchobject对象说明)&gt; | 全部手指信息。 |
| changedTouches | Array&lt;[TouchObject](#touchobject对象说明)&gt; | 当前发生变化的手指信息。 |
| stopPropagation | () => void | 阻塞事件冒泡。 |
| timestamp<sup>8+</sup> | number | 事件时间戳。 |
| target<sup>8+</sup> | [EventTarget](ts-universal-events-click.md) | 触发手势事件的元素对象显示区域。 |
| source<sup>8+</sup> | [SourceType](ts-gesture-settings.md) | 事件输入设备。 |
| 属性名称 | 类型 | 描述 |
| ------------------- | ------------------------------------------------------------ | ---------------------------------- |
| type | [TouchType](ts-appendix-enums.md#touchtype) | 触摸事件的类型。 |
| touches | Array&lt;[TouchObject](#touchobject对象说明)&gt; | 全部手指信息。 |
| changedTouches | Array&lt;[TouchObject](#touchobject对象说明)&gt; | 当前发生变化的手指信息。 |
| timestamp | number | 距离开机时间的时间戳,单位为毫秒。 |
| target<sup>8+</sup> | [EventTarget](ts-universal-events-click.md#eventtarget8对象说明) | 被触摸元素对象。 |
### 接口
| 接口名称 | 功能描述 |
| ---------------------- | ------- |
| stopPropagation():void | 阻塞事件冒泡。 |
## TouchObject对象说明 ## TouchObject对象说明
| 属性名称 | 类型 | 描述 |
| 名称 | 类型 | 描述 |
| ------- | --------------------------- | ------------------- | | ------- | --------------------------- | ------------------- |
| type | [TouchType](ts-appendix-enums.md#touchtype) | 触摸事件的类型。 | | type | [TouchType](ts-appendix-enums.md#touchtype) | 触摸事件的类型。 |
| id | number | 手指唯一标识符。 | | id | number | 手指唯一标识符。 |
......
...@@ -5,29 +5,28 @@ ...@@ -5,29 +5,28 @@
> 从API Version 8开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 > 从API Version 8开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
## 权限列表
## 事件 ## 事件
| 名称 | 支持冒泡 | 描述 | | 名称 | 支持冒泡 | 描述 |
| ---------------------------------------- | ---- | ---------------------------------------- | | ------------------------------------------------------------ | -------- | ------------------------------------------------------------ |
| onHover(callback:&nbsp;(isHover:&nbsp;boolean)&nbsp;=&gt;&nbsp;void) | 否 | 鼠标进入或退出组件时触发该回调。<br/>isHover:表示鼠标是否悬浮在组件上,鼠标进入时为true,&nbsp;退出时为false。 | | onHover(event:&nbsp;(isHover:&nbsp;boolean)&nbsp;=&gt;&nbsp;void) | 否 | 鼠标进入或退出组件时触发该回调。<br/>isHover:表示鼠标是否悬浮在组件上,鼠标进入时为true,&nbsp;退出时为false。 |
| onMouse(callback:&nbsp;(event?:&nbsp;MouseEvent)&nbsp;=&gt;&nbsp;void) | 是 | 当前组件被鼠标按键点击时或者鼠标在组件上移动时,触发该回调,event参数包含触发事件时的时间戳、鼠标按键、动作、点击触点在整个屏幕上的坐标和点击触点相对于当前组件的坐标。 | | onMouse(event:&nbsp;(event?:&nbsp;MouseEvent)&nbsp;=&gt;&nbsp;void) | 是 | 当前组件被鼠标按键点击时或者鼠标在组件上移动时,触发该回调,event参数包含触发事件时的时间戳、鼠标按键、动作、点击触点在整个屏幕上的坐标和点击触点相对于当前组件的坐标。 |
## MouseEvent对象说明 ## MouseEvent对象说明
| 属性名称 | 属性类型 | 描述 |
| 名称 | 属性类型 | 描述 |
| --------- | ------------------------------- | -------------------- | | --------- | ------------------------------- | -------------------- |
| timestamp | number | 触发事件时的时间戳。 |
| screenX | number | 点击触点相对于屏幕左上角的x轴坐标。 | | screenX | number | 点击触点相对于屏幕左上角的x轴坐标。 |
| screenY | number | 点击触点相对于屏幕左上角的y轴坐标。 | | screenY | number | 点击触点相对于屏幕左上角的y轴坐标。 |
| x | number | 点击触点相对于当前组件左上角的x轴坐标。 | | x | number | 点击触点相对于当前组件左上角的x轴坐标。 |
| y | number | 点击触点相对于当前组件左上角的y轴坐标。 | | y | number | 点击触点相对于当前组件左上角的y轴坐标。 |
| button | [MouseButton](ts-appendix-enums.md#mousebutton) | 鼠标按键。 | | button | [MouseButton](ts-appendix-enums.md#mousebutton) | 鼠标按键。 |
| action | [MouseAction](ts-appendix-enums.md#mouseaction) | 事件动作。 | | action | [MouseAction](ts-appendix-enums.md#mouseaction) | 事件动作。 |
| stopPropagation | () => void | 阻塞事件冒泡。 |
| timestamp<sup>8+</sup> | number | 事件时间戳。 |
| target<sup>8+</sup> | [EventTarget](ts-universal-events-click.md) | 触发手势事件的元素对象显示区域。 |
| source<sup>8+</sup> | [SourceType](ts-gesture-settings.md) | 事件输入设备。 |
## 示例 ## 示例
......
...@@ -195,7 +195,7 @@ import featureAbility from '@ohos.ability.featureAbility'; ...@@ -195,7 +195,7 @@ import featureAbility from '@ohos.ability.featureAbility';
import wantAgent from '@ohos.wantAgent'; import wantAgent from '@ohos.wantAgent';
import rpc from "@ohos.rpc"; import rpc from "@ohos.rpc";
function startBackgroundRunning() { function startContinuousTask() {
let wantAgentInfo = { let wantAgentInfo = {
// 点击通知后,将要执行的动作列表 // 点击通知后,将要执行的动作列表
wants: [ wants: [
...@@ -223,7 +223,7 @@ function startBackgroundRunning() { ...@@ -223,7 +223,7 @@ function startBackgroundRunning() {
}); });
} }
function stopBackgroundRunning() { function stopContinuousTask() {
backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext()).then(() => { backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext()).then(() => {
console.info("Operation stopBackgroundRunning succeeded"); console.info("Operation stopBackgroundRunning succeeded");
}).catch((err) => { }).catch((err) => {
...@@ -231,6 +231,13 @@ function stopBackgroundRunning() { ...@@ -231,6 +231,13 @@ function stopBackgroundRunning() {
}); });
} }
async function processAsyncJobs() {
// 此处执行具体的长时任务。
// 长时任务执行完,调用取消接口,释放资源。
stopContinuousTask();
}
let mMyStub; let mMyStub;
class MyStub extends rpc.RemoteObject { class MyStub extends rpc.RemoteObject {
...@@ -262,9 +269,9 @@ export default { ...@@ -262,9 +269,9 @@ export default {
onStart(want) { onStart(want) {
console.info('ServiceAbility onStart'); console.info('ServiceAbility onStart');
mMyStub = new MyStub("ServiceAbility-test"); mMyStub = new MyStub("ServiceAbility-test");
startBackgroundRunning(); // 在执行后台长时任前,调用申请接口。
// 此处执行后台具体的长时任务。 startContinuousTask();
stopBackgroundRunning(); processAsyncJobs();
}, },
onStop() { onStop() {
console.info('ServiceAbility onStop'); console.info('ServiceAbility onStop');
......
...@@ -22,5 +22,5 @@ ...@@ -22,5 +22,5 @@
**Misc软件服务子系统** **Misc软件服务子系统**
miscservices\_time [time_time_service](https://gitee.com/openharmony/time_time_service)
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册