diff --git a/en/application-dev/application-models/js-ui-widget-development.md b/en/application-dev/application-models/js-ui-widget-development.md index cb8a2287992a55fb960672b078e6d0d20f6ec1b1..178aa903a36b6a4742645cfab82a390364db0b37 100644 --- a/en/application-dev/application-models/js-ui-widget-development.md +++ b/en/application-dev/application-models/js-ui-widget-development.md @@ -16,13 +16,13 @@ The widget host consists of the following modules: - Widget usage: provides operations such as creating, deleting, or updating a widget. -- Communication adapter: provided by the OpenHarmony SDK for communication with the Widget Manager. It sends widget-related operations to the Widget Manager. +- Communication adapter: provided by the SDK for communication with the Widget Manager. It sends widget-related operations to the Widget Manager. The Widget Manager consists of the following modules: - Periodic updater: starts a scheduled task based on the update policy to periodically update a widget after it is added to the Widget Manager. -- Cache manager: caches view information of a widget after it is added to the Widget Manager to directly return the cached data when the widget is obtained next time. This reduces the latency greatly. +- Cache manager: caches view information of a widget after it is added to the Widget Manager. This enables the cached data to be directly returned when the widget is obtained next time, greatly reducing the latency. - Lifecycle manager: suspends update when a widget is switched to the background or is blocked, and updates and/or clears widget data during upgrade and deletion. @@ -36,9 +36,10 @@ The widget provider consists of the following modules: - Instance manager: implemented by the widget provider developer for persistent management of widget instances allocated by the Widget Manager. -- Communication adapter: provided by the OpenHarmony SDK for communication with the Widget Manager. It pushes update data to the Widget Manager. +- Communication adapter: provided by the SDK for communication with the Widget Manager. It pushes update data to the Widget Manager. > **NOTE** +> > You only need to develop the widget provider. The system automatically handles the work of the widget host and Widget Manager. @@ -48,14 +49,14 @@ The **FormExtensionAbility** class has the following APIs. For details, see [For | Name| Description| | -------- | -------- | -| onAddForm(want: Want): formBindingData.FormBindingData | Called to notify the widget provider that a widget has been created.| -| onCastToNormalForm(formId: string): void | Called to notify the widget provider that a temporary widget has been converted to a normal one.| -| onUpdateForm(formId: string): void | Called to notify the widget provider that a widget has been updated.| -| onChangeFormVisibility(newStatus: { [key: string]: number }): void | Called to notify the widget provider of the change in widget visibility.| -| onFormEvent(formId: string, message: string): void | Called to instruct the widget provider to receive and process a widget event.| -| onRemoveForm(formId: string): void | Called to notify the widget provider that a widget has been destroyed.| -| onConfigurationUpdate(config: Configuration): void | Called when the configuration of the environment where the widget is running is updated.| -| onShareForm?(formId: string): { [key: string]: any } | Called by the widget provider to receive shared widget data.| +| onAddForm(want: Want): formBindingData.FormBindingData | Called to notify the widget provider that a widget is being created.| +| onCastToNormalForm(formId: string): void | Called to notify the widget provider that a temporary widget is being converted to a normal one.| +| onUpdateForm(formId: string): void | Called to notify the widget provider that a widget is being updated.| +| onChangeFormVisibility(newStatus: { [key: string]: number }): void | Called to notify the widget provider that the widget visibility status is being changed.| +| onFormEvent(formId: string, message: string): void | Called to instruct the widget provider to process a widget event.| +| onRemoveForm(formId: string): void | Called to notify the widget provider that a widget is being destroyed.| +| onConfigurationUpdate(config: Configuration): void | Called when the configuration of the environment where the widget is running is being updated.| +| onShareForm?(formId: string): { [key: string]: any } | Called to notify the widget provider that the widget host is sharing the widget data.| The **FormProvider** class has the following APIs. For details, see [FormProvider](../reference/apis/js-apis-app-form-formProvider.md). @@ -81,9 +82,9 @@ The widget provider development based on the [stage model](stage-model-developme - [Configuring the Widget Configuration Files](#configuring-the-widget-configuration-files): Configure the application configuration file **module.json5** and profile configuration file. -- [Persistently Storing Widget Data](#persistently-storing-widget-data): This operation is a form of widget data exchange. +- [Persistently Storing Widget Data](#persistently-storing-widget-data): Manage widget data persistence. -- [Updating Widget Data](#updating-widget-data): Call **updateForm()** to update the information displayed on a widget. +- [Updating Widget Data](#updating-widget-data): Call **updateForm()** to update the information displayed in a widget. - [Developing the Widget UI Page](#developing-the-widget-ui-page): Use HML+CSS+JSON to develop a JS widget UI page. @@ -92,7 +93,7 @@ The widget provider development based on the [stage model](stage-model-developme ### Creating a FormExtensionAbility Instance -To create a widget in the stage model, implement the lifecycle callbacks of **FormExtensionAbility**. Generate a widget template by referring to [Developing a Service Widget](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-development-service-widget-0000001263280425). +To create a widget in the stage model, you need to implement the lifecycle callbacks of FormExtensionAbility. Generate a widget template and then perform the following: 1. Import related modules to **EntryFormAbility.ts**. @@ -102,7 +103,7 @@ To create a widget in the stage model, implement the lifecycle callbacks of **Fo import formBindingData from '@ohos.app.form.formBindingData'; import formInfo from '@ohos.app.form.formInfo'; import formProvider from '@ohos.app.form.formProvider'; - import dataStorage from '@ohos.data.storage'; + import dataPreferences from '@ohos.data.preferences'; ``` 2. Implement the FormExtension lifecycle callbacks in **EntryFormAbility.ts**. @@ -121,7 +122,7 @@ To create a widget in the stage model, implement the lifecycle callbacks of **Fo return formData; } onCastToNormalForm(formId) { - // Called when the widget host converts the temporary widget into a normal one. The widget provider should do something to respond to the conversion. + // Called when a temporary widget is being converted into a normal one. The widget provider should respond to the conversion. console.info('[EntryFormAbility] onCastToNormalForm'); } onUpdateForm(formId) { @@ -158,6 +159,7 @@ To create a widget in the stage model, implement the lifecycle callbacks of **Fo ``` > **NOTE** +> > FormExtensionAbility cannot reside in the background. Therefore, continuous tasks cannot be processed in the widget lifecycle callbacks. @@ -190,7 +192,7 @@ To create a widget in the stage model, implement the lifecycle callbacks of **Fo } ``` -2. Configure the widget configuration information. In the **metadata** configuration item of FormExtensionAbility, you can specify the resource index of specific configuration information of the widget. For example, if resource is set to **$profile:form_config**, **form_config.json** in the **resources/base/profile/** directory of the development view is used as the profile configuration file of the widget. The following table describes the internal field structure. +2. Configure the widget configuration information. In the **metadata** configuration item of FormExtensionAbility, you can specify the resource index of specific configuration information of the widget. For example, if **resource** is set to **$profile:form_config**, **form_config.json** in the **resources/base/profile/** directory of the development view is used as the profile configuration file of the widget. The following table describes the internal structure of the profile configuration file. **Table 1** Widget profile configuration file @@ -204,7 +206,7 @@ To create a widget in the stage model, implement the lifecycle callbacks of **Fo | colorMode | Color mode of the widget.
- **auto**: auto-adaptive color mode
- **dark**: dark color mode
- **light**: light color mode| String| Yes (initial value: **auto**)| | supportDimensions | Grid styles supported by the widget.
- **1 * 2**: indicates a grid with one row and two columns.
- **2 * 2**: indicates a grid with two rows and two columns.
- **2 * 4**: indicates a grid with two rows and four columns.
- **4 * 4**: indicates a grid with four rows and four columns.| String array| No| | defaultDimension | Default grid style of the widget. The value must be available in the **supportDimensions** array of the widget.| String| No| - | updateEnabled | Whether the widget can be updated periodically.
- **true**: The widget can be updated at a specified interval (**updateDuration**) or at the scheduled time (**scheduledUpdateTime**). **updateDuration** takes precedence over **scheduledUpdateTime**.
- **false**: The widget cannot be updated periodically.| Boolean| No| + | updateEnabled | Whether the widget can be updated periodically.
- **true**: The widget can be updated at a specified interval (**updateDuration**) or at the scheduled time (**scheduledUpdateTime**). **updateDuration** takes precedence over **scheduledUpdateTime**. If both are specified, the value specified by **updateDuration** is used.
- **false**: The widget cannot be updated periodically.| Boolean| No| | scheduledUpdateTime | Scheduled time to update the widget. The value is in 24-hour format and accurate to minute.
**updateDuration** takes precedence over **scheduledUpdateTime**. If both are specified, the value specified by **updateDuration** is used.| String| Yes (initial value: **0:0**)| | updateDuration | Interval to update the widget. The value is a natural number, in the unit of 30 minutes.
If the value is **0**, this field does not take effect.
If the value is a positive integer *N*, the interval is calculated by multiplying *N* and 30 minutes.
**updateDuration** takes precedence over **scheduledUpdateTime**. If both are specified, the value specified by **updateDuration** is used.| Number| Yes (initial value: **0**)| | formConfigAbility | Link to a specific page of the application. The value is a URI.| String| Yes (initial value: left empty)| @@ -255,7 +257,7 @@ async function storeFormInfo(formId: string, formName: string, tempFlag: boolean "updateCount": 0 }; try { - const storage = await dataStorage.getStorage(DATA_STORAGE_PATH); + const storage = await dataPreferences.getPreferences(this.context, DATA_STORAGE_PATH); // put form info await storage.put(formId, JSON.stringify(formInfo)); console.info(`[EntryFormAbility] storeFormInfo, put form info successfully, formId: ${formId}`); @@ -294,8 +296,8 @@ You should override **onRemoveForm** to implement widget data deletion. const DATA_STORAGE_PATH = "/data/storage/el2/base/haps/form_store"; async function deleteFormInfo(formId: string) { try { - const storage = await dataStorage.getStorage(DATA_STORAGE_PATH); - // del form info + const storage = await dataPreferences.getPreferences(this.context, DATA_STORAGE_PATH); + // Delete the widget information. await storage.delete(formId); console.info(`[EntryFormAbility] deleteFormInfo, del form info successfully, formId: ${formId}`); await storage.flush(); @@ -317,7 +319,7 @@ export default class EntryFormAbility extends FormExtension { } ``` -For details about how to implement persistent data storage, see [Persisting Preferences Data](../database/data-persistence-by-preferences.md). +For details about how to implement persistent data storage, see [Application Data Persistence](../database/app-data-persistence-overview.md). The **Want** object passed in by the widget host to the widget provider contains a flag that specifies whether the requested widget is normal or temporary. @@ -449,14 +451,14 @@ The key steps are as follows: - **action**: **"router"**, which indicates a router event. - **abilityName**: name of the UIAbility to redirect to (PageAbility component in the FA model and UIAbility component in the stage model). For example, the default UIAbility name of the stage model created by DevEco Studio is EntryAbility. - - **params**: custom parameters passed to the target UIAbility. Set them as required. The value can be obtained from **parameters** in **want** used for starting the target UIAbility. For example, in the lifecycle function **onCreate** of the main ability in the stage model, you can obtain **want** and its **parameters** field. + - **params**: custom parameters passed to the target UIAbility. Set them as required. The value can be obtained from **parameters** in **want** used for starting the target UIAbility. For example, in the lifecycle function **onCreate** of the MainAbility in the stage model, you can obtain **want** and its **parameters** field. 3. Set the message event. - **action**: **"message"**, which indicates a message event. - **params**: custom parameters of the message event. Set them as required. The value can be obtained from **message** in the widget lifecycle function **onFormEvent()**. -The following is an example: +The following are examples: - HML file: @@ -545,7 +547,7 @@ The following is an example: } ``` -- Receive the router event and obtain parameters in UIAbility. +- Receive the router event in UIAbility and obtain parameters. ```ts diff --git a/en/application-dev/reference/apis/js-apis-arkui-componentSnapshot.md b/en/application-dev/reference/apis/js-apis-arkui-componentSnapshot.md index b6a2b41d6c9b9ed05603c68f94d8f53426570414..1a1972d66c2648ae0776cbd12d5dc7b769186414 100644 --- a/en/application-dev/reference/apis/js-apis-arkui-componentSnapshot.md +++ b/en/application-dev/reference/apis/js-apis-arkui-componentSnapshot.md @@ -34,6 +34,12 @@ Obtains the snapshot of a component that has been loaded. This API uses an async | id | string | Yes | [ID](../arkui-ts/ts-universal-attributes-component-id.md) of the target component.| | callback | AsyncCallback<image.PixelMap> | Yes | Callback used to return the result. | +**Error codes** + +| ID| Error Message | +| -------- | ------------------- | +| 100001 | if id is not valid. | + **Example** ```js @@ -159,6 +165,12 @@ Renders a custom component in the application background and outputs its snapsho | builder | [CustomBuilder](../arkui-ts/ts-types.md#custombuilder8) | Yes | Builder of the custom component.| | callback | AsyncCallback<image.PixelMap> | Yes | Callback used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | ----------------------------------------- | +| 100001 | if builder is not a valid build function. | + **Example** ```ts diff --git a/en/application-dev/reference/apis/js-apis-font.md b/en/application-dev/reference/apis/js-apis-font.md index 721fd187c6f86f786159c6569d55e8354d63d786..ce578a35c157539965e3ea810dbc7d646ed83580 100644 --- a/en/application-dev/reference/apis/js-apis-font.md +++ b/en/application-dev/reference/apis/js-apis-font.md @@ -6,7 +6,6 @@ The **font** module provides APIs for registering custom fonts. > > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > -> The APIs provided by this module are system APIs. ## Modules to Import @@ -30,12 +29,14 @@ Registers a custom font with the font manager. ## FontOptions +**System capability**: SystemCapability.ArkUI.ArkUI.Full + | Name | Type | Mandatory | Description | | ---------- | ------ | ---- | ------------ | | familyName | string | Yes | Name of the custom font to register. | | familySrc | string | Yes | Path of the custom font to register.| -## Example +**Example** ```ts // xxx.ets diff --git a/en/application-dev/reference/apis/js-apis-matrix4.md b/en/application-dev/reference/apis/js-apis-matrix4.md index 9c8c1a77c0150f8d820ec03701c3bd58ad9c8a17..e2de4ddcedf439f08598e5aa6b7eaca294fb936c 100644 --- a/en/application-dev/reference/apis/js-apis-matrix4.md +++ b/en/application-dev/reference/apis/js-apis-matrix4.md @@ -16,7 +16,7 @@ import matrix4 from '@ohos.matrix4' ## matrix4.init -init(option: [number,number,number,number,number,number,number,number,number,number,number,number,number,number,number,number]): Matrix4Transit +init(options: [number,number,number,number,number,number,number,number,number,number,number,number,number,number,number,number]): Matrix4Transit Matrix constructor, which is used to create a 4 x 4 matrix by using the input parameter. Column-major order is used. @@ -27,7 +27,7 @@ Matrix constructor, which is used to create a 4 x 4 matrix by using the input pa | Name| Type | Mandatory| Description | | ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| option | [number,number,number,number,number,number,number,number,number,number,number,number,number,number,number,number] | Yes | A number array whose length is 16 (4 x 4). For details, see **Description of a 4 x 4 matrix**.
Default value:
[1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1] | +| option | [number,number,number,number,number,number,number,number,number,number,number,number,number,number,number,number] | Yes | A number array whose length is 16 (4 x 4). For details, see **Description of a 4 x 4 matrix**.
Default value:
[1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1] | **Return value** @@ -176,7 +176,7 @@ struct Test { ### combine -combine(option: Matrix4Transit): Matrix4Transit +combine(options: Matrix4Transit): Matrix4Transit Combines the effects of two matrices to generate a new matrix object. @@ -273,7 +273,7 @@ struct Tests { ### translate -translate(option: TranslateOption): Matrix4Transit +translate(options: TranslateOption): Matrix4Transit Translates this matrix object along the x, y, and z axes. @@ -317,7 +317,7 @@ struct Test { ### scale -scale(option: ScaleOption): Matrix4Transit +scale(options: ScaleOption): Matrix4Transit Scales this matrix object along the x, y, and z axes. @@ -362,7 +362,7 @@ struct Test { ### rotate -rotate(option: RotateOption): Matrix4Transit +rotate(options: RotateOption): Matrix4Transit Rotates this matrix object along the x, y, and z axes. @@ -408,7 +408,7 @@ struct Test { ### transformPoint -transformPoint(option: [number, number]): [number, number] +transformPoint(options: [number, number]): [number, number] Applies the current transformation effect to a coordinate point. @@ -466,15 +466,19 @@ struct Test { ## TranslateOption +**System capability**: SystemCapability.ArkUI.ArkUI.Full + | Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ----------------------------------------------------------- | -| x | number | No | Translation distance along the x-axis, in px.
Default value: **0**
Value range: (-∞, +∞)| -| y | number | No | Translation distance along the y-axis, in px.
Default value: **0**
Value range: (-∞, +∞)| -| z | number | No | Translation distance along the z-axis, in px.
Default value: **0**
Value range: (-∞, +∞)| +| ---- | ------ | ---- | ----------------------------------------------------------- | +| x | number | No | Translation distance along the x-axis, in px.
Default value: **0**
Value range: (-∞, +∞)| +| y | number | No | Translation distance along the y-axis, in px.
Default value: **0**
Value range: (-∞, +∞)| +| z | number | No | Translation distance along the z-axis, in px.
Default value: **0**
Value range: (-∞, +∞)| ## ScaleOption -| Name | Type | Mandatory| Description | +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory| Description | | ------- | ------ | ---- | ------------------------------------------------------------ | | x | number | No | Scaling multiple along the x-axis. If the value is greater than 1, the image is scaled up along the x-axis. If the value is less than 1, the image is scaled down along the x-axis.
Default value: **1**
Value range: [0, +∞)
**NOTE**
A value less than 0 evaluates to the default value.| | y | number | No | Scaling multiple along the y-axis. If the value is greater than 1, the image is scaled up along the y-axis. If the value is less than 1, the image is scaled down along the y-axis.
Default value: **1**
Value range: [0, +∞)
**NOTE**
A value less than 0 evaluates to the default value.| @@ -484,7 +488,9 @@ struct Test { ## RotateOption -| Name | Type | Mandatory| Description | +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory| Description | | ------- | ------ | ---- | ------------------------------------------------------- | | x | number | No | X coordinate of the rotation axis vector.
Default value: **1**
Value range: (-∞, +∞)| | y | number | No | Y coordinate of the rotation axis vector.
Default value: **1**
Value range: (-∞, +∞)| diff --git a/en/application-dev/reference/apis/js-apis-plugincomponent.md b/en/application-dev/reference/apis/js-apis-plugincomponent.md index 0ae1baf6eebdadbbdc9d43de1e9c100ac73163db..d6e63c978f5f9891858c102e161b3b9e7eddc29b 100644 --- a/en/application-dev/reference/apis/js-apis-plugincomponent.md +++ b/en/application-dev/reference/apis/js-apis-plugincomponent.md @@ -262,7 +262,7 @@ pluginComponentManager.push( name: "ets/pages/plugin2.js", data: { "js": "ets/pages/plugin.js", - "key_1": 1111, , + "key_1": 1111, }, extraData: { "extra_str": "this is push event" @@ -376,10 +376,24 @@ Listens for events of the request type and returns the requested data, or listen | eventType | string | Yes | Type of the event to listen for. The options are as follows:
**"push"**: The component provider pushes data to the component consumer.
**"request"**: The component consumer proactively requests data from the component provider.| | callback | [OnPushEventCallback](#onpusheventcallback) \| [OnRequestEventCallback](#onrequesteventcallback) | Yes | Callback used to return the result. The type is [OnPushEventCallback](#onpusheventcallback) for the push event and [OnRequestEventCallback](#onrequesteventcallback) for the request event.| - **Example** ```js +function onPushListener(source, template, data, extraData) { + console.log("onPushListener template.source=" + template.source) + console.log("onPushListener source=" + JSON.stringify(source)) + console.log("onPushListener template=" + JSON.stringify(template)) + console.log("onPushListener data=" + JSON.stringify(data)) + console.log("onPushListener extraData=" + JSON.stringify(extraData)) +} +function onRequestListener(source, name, data) { + console.error("onRequestListener"); + console.log("onRequestListener source=" + JSON.stringify(source)); + console.log("onRequestListener name=" + name); + console.log("onRequestListener data=" + JSON.stringify(data)); + + return { template: "ets/pages/plugin.js", data: data }; +} pluginComponentManager.on("push", onPushListener) pluginComponentManager.on("request", onRequestListener) ``` diff --git a/en/application-dev/reference/apis/js-apis-router.md b/en/application-dev/reference/apis/js-apis-router.md index 2020f98279bc94e3ba292ced7d156cc963f46dd6..4d4a69ae73087d5903bd1435122170a5fb16568c 100644 --- a/en/application-dev/reference/apis/js-apis-router.md +++ b/en/application-dev/reference/apis/js-apis-router.md @@ -671,7 +671,7 @@ struct Second { Text(this.text) .fontSize(30) .onClick(() => { - this.secondData = (this.data.['array'][1]).toString() + this.secondData = (this.data['array'][1]).toString() }) .margin({ top: 20 }) Text(`This is the data passed from the first page: ${this.secondData}`) diff --git a/en/application-dev/reference/apis/js-apis-uitest.md b/en/application-dev/reference/apis/js-apis-uitest.md index 673744bf89745e4b929bddf57db88f7de730c33f..f3ed68ea09339eec7f3b2901b7e3d2037bf47108 100644 --- a/en/application-dev/reference/apis/js-apis-uitest.md +++ b/en/application-dev/reference/apis/js-apis-uitest.md @@ -8,9 +8,9 @@ This module provides the following functions: - [Component9+](#component9): represents a component on the UI and provides APIs for obtaining component attributes, clicking a component, scrolling to search for a component, and text injection. - [Driver9+](#driver9): works as the entry class and provides APIs for features such as component matching/search, key injection, coordinate clicking/sliding, and screenshot. - [UiWindow9+](#uiwindow9): works as the entry class and provides APIs for obtaining window attributes, dragging windows, and adjusting window sizes. -- [By(deprecated)](#bydeprecated): provides UI component feature description APIs for component filtering and matching. This API is deprecated since API version 9. You are advised to use [On9+](#on9) instead. -- [UiComponent(deprecated)](#uicomponentdeprecated): represents a component on the UI and provides APIs for obtaining component attributes, clicking a component, scrolling to search for a component, and text injection. This API is deprecated since API version 9. You are advised to use [Component9+](#component9) instead. -- [UiDriver(deprecated)](#uidriverdeprecated): works as the entry class and provides APIs for features such as component matching/search, key injection, coordinate clicking/sliding, and screenshot. This API is deprecated since API version 9. You are advised to use [Driver9+](#driver9) instead. +- [By(deprecated)](#bydeprecated): provides UI component feature description APIs for component filtering and matching. This class is deprecated since API version 9. You are advised to use [On9+](#on9) instead. +- [UiComponent(deprecated)](#uicomponentdeprecated): represents a component on the UI and provides APIs for obtaining component attributes, clicking a component, scrolling to search for a component, and text injection. This class is deprecated since API version 9. You are advised to use [Component9+](#component9) instead. +- [UiDriver(deprecated)](#uidriverdeprecated): works as the entry class and provides APIs for features such as component matching/search, key injection, coordinate clicking/sliding, and screenshot. This class is deprecated since API version 9. You are advised to use [Driver9+](#driver9) instead. >**NOTE** > @@ -160,10 +160,8 @@ Since API version 9, the UiTest framework provides a wide range of UI component The API capabilities provided by the **On** class exhibit the following features: - Allow one or more attributes as the match conditions. For example, you can specify both the **text** and **id** attributes to find the target component. - - Provide multiple match patterns for component attributes. - -- Support absolute positioning and relative positioning for components. APIs such as [ON.isBefore](#isbefore9) and [ON.isAfter](#isafter9) can be used to specify the features of adjacent components to assist positioning. +- Support absolute positioning and relative positioning for components. APIs such as [ON.isBefore](#isbefore9) and [ON.isAfter](#isafter9) can be used to specify the features of adjacent components to assist positioning. All APIs provided in the **On** class are synchronous. You are advised to use the static constructor **ON** to create an **On** object in chain mode. @@ -1208,7 +1206,7 @@ For details about the error codes, see [UiTest Error Codes](../errorcodes/errorc ```js async function demo() { let driver = Driver.create(); - let button = await driver.findComponent(ON.type('Scroll')); + let scrollBar = await driver.findComponent(ON.type('Scroll')); let button = await scrollBar.scrollSearch(ON.text('next page')); } ``` @@ -2439,7 +2437,7 @@ For details about the error codes, see [UiTest Error Codes](../errorcodes/errorc ```js async function demo() { let driver = Driver.create(); - let obeserver = await driver.createUiEventObserve(); + let observer = await driver.createUIEventObserver() } ``` @@ -2950,7 +2948,7 @@ async function demo() { ## UIEventObserver10+ -UI event listener. +Implements a UI event listener. ### once('toastShow') @@ -2971,6 +2969,7 @@ Subscribes to events of the toast component. This API uses a callback to return ```js async function demo() { + let driver = Driver.create(); let observer = await driver.createUIEventObserver() let callback = (UIElementInfo)=>{ console.info(UIElementInfo.bundleName) @@ -3000,6 +2999,7 @@ Subscribes to events of the dialog component. This API uses a callback to return ```js async function demo() { + let driver = Driver.create(); let observer = await driver.createUIEventObserver() let callback = (UIElementInfo)=>{ console.info(UIElementInfo.bundleName) @@ -3013,15 +3013,16 @@ async function demo() { ## By(deprecated) The UiTest framework provides a wide range of UI component feature description APIs in the **By** class to filter and match components. -The API capabilities provided by the **By** class exhibit the following features: -- Allow one or more attributes as the match conditions. For example, you can specify both the **text** and **id** attributes to find the target component. +The API capabilities provided by the **By** class exhibit the following features: + +- Allow one or more attributes as the match conditions. For example, you can specify both the **text** and **id** attributes to find the target component. - Provide multiple match patterns for component attributes. - Support absolute positioning and relative positioning for components. APIs such as [By.isBefore(deprecated)](#isbeforedeprecated) and [By.isAfter(deprecated)](#isafterdeprecated) can be used to specify the features of adjacent components to assist positioning. All APIs provided in the **By** class are synchronous. You are advised to use the static constructor **BY** to create a **By** object in chain mode. -This API is deprecated since API version 9. You are advised to use [On9+](#on9) instead. +This class is deprecated since API version 9. You are advised to use [On9+](#on9) instead. ```js BY.text('123').type('button'); @@ -3347,7 +3348,7 @@ In **UiTest**, the **UiComponent** class represents a component on the UI and pr All APIs provided in this class use a promise to return the result and must be invoked using **await**. -This API is deprecated since API version 9. You are advised to use [Component9+](#component9) instead. +This class is deprecated since API version 9. You are advised to use [Component9+](#component9) instead. ### click(deprecated) @@ -3729,7 +3730,7 @@ The **UiDriver** class is the main entry to the UiTest framework. It provides AP All APIs provided by this class, except for **UiDriver.create()**, use a promise to return the result and must be invoked using **await**. -This API is deprecated since API version 9. You are advised to use [Driver9+](#driver9) instead. +This class is deprecated since API version 9. You are advised to use [Driver9+](#driver9) instead. ### create(deprecated) diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-text.md b/en/application-dev/reference/arkui-ts/ts-basic-components-text.md index 9a52243939d77e88ba48b793830784aa51ebc608..5acd3cadcecdbe3a0b9383419859e1d0061c97ab 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-text.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-text.md @@ -31,19 +31,19 @@ In addition to the [universal attributes](ts-universal-attributes-size.md) and [ | Name | Type | Description | | ----------------------- | ----------------------------------- | ------------------------------------------- | | textAlign | [TextAlign](ts-appendix-enums.md#textalign) | Horizontal alignment mode of the text.
Default value: **TextAlign.Start**
**NOTE**
The text takes up the full width of the **\** component. To set vertical alignment for the text, use the [align](ts-universal-attributes-location.md) attribute. The **align** attribute alone does not control the horizontal position of the text. In other words, **Alignment.TopStart**, **Alignment.Top**, and **Alignment.TopEnd** produce the same effect, top-aligning the text; **Alignment.Start**, **Alignment.Center**, and **Alignment.End** produce the same effect, centered-aligning the text vertically; **Alignment.BottomStart**, **Alignment.Bottom**, and **Alignment.BottomEnd** produce the same effect, bottom-aligning the text. Yet, it can work with the **textAlign** attribute to jointly determine the horizontal position of the text.
Since API version 9, this API is supported in ArkTS widgets.| -| textOverflow | {overflow: [TextOverflow](ts-appendix-enums.md#textoverflow)} | Display mode when the text is too long.
Default value: **{overflow: TextOverflow.Clip}**
**NOTE**
Text is clipped at the transition between words. To clip text in the middle of a word, add **\u200B** between characters.
If **overflow** is set to **TextOverflow.None**, **TextOverflow.Clip**, or **TextOverflow.Ellipsis**, this attribute must be used with **maxLines**. Otherwise, the setting does not take effect. **TextOverflow.None** produces the same effect as **TextOverflow.Clip**. If **overflow** is set to **TextOverflow.Marquee**, the text scrolls in a line, and neither **maxLines** nor **copyOption** takes effect.
Since API version 9, this API is supported in ArkTS widgets.| +| textOverflow | {overflow: [TextOverflow](ts-appendix-enums.md#textoverflow)} | Display mode when the text is too long.
Default value: **{overflow: TextOverflow.Clip}**
**NOTE**
Text is clipped at the transition between words. To clip text in the middle of a word, add **\u200B** between characters.
If **overflow** is set to **TextOverflow.None**, **TextOverflow.Clip**, or **TextOverflow.Ellipsis**, this attribute must be used with **maxLines**. Otherwise, the setting does not take effect. **TextOverflow.None** produces the same effect as **TextOverflow.Clip**. If **overflow** is set to **TextOverflow.Marquee**, the text scrolls in a line, and neither **maxLines** nor **copyOption** takes effect.
Since API version 9, this API is supported in ArkTS widgets. | | maxLines | number | Maximum number of lines in the text.
Default value: **Infinity**
**NOTE**
By default, text is automatically folded. If this attribute is specified, the text will not exceed the specified number of lines. If there is extra text, you can use **textOverflow** to specify how it is displayed.
Since API version 9, this API is supported in ArkTS widgets. | | lineHeight | string \| number \| [Resource](ts-types.md#resource) | Text line height. If the value is less than or equal to **0**, the line height is not limited and the font size is adaptive. If the value of the number type, the unit fp is used.
Since API version 9, this API is supported in ArkTS widgets.| | decoration | {
type: [TextDecorationType](ts-appendix-enums.md#textdecorationtype),
color?: [ResourceColor](ts-types.md#resourcecolor)
} | Style and color of the text decorative line.
Default value: {
type: TextDecorationType.None,
color: Color.Black
}
Since API version 9, this API is supported in ArkTS widgets.| | baselineOffset | number \| string | Baseline offset of the text. The default value is **0**.
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**

If this attribute is set to a percentage, the default value is used.| -| letterSpacing | number \| string | Letter spacing.
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
If this attribute is set to a percentage, the default value is used.
If this attribute is set to a negative value, the letters will overlap each other. | +| letterSpacing | number \| string | Letter spacing.
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
If this attribute is set to a percentage, the default value is used.
If this attribute is set to a negative value, the letters will overlap each other.| | minFontSize | number \| string \| [Resource](ts-types.md#resource) | Minimum font size.
For the setting to take effect, this attribute must be used together with **maxFontSize**, **maxLines**, or layout constraint settings.
Since API version 9, this API is supported in ArkTS widgets. | | maxFontSize | number \| string \| [Resource](ts-types.md#resource) | Maximum font size.
For the setting to take effect, this attribute must be used together with **minFontSize**, **maxLines**, or layout constraint settings.
Since API version 9, this API is supported in ArkTS widgets. | | textCase | [TextCase](ts-appendix-enums.md#textcase) | Text case.
Default value: **TextCase.Normal**
Since API version 9, this API is supported in ArkTS widgets.| | copyOption9+ | [CopyOptions](ts-appendix-enums.md#copyoptions9) | Whether copy and paste is allowed.
Default value: **CopyOptions.None**
This API is supported in ArkTS widgets.| -| draggable9+ | boolean | Drag effect of the selected text.
This attribute cannot be used with the [onDragStart](ts-universal-events-drag-drop.md) event.
It must be used with **copyOption** to enable the selected text to be dragged and copied.
Default value: **false**| +| draggable(deprecated) | boolean | Drag effect of the selected text.
This attribute cannot be used with the [onDragStart](ts-universal-events-drag-drop.md) event.
It must be used with **copyOption** to enable the selected text to be dragged and copied.
Default value: **false**
**NOTE**
This API is supported since API version 8 and deprecated since API version 10. You are advised to use the universal attribute [draggable](ts-universal-events-drag-drop.md) instead. | | textShadow10+ | [ShadowOptions](ts-universal-attributes-image-effect.md#shadowoptions) | Text shadow.| -| heightAdaptivePolicy10+ | [TextHeightAdaptivePolicy](ts-appendix-enums.md#textheightadaptivepolicy10) | How the adaptive height is determined for the text.
Default value: **TextHeightAdaptivePolicy.MAX_LINES_FIRST**
**NOTE**
When this attribute is set to **TextHeightAdaptivePolicy.MAX_LINES_FIRST**, the **maxLines** attribute takes precedence for adjusting the text height. If the **maxLines** setting results in a layout beyond the layout constraints, the text will shrink to a font size between `minFontSize` and `maxFontSize` to allow for more content to be shown.
When this attribute is set to **TextHeightAdaptivePolicy.MIN_FONT_SIZE_FIRST**, the **minFontSize** attribute takes precedence for adjusting the text height. If the text can fit in one line with the `minFontSize` setting, the text will enlarge to the largest possible font size between `minFontSize` and `maxFontSize`.
When this attribute is set to **TextHeightAdaptivePolicy.LAYOUT_CONSTRAINT_FIRST**, the layout constraints take precedence for adjusting the text height. If the resultant layout is beyond the layout constraints, the text will shrink to a font size between `minFontSize` and `maxFontSize` to respect the layout constraints. If the layout still exceeds the layout constraints after the font size is reduced to **minFontSize**, the lines that exceed the layout constraints are deleted. | +| heightAdaptivePolicy10+ | [TextHeightAdaptivePolicy](ts-appendix-enums.md#textheightadaptivepolicy10) | How the adaptive height is determined for the text.
Default value: **TextHeightAdaptivePolicy.MAX_LINES_FIRST**
**NOTE**
When this attribute is set to **TextHeightAdaptivePolicy.MAX_LINES_FIRST**, the **maxLines** attribute takes precedence for adjusting the text height. If the **maxLines** setting results in a layout beyond the layout constraints, the text will shrink to a font size between `minFontSize` and `maxFontSize` to allow for more content to be shown.
When this attribute is set to **TextHeightAdaptivePolicy.MIN_FONT_SIZE_FIRST**, the **minFontSize** attribute takes precedence for adjusting the text height. If the text can fit in one line with the **minFontSize** setting, the text will enlarge to the largest possible font size between **minFontSize** and **maxFontSize**.
When this attribute is set to **TextHeightAdaptivePolicy.LAYOUT_CONSTRAINT_FIRST**, the layout constraints take precedence for adjusting the text height. If the resultant layout is beyond the layout constraints, the text will shrink to a font size between **minFontSize** and **maxFontSize** to respect the layout constraints. If the layout still exceeds the layout constraints after the font size is reduced to **minFontSize**, the lines that exceed the layout constraints are deleted. | | textIndent10+ | number \| string | Indentation of the first line.
Default value: **0**| > **NOTE** diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-textarea.md b/en/application-dev/reference/arkui-ts/ts-basic-components-textarea.md index f3af7b67cb3eb17ada3be85777566ce874b1a72e..9244593898d8027c0cd0d67c56f91f16fdf5646c 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-textarea.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-textarea.md @@ -27,16 +27,16 @@ TextArea(value?:{placeholder?: ResourceStr, text?: ResourceStr, controller?: Tex ## Attributes -In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. - -| Name | Type | Description | -| ------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | -| placeholderColor | [ResourceColor](ts-types.md#resourcecolor) | Placeholder text color. | -| placeholderFont | [Font](ts-types.md#font) | Placeholder text style, including the font size, font width, font family, and font style. Currently, only the default font family is supported.| -| textAlign | [TextAlign](ts-appendix-enums.md#textalign) | Horizontal alignment of the text.
Default value: **TextAlign.Start**| -| caretColor | [ResourceColor](ts-types.md#resourcecolor) | Color of the caret in the text box. | -| inputFilter8+ | {
value: [ResourceStr](ts-types.md#resourcestr),
error?: (value: string) => void
} | Regular expression for input filtering. Only inputs that comply with the regular expression can be displayed. Other inputs are filtered out. The specified regular expression can match single characters, but not strings.
- **value**: regular expression to set.
- **error**: filtered-out content to return when regular expression matching fails.| -| copyOption9+ | [CopyOptions](ts-appendix-enums.md#copyoptions9) | Whether copy and paste is allowed.
If this attribute is set to **CopyOptions.None**, the paste operation is allowed, but the copy and cut operations are not.| +Among the [universal attributes](ts-universal-attributes-size.md) and [universal text attributes](ts-universal-attributes-text-style.md), **fontColor**, **fontSize**, **fontStyle**, **fontWeight**, and **fontFamily** are supported. In addition, the following attributes are supported. + +| Name | Type | Description | +| ------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | +| placeholderColor | [ResourceColor](ts-types.md#resourcecolor) | Placeholder text color.
The default value follows the theme. | +| placeholderFont | [Font](ts-types.md#font) | Placeholder text style, including the font size, font width, font family, and font style. Currently, only the default font family is supported.| +| textAlign | [TextAlign](ts-appendix-enums.md#textalign) | Horizontal alignment of the text.
Default value: **TextAlign.Start**
**NOTE**
Available options are **TextAlign.Start**, **TextAlign.Center**, and **TextAlign.End**.
To set vertical alignment for the text, use the [align](ts-universal-attributes-location.md) attribute. The **align** attribute alone does not control the horizontal position of the text. In other words, **Alignment.TopStart**, **Alignment.Top**, and **Alignment.TopEnd** produce the same effect, top-aligning the text; **Alignment.Start**, **Alignment.Center**, and **Alignment.End** produce the same effect, centered-aligning the text vertically; **Alignment.BottomStart**, **Alignment.Bottom**, and **Alignment.BottomEnd** produce the same effect, bottom-aligning the text.| +| caretColor | [ResourceColor](ts-types.md#resourcecolor) | Color of the caret in the text box.
Default value: **'#007DFF'** | +| inputFilter8+ | {
value: [ResourceStr](ts-types.md#resourcestr),
error?: (value: string) => void
} | Regular expression for input filtering. Only inputs that comply with the regular expression can be displayed. Other inputs are filtered out. The specified regular expression can match single characters, but not strings.
- **value**: regular expression to set.
- **error**: filtered-out content to return when regular expression matching fails.| +| copyOption9+ | [CopyOptions](ts-appendix-enums.md#copyoptions9) | Whether copy and paste is allowed.
Default value: **CopyOptions.LocalDevice**
If this attribute is set to **CopyOptions.None**, the paste operation is allowed, but the copy and cut operations are not.| > **NOTE** > diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-textinput.md b/en/application-dev/reference/arkui-ts/ts-basic-components-textinput.md index 588f88057abe66a553dd25dc8337503b8786e65a..5c477d98d5d375a092925fd828f637d3f75744bf 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-textinput.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-textinput.md @@ -21,27 +21,27 @@ TextInput(value?:{placeholder?: ResourceStr, text?: ResourceStr, controller?: Te | Name | Type | Mandatory | Description | | ----------------------- | ---------------------------------------- | ---- | --------------- | | placeholder | [ResourceStr](ts-types.md#resourcestr) | No | Placeholder text displayed when there is no input. | -| text | [ResourceStr](ts-types.md#resourcestr) | No | Current text input.
If the component has [stateStyles](ts-universal-attributes-polymorphic-style.md) or any other attribute that may trigger updating configured, you are advised to bind the state variable to the text in real time through the **onChange** event,
so as to prevent display errors when the component is updated.
Since API version 10, this parameter supports [$$](../../quick-start/arkts-two-way-sync.md) for two-way binding of variables.| +| text | [ResourceStr](ts-types.md#resourcestr) | No | Current text input.
If the component has [stateStyles](ts-universal-attributes-polymorphic-style.md) or any other attribute that may trigger updating configured, you are advised to bind the state variable to the text in real time through the **onChange** event, so as to prevent display errors when the component is updated.
Since API version 10, this parameter supports [$$](../../quick-start/arkts-two-way-sync.md) for two-way binding of variables.| | controller8+ | [TextInputController](#textinputcontroller8) | No | Text input controller.| ## Attributes -In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. +Among the [universal attributes](ts-universal-attributes-size.md) and [universal text attributes](ts-universal-attributes-text-style.md), **fontColor**, **fontSize**, **fontStyle**, **fontWeight**, and **fontFamily** are supported. In addition, the following attributes are supported. | Name | Type | Description | | ------------------------ | ---------------------------------------- | ---------------------------------------- | | type | [InputType](#inputtype) | Input box type.
Default value: **InputType.Normal** | -| placeholderColor | [ResourceColor](ts-types.md#resourcecolor) | Placeholder text color.| +| placeholderColor | [ResourceColor](ts-types.md#resourcecolor) | Placeholder text color.
The default value follows the theme. | | placeholderFont | [Font](ts-types.md#font) | Placeholder text font.| | enterKeyType | [EnterKeyType](#enterkeytype) | Type of the Enter key. Currently, only the default value is supported.
Default value: **EnterKeyType.Done**| -| caretColor | [ResourceColor](ts-types.md#resourcecolor) | Color of the caret in the text box. | +| caretColor | [ResourceColor](ts-types.md#resourcecolor) | Color of the caret in the text box.
Default value: **'#007DFF'** | | maxLength | number | Maximum number of characters in the text input. | | inputFilter8+ | {
value: [ResourceStr](ts-types.md#resourcestr),
error?: (value: string) => void
} | Regular expression for input filtering. Only inputs that comply with the regular expression can be displayed. Other inputs are filtered out. The regular expression can match single characters, but not strings.
- **value**: regular expression to set.
- **error**: filtered-out content to return when regular expression matching fails.| -| copyOption9+ | [CopyOptions](ts-appendix-enums.md#copyoptions9) | Whether copy and paste is allowed.
If this attribute is set to **CopyOptions.None**, the paste operation is allowed, but not the copy or cut operation.| -| showPasswordIcon9+ | boolean | Whether to display the show password icon at the end of the password text box.
Default value: **true**| -| style9+ | [TextInputStyle](#textinputstyle9) | Text input style.
Default value: **TextInputStyle.Default**| -| textAlign9+ | [TextAlign](ts-appendix-enums.md#textalign) | Alignment mode of the text in the text box.
Default value: **TextAlign.Start** | +| copyOption9+ | [CopyOptions](ts-appendix-enums.md#copyoptions9) | Whether copy and paste is allowed.
Default value: **CopyOptions.LocalDevice**
If this attribute is set to **CopyOptions.None**, the paste operation is allowed, but not the copy or cut operation.| +| showPasswordIcon9+ | boolean | Whether to display the password icon at the end of the password text box.
Default value: **true**| +| style9+ | [TextInputStyle](#textinputstyle9) \| [TextContentStyle](enums.d.ts#TextContentStyle) | Text input style.
Default value: **TextInputStyle.Default**| +| textAlign9+ | [TextAlign](ts-appendix-enums.md#textalign) | Horizontal alignment of the text.
Default value: **TextAlign.Start**
**NOTE**
Available options are **TextAlign.Start**, **TextAlign.Center**, and **TextAlign.End**.
To set vertical alignment for the text, use the [align](ts-universal-attributes-location.md) attribute. The **align** attribute alone does not control the horizontal position of the text. In other words, **Alignment.TopStart**, **Alignment.Top**, and **Alignment.TopEnd** produce the same effect, top-aligning the text; **Alignment.Start**, **Alignment.Center**, and **Alignment.End** produce the same effect, centered-aligning the text vertically; **Alignment.BottomStart**, **Alignment.Bottom**, and **Alignment.BottomEnd** produce the same effect, bottom-aligning the text. | | selectedBackgroundColor10+ | [ResourceColor](ts-types.md#resourcecolor) | Background color of the selected text.
If the opacity is not set, the color is opaque. For example, **0x80000000** indicates black with 50% opacity.| | caretStyle10+ | {
width: [Length](ts-types.md#length)
} | Caret style. | | caretPosition10+ | number | Caret position.| diff --git a/en/application-dev/reference/arkui-ts/ts-canvasrenderingcontext2d.md b/en/application-dev/reference/arkui-ts/ts-canvasrenderingcontext2d.md index 6f899761e3609c2ee9a91fa2e9d8d2d04d105ee0..7f0b8291246271cef1d8b9e82394004c051cf491 100644 --- a/en/application-dev/reference/arkui-ts/ts-canvasrenderingcontext2d.md +++ b/en/application-dev/reference/arkui-ts/ts-canvasrenderingcontext2d.md @@ -10,15 +10,15 @@ Use **RenderingContext** to draw rectangles, text, images, and other objects on ## APIs -CanvasRenderingContext2D(setting: RenderingContextSetting) +CanvasRenderingContext2D(settings?: RenderingContextSettings) Since API version 9, this API is supported in ArkTS widgets. **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ---------------------------------------- | ---- | ---------------------------------------- | -| setting | [RenderingContextSettings](#renderingcontextsettings) | Yes | See [RenderingContextSettings](#renderingcontextsettings).| +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| settings | [RenderingContextSettings](#renderingcontextsettings) | No | See [RenderingContextSettings](#renderingcontextsettings).| ### RenderingContextSettings @@ -38,25 +38,30 @@ Since API version 9, this API is supported in ArkTS widgets. ## Attributes -| Name | Type | Description | -| ----------------------------------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | -| [fillStyle](#fillstyle) | string \|number10+ \|[CanvasGradient](ts-components-canvas-canvasgradient.md) \| [CanvasPattern](#canvaspattern) | Style to fill an area.
- When the type is string, this attribute indicates the color of the fill area.
- When the type is number, this attribute indicates the color of the fill area.
- When the type is **CanvasGradient**, this attribute indicates a gradient object, which is created using the **[createLinearGradient](#createlineargradient)** API.
- When the type is **CanvasPattern**, this attribute indicates a pattern, which is created using the **[createPattern](#createpattern)** API.
Since API version 9, this API is supported in ArkTS widgets.| -| [lineWidth](#linewidth) | number | Line width. | -| [strokeStyle](#strokestyle) | string \|number10+ \|[CanvasGradient](ts-components-canvas-canvasgradient.md) \| [CanvasPattern](#canvaspattern) | Stroke style.
- When the type is string, this attribute indicates the stroke color.
- When the type is number, this attribute indicates the stroke color.
- When the type is **CanvasGradient**, this attribute indicates a gradient object, which is created using the **[createLinearGradient](#createlineargradient)** API.
- When the type is **CanvasPattern**, this attribute indicates a pattern, which is created using the **[createPattern](#createpattern)** API.
Since API version 9, this API is supported in ArkTS widgets.| -| [lineCap](#linecap) | CanvasLineCap | Style of the line endpoints. The options are as follows:
- **'butt'**: The endpoints of the line are squared off.
- **'round'**: The endpoints of the line are rounded.
- **'square'**: The endpoints of the line are squared off by adding a box with an equal width and half the height of the line's thickness.
Default value: **'butt'**
Since API version 9, this API is supported in ArkTS widgets.| -| [lineJoin](#linejoin) | CanvasLineJoin | Style of the shape used to join line segments. The options are as follows:
- **'round'**: The shape used to join line segments is a sector, whose radius at the rounded corner is equal to the line width.
- **'bevel'**: The shape used to join line segments is a triangle. The rectangular corner of each line is independent.
- **'miter'**: The shape used to join line segments has a mitered corner by extending the outside edges of the lines until they meet. You can view the effect of this attribute in **miterLimit**.
Default value: **'miter'**
Since API version 9, this API is supported in ArkTS widgets.| -| [miterLimit](#miterlimit) | number | Maximum miter length. The miter length is the distance between the inner corner and the outer corner where two lines meet.
Default value: **10**
Since API version 9, this API is supported in ArkTS widgets.| -| [font](#font) | string | Font style.
Syntax: ctx.font='font-size font-family'
- (Optional) **font-size**: font size and row height. The unit can only be pixels.
- (Optional) **font-family**: font family.
Syntax: ctx.font='font-style font-weight font-size font-family'
- (Optional) **font-style**: font style. Available values are **'normal'** and **'italic'**.
- (Optional) **font-weight**: font weight. Available values are as follows: **'normal'**, **'bold'**, **'bolder'**, **'lighter'**, **'100'**, **'200'**, **'300'**, **'400'**, **'500'**, **'600'**, **'700'**, **'800'**, **'900'**.
- (Optional) **font-size**: font size and row height. The unit can only be pixels.
- (Optional) **font-family**: font family. Available values are **'sans-serif'**, **'serif'**, and **'monospace'**.
Default value: **'normal normal 14px sans-serif'**
Since API version 9, this API is supported in ArkTS widgets.| -| [textAlign](#textalign) | CanvasTextAlign | Text alignment mode. Available values are as follows:
- **'left'**: The text is left-aligned.
- **'right'**: The text is right-aligned.
- **'center'**: The text is center-aligned.
- **'start'**: The text is aligned with the start bound.
- **'end'**: The text is aligned with the end bound.
In the **ltr** layout mode, the value **'start'** equals **'left'**. In the **rtl** layout mode, the value **'start'** equals **'right'**.
Default value: **'left'**
Since API version 9, this API is supported in ArkTS widgets.| -| [textBaseline](#textbaseline) | CanvasTextBaseline | Horizontal alignment mode of text. Available values are as follows:
- **'alphabetic'**: The text baseline is the normal alphabetic baseline.
- **'top'**: The text baseline is on the top of the text bounding box.
- **'hanging'**: The text baseline is a hanging baseline over the text.
- **'middle'**: The text baseline is in the middle of the text bounding box.
**'ideographic'**: The text baseline is the ideographic baseline. If a character exceeds the alphabetic baseline, the ideographic baseline is located at the bottom of the excess character.
- **'bottom'**: The text baseline is at the bottom of the text bounding box. Its difference from the ideographic baseline is that the ideographic baseline does not consider letters in the next line.
Default value: **'alphabetic'**
Since API version 9, this API is supported in ArkTS widgets.| -| [globalAlpha](#globalalpha) | number | Opacity.
**0.0**: completely transparent.
**1.0**: completely opaque.
Since API version 9, this API is supported in ArkTS widgets.| -| [lineDashOffset](#linedashoffset) | number | Offset of the dashed line. The precision is float.
Default value: **0.0**
Since API version 9, this API is supported in ArkTS widgets.| -| [globalCompositeOperation](#globalcompositeoperation) | string | Composition operation type. Available values are as follows: **'source-over'**, **'source-atop'**, **'source-in'**, **'source-out'**, **'destination-over'**, **'destination-atop'**, **'destination-in'**, **'destination-out'**, **'lighter'**, **'copy'**, and **'xor'**.
Default value: **'source-over'**
Since API version 9, this API is supported in ArkTS widgets.| -| [shadowBlur](#shadowblur) | number | Blur level during shadow drawing. A larger value indicates a more blurred effect. The precision is float.
Default value: **0.0**
Since API version 9, this API is supported in ArkTS widgets.| -| [shadowColor](#shadowcolor) | string | Shadow color.
Since API version 9, this API is supported in ArkTS widgets.| -| [shadowOffsetX](#shadowoffsetx) | number | X-axis shadow offset relative to the original object.
Since API version 9, this API is supported in ArkTS widgets.| -| [shadowOffsetY](#shadowoffsety) | number | Y-axis shadow offset relative to the original object.
Since API version 9, this API is supported in ArkTS widgets.| -| [imageSmoothingEnabled](#imagesmoothingenabled) | boolean | Whether to adjust the image smoothness during image drawing. The value **true** means to enable this feature, and **false** means the opposite.
Default value: **true**
Since API version 9, this API is supported in ArkTS widgets.| +| Name | Type | Description | +| ---------------------------------------- | ---------------------------------------- | ---------------------------------------- | +| [fillStyle](#fillstyle) | string \|number10+ \|[CanvasGradient](ts-components-canvas-canvasgradient.md) \| [CanvasPattern](ts-components-canvas-canvaspattern.md#canvaspattern) | Style to fill an area.
- When the type is string, this attribute indicates the color of the fill area.
- When the type is number, this attribute indicates the color of the fill area.
- When the type is **CanvasGradient**, this attribute indicates a gradient object, which is created using the **[createLinearGradient](#createlineargradient)** API.
- When the type is **CanvasPattern**, this attribute indicates a pattern, which is created using the **[createPattern](#createpattern)** API.
Since API version 9, this API is supported in ArkTS widgets.| +| [lineWidth](#linewidth) | number | Line width. | +| [strokeStyle](#strokestyle) | string \|number10+ \|[CanvasGradient](ts-components-canvas-canvasgradient.md) \| [CanvasPattern](ts-components-canvas-canvaspattern.md#canvaspattern) | Stroke style.
- When the type is string, this attribute indicates the stroke color.
- When the type is number, this attribute indicates the stroke color.
- When the type is **CanvasGradient**, this attribute indicates a gradient object, which is created using the **[createLinearGradient](#createlineargradient)** API.
- When the type is **CanvasPattern**, this attribute indicates a pattern, which is created using the **[createPattern](#createpattern)** API.
Since API version 9, this API is supported in ArkTS widgets.| +| [lineCap](#linecap) | CanvasLineCap | Style of the line endpoints. The options are as follows:
- **'butt'**: The endpoints of the line are squared off.
- **'round'**: The endpoints of the line are rounded.
- **'square'**: The endpoints of the line are squared off by adding a box with an equal width and half the height of the line's thickness.
Default value: **'butt'**
Since API version 9, this API is supported in ArkTS widgets.| +| [lineJoin](#linejoin) | CanvasLineJoin | Style of the shape used to join line segments. The options are as follows:
- **'round'**: The shape used to join line segments is a sector, whose radius at the rounded corner is equal to the line width.
- **'bevel'**: The shape used to join line segments is a triangle. The rectangular corner of each line is independent.
- **'miter'**: The shape used to join line segments has a mitered corner by extending the outside edges of the lines until they meet. You can view the effect of this attribute in **miterLimit**.
Default value: **'miter'**
Since API version 9, this API is supported in ArkTS widgets.| +| [miterLimit](#miterlimit) | number | Maximum miter length. The miter length is the distance between the inner corner and the outer corner where two lines meet.
Default value: **10**
Since API version 9, this API is supported in ArkTS widgets.| +| [font](#font) | string | Font style.
Syntax: ctx.font='font-size font-family'
- (Optional) **font-size**: font size and row height. The unit can only be pixels.
- (Optional) **font-family**: font family.
Syntax: ctx.font='font-style font-weight font-size font-family'
- (Optional) **font-style**: font style. Available values are **'normal'** and **'italic'**.
- (Optional) **font-weight**: font weight. Available values are as follows: **'normal'**, **'bold'**, **'bolder'**, **'lighter'**, **'100'**, **'200'**, **'300'**, **'400'**, **'500'**, **'600'**, **'700'**, **'800'**, **'900'**.
- (Optional) **font-size**: font size and row height. The unit must be specified and can only be px or vp.
- (Optional) **font-family**: font family. Available values are **'sans-serif'**, **'serif'**, and **'monospace'**.
Default value: **'normal normal 14px sans-serif'**
Since API version 9, this API is supported in ArkTS widgets.| +| [textAlign](#textalign) | CanvasTextAlign | Text alignment mode. Available values are as follows:
- **'left'**: The text is left-aligned.
- **'right'**: The text is right-aligned.
- **'center'**: The text is center-aligned.
- **'start'**: The text is aligned with the start bound.
- **'end'**: The text is aligned with the end bound.
In the **ltr** layout mode, the value **'start'** equals **'left'**. In the **rtl** layout mode, the value **'start'** equals **'right'**.
Default value: **'left'**
Since API version 9, this API is supported in ArkTS widgets.| +| [textBaseline](#textbaseline) | CanvasTextBaseline | Horizontal alignment mode of text. Available values are as follows:
- **'alphabetic'**: The text baseline is the normal alphabetic baseline.
- **'top'**: The text baseline is on the top of the text bounding box.
- **'hanging'**: The text baseline is a hanging baseline over the text.
- **'middle'**: The text baseline is in the middle of the text bounding box.
**'ideographic'**: The text baseline is the ideographic baseline. If a character exceeds the alphabetic baseline, the ideographic baseline is located at the bottom of the excess character.
- **'bottom'**: The text baseline is at the bottom of the text bounding box. Its difference from the ideographic baseline is that the ideographic baseline does not consider letters in the next line.
Default value: **'alphabetic'**
Since API version 9, this API is supported in ArkTS widgets.| +| [globalAlpha](#globalalpha) | number | Opacity.
**0.0**: completely transparent.
**1.0**: completely opaque.
Since API version 9, this API is supported in ArkTS widgets.| +| [lineDashOffset](#linedashoffset) | number | Offset of the dashed line. The precision is float.
Default value: **0.0**
Since API version 9, this API is supported in ArkTS widgets.| +| [globalCompositeOperation](#globalcompositeoperation) | string | Composition operation type. Available values are as follows: **'source-over'**, **'source-atop'**, **'source-in'**, **'source-out'**, **'destination-over'**, **'destination-atop'**, **'destination-in'**, **'destination-out'**, **'lighter'**, **'copy'**, and **'xor'**.
Default value: **'source-over'**
Since API version 9, this API is supported in ArkTS widgets.| +| [shadowBlur](#shadowblur) | number | Blur level during shadow drawing. A larger value indicates a more blurred effect. The precision is float.
Default value: **0.0**
Since API version 9, this API is supported in ArkTS widgets.| +| [shadowColor](#shadowcolor) | string | Shadow color.
Since API version 9, this API is supported in ArkTS widgets.| +| [shadowOffsetX](#shadowoffsetx) | number | X-axis shadow offset relative to the original object.
Since API version 9, this API is supported in ArkTS widgets.| +| [shadowOffsetY](#shadowoffsety) | number | Y-axis shadow offset relative to the original object.
Since API version 9, this API is supported in ArkTS widgets.| +| [imageSmoothingEnabled](#imagesmoothingenabled) | boolean | Whether to adjust the image smoothness during image drawing. The value **true** means to enable this feature, and **false** means the opposite.
Default value: **true**
Since API version 9, this API is supported in ArkTS widgets.| +| [height](#height) | number | Component height.
Unit: vp
Since API version 9, this API is supported in ArkTS widgets.| +| [width](#width) | number | Component width.
Unit: vp
Since API version 9, this API is supported in ArkTS widgets.| +| [imageSmoothingQuality](#imagesmoothingquality) | ImageSmoothingQuality | Quality of image smoothing. This attribute works only when **imageSmoothingEnabled** is set to **true**. Available values are as follows:
- **'low'**: low quality.
- **'medium'**: medium quality.
- **'high'**: high quality.
Default value: **'low'**
Since API version 9, this API is supported in ArkTS widgets.| +| [direction](#direction) | CanvasDirection | Text direction used for drawing text. Available values are as follows:
- **'inherit'**: The text direction is inherited from the **\** component.
- **'ltr'**: The text direction is from left to right.
- **'rtl'**: The text direction is from right to left.
Default value: **'inherit'**
Since API version 9, this API is supported in ArkTS widgets.| +| [filter](#filter) | string | Filter effect. Available values are as follows:
- **'none'**: no filter effect.
- **'blur'**: applies the Gaussian blur for the image.
- **'brightness'**: applies a linear multiplication to the image to make it look brighter or darker.
- **'contrast'**: adjusts the image contrast.
- **'grayscale'**: converts the image to a grayscale image.
- **'hue-rotate'**: applies hue rotation to the image.
- **'invert'**: inverts the input image.
- **'opacity'**: sets the opacity of the image.
- **'saturate'**: sets the saturation of the image.
- **'sepia'**: converts the image to dark brown.
Default value: **'none'**
Since API version 9, this API is supported in ArkTS widgets.| > **NOTE** > @@ -652,6 +657,68 @@ struct ImageSmoothingEnabled { ![en-us_image_0000001211898472](figures/en-us_image_0000001211898472.png) +### height + +```ts +// xxx.ets +@Entry +@Component +struct HeightExample { + 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(300) + .height(300) + .backgroundColor('#ffff00') + .onReady(() => { + let h = this.context.height + let w = this.context.width + this.context.fillRect(0, 0, 300, h/2) + }) + } + .width('100%') + .height('100%') + } +} +``` + +![en-us_image_canvas_height](figures/en-us_image_canvas_height.png) + + +### width + +```ts +// xxx.ets +@Entry +@Component +struct WidthExample { + 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(300) + .height(300) + .backgroundColor('#ffff00') + .onReady(() => { + let h = this.context.height + let w = this.context.width + this.context.fillRect(0, 0, w/2, 300) + }) + } + .width('100%') + .height('100%') + } +} +``` + +![en-us_image_canvas_width](figures/en-us_image_canvas_width.png) + + ## Methods @@ -805,12 +872,12 @@ Since API version 9, this API is supported in ArkTS widgets. **Parameters** -| Name | Type | Mandatory| Default Value| Description | -| -------- | ------ | ---- | ------ | ----------------------------- | -| text | string | Yes | '' | Text to draw. | -| x | number | Yes | 0 | X-coordinate of the lower left corner of the text.| -| y | number | Yes | 0 | Y-coordinate of the lower left corner of the text.| -| maxWidth | number | No | - | Maximum width allowed for the text. | +| Name | Type | Mandatory | Default Value | Description | +| -------- | ------ | ---- | ---- | --------------- | +| text | string | Yes | '' | Text to draw. | +| x | number | Yes | 0 | X-coordinate of the lower left corner of the text.| +| y | number | Yes | 0 | Y-coordinate of the lower left corner of the text.| +| maxWidth | number | No | - | Maximum width allowed for the text. | **Example** @@ -852,12 +919,12 @@ Since API version 9, this API is supported in ArkTS widgets. **Parameters** -| Name | Type | Mandatory| Default Value| Description | -| -------- | ------ | ---- | ------ | ----------------------------- | -| text | string | Yes | '' | Text to draw. | -| x | number | Yes | 0 | X-coordinate of the lower left corner of the text.| -| y | number | Yes | 0 | Y-coordinate of the lower left corner of the text.| -| maxWidth | number | No | - | Maximum width of the text to be drawn. | +| Name | Type | Mandatory | Default Value | Description | +| -------- | ------ | ---- | ---- | --------------- | +| text | string | Yes | '' | Text to draw. | +| x | number | Yes | 0 | X-coordinate of the lower left corner of the text.| +| y | number | Yes | 0 | Y-coordinate of the lower left corner of the text.| +| maxWidth | number | No | - | Maximum width of the text to be drawn. | **Example** @@ -899,14 +966,14 @@ Since API version 9, this API is supported in ArkTS widgets. **Parameters** -| Name| Type | Mandatory| Default Value| Description | -| ---- | ------ | ---- | ------ | -------------------- | -| text | string | Yes | '' | Text to be measured.| +| Name | Type | Mandatory | Default Value | Description | +| ---- | ------ | ---- | ---- | ---------- | +| text | string | Yes | '' | Text to be measured.| **Return value** -| Type | Description | -| ----------- | ------------------------------------------------------------ | +| Type | Description | +| ----------- | ---------------------------------------- | | TextMetrics | **TextMetrics** object.
Since API version 9, this API is supported in ArkTS widgets.| **TextMetrics** @@ -1197,16 +1264,16 @@ Since API version 9, this API is supported in ArkTS widgets. **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | -------------------------------------------------- | ---- | ------------------------------------------------------------ | -| image | [ImageBitmap](ts-components-canvas-imagebitmap.md) | Yes | Source image. For details, see **ImageBitmap**. | -| repetition | string | Yes | Repetition mode. The value can be **'repeat'**, **'repeat-x'**, **'repeat-y'**, **'no-repeat'**, **'clamp'**, or **'mirror'**.
Default value: **''**| +| Name | Type | Mandatory | Description | +| ---------- | ---------------------------------------- | ---- | ---------------------------------------- | +| image | [ImageBitmap](ts-components-canvas-imagebitmap.md) | Yes | Source image. For details, see **ImageBitmap**. | +| repetition | string | Yes | Repetition mode. The value can be **'repeat'**, **'repeat-x'**, **'repeat-y'**, **'no-repeat'**, **'clamp'**, or **'mirror'**.
Default value: **''**| **Return value** -| Type | Description | -| ------------------------------- | ----------------------- | -| [CanvasPattern](#canvaspattern) | Created pattern for image filling based on a specified source image and repetition mode.| +| Type | Description | +| ---------------------------------------- | ----------------------- | +| [CanvasPattern](ts-components-canvas-canvaspattern.md#canvaspattern) | Created pattern for image filling based on a specified source image and repetition mode.| **Example** @@ -1449,16 +1516,16 @@ Since API version 9, this API is supported in ArkTS widgets. **Parameters** -| Name | Type | Mandatory | Default Value | Description | -| ---------------- | ------- | ---- | ----- | ----------------- | -| x | number | Yes | 0 | X-coordinate of the ellipse center. | -| y | number | Yes | 0 | Y-coordinate of the ellipse center. | -| radiusX | number | Yes | 0 | Ellipse radius on the x-axis. | -| radiusY | number | Yes | 0 | Ellipse radius on the y-axis. | -| rotation | number | Yes | 0 | Rotation angle of the ellipse. The unit is radian. | -| startAngle | number | Yes | 0 | Angle of the start point for drawing the ellipse. The unit is radian.| -| endAngle | number | Yes | 0 | Angle of the end point for drawing the ellipse. The unit is radian.| -| counterclockwise | boolean | No | false | Whether to draw the ellipse in the counterclockwise direction.
**true**: Draw the arc counterclockwise.
**false**: Draw the arc clockwise. | +| Name | Type | Mandatory | Default Value | Description | +| ---------------- | ------- | ---- | ----- | ---------------------------------------- | +| x | number | Yes | 0 | X-coordinate of the ellipse center. | +| y | number | Yes | 0 | Y-coordinate of the ellipse center. | +| radiusX | number | Yes | 0 | Ellipse radius on the x-axis. | +| radiusY | number | Yes | 0 | Ellipse radius on the y-axis. | +| rotation | number | Yes | 0 | Rotation angle of the ellipse. The unit is radian. | +| startAngle | number | Yes | 0 | Angle of the start point for drawing the ellipse. The unit is radian. | +| endAngle | number | Yes | 0 | Angle of the end point for drawing the ellipse. The unit is radian. | +| counterclockwise | boolean | No | false | Whether to draw the ellipse in the counterclockwise direction.
**true**: Draw the arc counterclockwise.
**false**: Draw the arc clockwise.| **Example** @@ -1739,15 +1806,76 @@ Since API version 9, this API is supported in ArkTS widgets. filter(filter: string): void -Provides filter effects. This API is a void API. +Provides filter effects. Since API version 9, this API is supported in ArkTS widgets. **Parameters** -| Name | Type | Mandatory | Default Value | Description | -| ------ | ------ | ---- | ---- | ------------ | -| filter | string | Yes | - | Filter functions.| +| Name | Type | Mandatory | Default Value | Description | +| ------ | ------ | ---- | ---- | ---------------------------------------- | +| filter | string | Yes | - | Filter functions. Available values are as follows:
- **'none'**: no filter effect.
- **'blur'**: applies the Gaussian blur for the image.
- **'brightness'**: applies a linear multiplication to the image to make it look brighter or darker.
- **'contrast'**: adjusts the image contrast.
- **'grayscale'**: converts the image to a grayscale image.
- **'hue-rotate'**: applies hue rotation to the image.
- **'invert'**: inverts the input image.
- **'opacity'**: sets the opacity of the image.
- **'saturate'**: sets the saturation of the image.
- **'sepia'**: converts the image to dark brown.
Default value: **'none'**| + +**Example** +```ts + // xxx.ets + @Entry + @Component + struct FilterDemo { + private settings: RenderingContextSettings = new RenderingContextSettings(true); + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + private img:ImageBitmap = new ImageBitmap("common/images/example.jpg"); + + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Canvas(this.context) + .width('100%') + .height('100%') + .backgroundColor('#ffff00') + .onReady(() =>{ + let ctx = this.context + let img = this.img + + ctx.drawImage(img, 0, 0, 100, 100); + + ctx.filter = 'grayscale(50%)'; + ctx.drawImage(img, 100, 0, 100, 100); + + ctx.filter = 'sepia(60%)'; + ctx.drawImage(img, 200, 0, 100, 100); + + ctx.filter = 'saturate(30%)'; + ctx.drawImage(img, 0, 100, 100, 100); + + ctx.filter = 'hue-rotate(90degree)'; + ctx.drawImage(img, 100, 100, 100, 100); + + ctx.filter = 'invert(100%)'; + ctx.drawImage(img, 200, 100, 100, 100); + + ctx.filter = 'opacity(25%)'; + ctx.drawImage(img, 0, 200, 100, 100); + + ctx.filter = 'brightness(0.4)'; + ctx.drawImage(img, 100, 200, 100, 100); + + ctx.filter = 'contrast(200%)'; + ctx.drawImage(img, 200, 200, 100, 100); + + ctx.filter = 'blur(5px)'; + ctx.drawImage(img, 0, 300, 100, 100); + + let result = ctx.toDataURL() + console.info(result) + }) + } + .width('100%') + .height('100%') + } + } +``` + +![filterDemo](figures/filterDemo.jpeg) ### getTransform @@ -1758,6 +1886,12 @@ Obtains the current transformation matrix being applied to the context. This API Since API version 9, this API is supported in ArkTS widgets. +**Return value** + +| Type | Description | +| ---------------------------------------- | ----- | +| [Matrix2D](ts-components-canvas-matrix2d.md#Matrix2D) | **Matrix2D** object.| + ### resetTransform @@ -1772,10 +1906,42 @@ Since API version 9, this API is supported in ArkTS widgets. direction(direction: CanvasDirection): void -Sets the current text direction used to draw text. This API is a void API. +Sets the current text direction used to draw text. Since API version 9, this API is supported in ArkTS widgets. +**Example** +```ts + // xxx.ets + @Entry + @Component + struct DirectionDemo { + 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 ctx = this.context + ctx.font = '48px serif'; + ctx.textAlign = 'start' + ctx.fillText("Hi ltr!", 200, 50); + + ctx.direction = "rtl"; + ctx.fillText("Hi rtl!", 200, 100); + }) + } + .width('100%') + .height('100%') + } + } +``` + +![directionDemo](figures/directionDemo.jpeg) ### rotate @@ -1982,6 +2148,7 @@ Since API version 9, this API is supported in ArkTS widgets. ![en-us_image_0000001256858395](figures/en-us_image_0000001256858395.png) +### setTransform setTransform(transform?: Matrix2D): void @@ -1989,6 +2156,11 @@ Resets the current transformation to the identity matrix, and then creates a new Since API version 9, this API is supported in ArkTS widgets. +**Parameters** + +| Name | Type | Mandatory | Default Value | Description | +| --------- | ---------------------------------------- | ---- | ---- | ----- | +| transform | [Matrix2D](ts-components-canvas-matrix2d.md#Matrix2D) | No | null | Transformation matrix.| ### translate @@ -2207,9 +2379,9 @@ Since API version 9, this API is supported in ArkTS widgets. ### putImageData -putImageData(imageData: ImageData, dx: number, dy: number): void +putImageData(imageData: ImageData, dx: number | string, dy: number | string): void -putImageData(imageData: ImageData, dx: number, dy: number, dirtyX: number, dirtyY: number, dirtyWidth: number, dirtyHeight: number): void +putImageData(imageData: ImageData, dx: number | string, dy: number | string, dirtyX: number | string, dirtyY: number | string, dirtyWidth: number | string, dirtyHeight: number | string): void Puts an **[ImageData](ts-components-canvas-imagedata.md)** object onto a rectangular area on the canvas. @@ -2220,12 +2392,12 @@ Since API version 9, this API is supported in ArkTS widgets. | Name | Type | Mandatory | Default Value | Description | | ----------- | ---------------------------------------- | ---- | ------------ | ----------------------------- | | imagedata | [ImageData](ts-components-canvas-imagedata.md) | Yes | null | **ImageData** object with pixels to put onto the canvas. | -| dx | number | Yes | 0 | X-axis offset of the rectangular area on the canvas. | -| dy | number | Yes | 0 | Y-axis offset of the rectangular area on the canvas. | -| dirtyX | number | No | 0 | X-axis offset of the upper left corner of the rectangular area relative to that of the source image.| -| dirtyY | number | No | 0 | Y-axis offset of the upper left corner of the rectangular area relative to that of the source image.| -| dirtyWidth | number | No | Width of the **ImageData** object| Width of the rectangular area to crop the source image. | -| dirtyHeight | number | No | Height of the **ImageData** object| Height of the rectangular area to crop the source image. | +| dx | number \| string10+ | Yes | 0 | X-axis offset of the rectangular area on the canvas. | +| dy | number \| string10+ | Yes | 0 | Y-axis offset of the rectangular area on the canvas. | +| dirtyX | number \| string10+ | No | 0 | X-axis offset of the upper left corner of the rectangular area relative to that of the source image.| +| dirtyY | number \| string10+ | No | 0 | Y-axis offset of the upper left corner of the rectangular area relative to that of the source image.| +| dirtyWidth | number \| string10+ | No | Width of the **ImageData** object| Width of the rectangular area to crop the source image. | +| dirtyHeight | number \| string10+ | No | Height of the **ImageData** object| Height of the rectangular area to crop the source image. | **Example** @@ -2370,7 +2542,7 @@ Since API version 9, this API is supported in ArkTS widgets. imageSmoothingQuality(quality: imageSmoothingQuality) -Sets the quality of image smoothing. This API is a void API. +Sets the quality of image smoothing. Since API version 9, this API is supported in ArkTS widgets. @@ -2378,9 +2550,38 @@ Since API version 9, this API is supported in ArkTS widgets. | Name | Type | Description | | ------- | --------------------- | ---------------------------------------- | -| quality | imageSmoothingQuality | The options are as follows: '**low'**, **'medium'**, and **'high'**.| +| quality | imageSmoothingQuality | Quality of image smoothing.
- **'low'**: low quality.
- **'medium'**: medium quality.
- **'high'**: high quality.| +**Example** +```ts + // xxx.ets + @Entry + @Component + struct ImageSmoothingQualityDemo { + private settings: RenderingContextSettings = new RenderingContextSettings(true); + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + private img:ImageBitmap = new ImageBitmap("common/images/example.jpg"); + + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Canvas(this.context) + .width('100%') + .height('100%') + .backgroundColor('#ffff00') + .onReady(() =>{ + let ctx = this.context + ctx.imageSmoothingEnabled = true + ctx.imageSmoothingQuality = 'high' + ctx.drawImage(this.img, 0, 0, 400, 200) + }) + } + .width('100%') + .height('100%') + } + } +``` +![ImageSmoothingQualityDemo](figures/ImageSmoothingQualityDemo.jpeg) ### transferFromImageBitmap @@ -2673,11 +2874,11 @@ Creates a conic gradient. **Parameters** -| Name | Type | Mandatory| Default Value| Description | -| ---------- | ------ | ---- | ------ | ------------------------------------------------------------ | -| startAngle | number | Yes | 0 | Angle at which the gradient starts, in radians. The angle measurement starts horizontally from the right side of the center and moves clockwise.| -| x | number | Yes | 0 | X-coordinate of the center of the conic gradient, in vp. | -| y | number | Yes | 0 | Y-coordinate of the center of the conic gradient, in vp. | +| Name | Type | Mandatory | Default Value | Description | +| ---------- | ------ | ---- | ---- | ----------------------------------- | +| startAngle | number | Yes | 0 | Angle at which the gradient starts, in radians. The angle measurement starts horizontally from the right side of the center and moves clockwise.| +| x | number | Yes | 0 | X-coordinate of the center of the conic gradient, in vp. | +| y | number | Yes | 0 | X-coordinate of the center of the conic gradient, in vp. | **Example** @@ -2711,9 +2912,3 @@ struct CanvasExample { ``` ![en-us_image_0000001239032419](figures/en-us_image_0000001239032420.png) - -## CanvasPattern - -Defines an object created using the **[createPattern](#createpattern)** API. - -Since API version 9, this API is supported in ArkTS widgets. diff --git a/en/application-dev/reference/arkui-ts/ts-container-list.md b/en/application-dev/reference/arkui-ts/ts-container-list.md index e20063ba938358602853548c86cfba6275e0620a..662982a40ce6246f44bbd4baba6c239fd889c7df 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-list.md +++ b/en/application-dev/reference/arkui-ts/ts-container-list.md @@ -39,37 +39,37 @@ Since API version 9, this API is supported in ArkTS widgets. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| space | number \| string | No| Spacing between list items along the main axis.
Default value: **0**
**NOTE**
If this parameter is set to a percentage or a negative number other than -1, the default value is used.
If the value of **space** is less than the width of the list divider, the latter is used as the spacing.| -| initialIndex | number | No| Item displayed at the beginning of the viewport when the current list is loaded for the first time, that is, the first item to be displayed.
Default value: **0**
**NOTE**
If this parameter is set to a negative value other than -1 or is greater than the index value of the last item in the current list, the value is invalid. In this case, the default value is used.| -| scroller | [Scroller](ts-container-scroll.md#scroller) | No| Scroller, which can be bound to scrollable components.
**NOTE**
The scroller cannot be bound to other scrollable components.| +| Name | Type | Mandatory | Description | +| ------------ | ---------------------------------------- | ---- | ---------------------------------------- | +| space | number \| string | No | Spacing between list items along the main axis.
Default value: **0**
**NOTE**
If the set value is a negative number, the default value will be used.
If the value of **space** is less than the width of the list divider, the latter is used as the spacing.| +| initialIndex | number | No | Item displayed at the beginning of the viewport when the current list is loaded for the first time, that is, the first item to be displayed.
Default value: **0**
**NOTE**
If the set value is a negative number or is greater than the index of the last item in the list, the value is invalid. In this case, the default value will be used.| +| scroller | [Scroller](ts-container-scroll.md#scroller) | No | Scroller, which can be bound to scrollable components.
**NOTE**
The scroller cannot be bound to other scrollable components.| ## Attributes In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. -| Name| Type| Description| -| -------- | -------- | -------- | -| listDirection | [Axis](ts-appendix-enums.md#axis) | Direction in which the list items are arranged.
Default value: **Axis.Vertical**
Since API version 9, this API is supported in ArkTS widgets.| -| divider | {
strokeWidth: [Length](ts-types.md#length),
color?:[ResourceColor](ts-types.md#resourcecolor),
startMargin?: Length,
endMargin?: Length
} \| null | Style of the divider for the list items. By default, there is no divider.
- **strokeWidth**: stroke width of the divider.
- **color**: color of the divider.
- **startMargin**: distance between the divider and the start edge of the list.
- **endMargin**: distance between the divider and the end edge of the list.
Since API version 9, this API is supported in ArkTS widgets.
The sum of **endMargin** and **startMargin** cannot exceed the column width.
**startMargin** and **endMargin** cannot be set in percentage.
The divider is drawn between list items along the main axis, and not above the first list item and below the last list item.
In multi-column mode, the value of **startMargin** is calculated from the start edge of the cross axis of each column. In other cases, it is calculated from the start edge of the cross axis of the list.| -| scrollBar | [BarState](ts-appendix-enums.md#barstate) | Scrollbar status.
Default value: **BarState.Off**
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
In API version 9 and earlier versions, the default value is **BarState.Off**. In API version 10, the default value is **BarState.Auto**.| -| cachedCount | number | Number of list items or list item groups to be preloaded (cached). It works only in [LazyForEach](../../quick-start/arkts-rendering-control-lazyforeach.md). A list item group is calculated as a whole, and all list items of the group are preloaded at the same time. For details, see [Minimizing White Blocks During Swiping](../../ui/arkts-performance-improvement-recommendation.md#minimizing-white-blocks-during-swiping).
Default value: **1**
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
In single-column mode, the number of the list items to be cached before and after the currently displayed one equals the value of **cachedCount**.
In multi-column mode, the number of the list items to be cached is the value of **cachedCount** multiplied by the number of columns.| -| editMode(deprecated) | boolean | Whether to enter editing mode.
This API is deprecated since API version 9. For details about how to implement deletion of a selected list item, see [Example 3](#example-3).
Default value: **false**| -| edgeEffect | [EdgeEffect](ts-appendix-enums.md#edgeeffect) | Scroll effect. The spring effect and shadow effect are supported.
Default value: **EdgeEffect.Spring**
Since API version 9, this API is supported in ArkTS widgets.| -| chainAnimation | boolean | Whether to display chained animations on this list when it slides or its top or bottom is dragged. The list items are separated with even space, and one item animation starts after the previous animation during basic sliding interactions. The chained animation effect is similar with spring physics.
Default value: **false**
- **false**: No chained animations are displayed.
- **true**: Chained animations are displayed.
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
When chained animations are in motion, the list divider is not displayed.
The following prerequisites must be met for the chained animations to take effect:
- The edge effect of the list is of the Spring type.
- The multi-column mode is not enabled for the list.| -|chainAnimationOptions10+| [ChainAnimationOptions](#chainanimationoptions10) | Chained animation settings.
**System API**: This is a system API.| -| multiSelectable8+ | boolean | Whether to enable mouse frame selection.
Default value: **false**
- **false**: The mouse frame selection is disabled.
- **true**: The mouse frame selection is enabled.
Since API version 9, this API is supported in ArkTS widgets.| -| lanes9+ | number \| [LengthConstrain](ts-types.md#lengthconstrain) | In the following description, **listDirection** is set to **Axis.Vertical**:
Number of columns in which the list items are arranged along the cross axis.
Default value: **1**
The rules are as follows:
- If the value is set to a number, the column width is calculated by dividing the cross-axis width of the **\** component by the specified number.
- If the value is set to {minLength, maxLength}, the number of columns is adjusted adaptively based on the width of the **\** component, ensuring that the width respects the {minLength, maxLength} constraints during adaptation. The **minLength** constraint is prioritized.
- If the value is set to {minLength, maxLength}, and the cross-axis width constraint of the parent component is infinite, the parent component is arranged by column, and the column width is calculated based on the largest list item in the display area.
- Each list item group occupies one row in multi-column mode. Its child list items are arranged based on the **lanes** attribute of the list.
- If the value is set to {minLength, maxLength}, the number of columns is calculated based on the cross-axis width of the list item group. If the cross-axis width of the list item group is different from that of the list, the number of columns in the list item group may be different from that in the list.
This API is supported in ArkTS widgets.| -| alignListItem9+ | [ListItemAlign](#listitemalign9) | Alignment mode of list items along the cross axis when: Cross-axis width of the **\** component > Cross-axis width of list items x Value of **lanes**.
Default value: **ListItemAlign.Start**
This API is supported in ArkTS widgets.| -| sticky9+ | [StickyStyle](#stickystyle9) | Whether to pin the header to the top or the footer to the bottom in the **\** component. This attribute is used together with the **[\](ts-container-listitemgroup.md)** component.
Default value: **StickyStyle.None**
This API is supported in ArkTS widgets.
**NOTE**
The **sticky** attribute can be set to **StickyStyle.Header** or \| **StickyStyle.Footer** to support both the pin-to-top and pin-to-bottom features.| +| Name | Type | Description | +| ----------------------------------- | ---------------------------------------- | ---------------------------------------- | +| listDirection | [Axis](ts-appendix-enums.md#axis) | Direction in which the list items are arranged.
Default value: **Axis.Vertical**
Since API version 9, this API is supported in ArkTS widgets.| +| divider | {
strokeWidth: [Length](ts-types.md#length),
color?:[ResourceColor](ts-types.md#resourcecolor),
startMargin?: Length,
endMargin?: Length
} \| null | Style of the divider for the list items. By default, there is no divider.
- **strokeWidth**: stroke width of the divider.
- **color**: color of the divider.
- **startMargin**: distance between the divider and the start edge of the list.
- **endMargin**: distance between the divider and the end edge of the list.
Since API version 9, this API is supported in ArkTS widgets.
The sum of **endMargin** and **startMargin** cannot exceed the column width.
**startMargin** and **endMargin** cannot be set in percentage.
The divider is drawn between list items along the main axis, and not above the first list item and below the last list item.
In multi-column mode, the value of **startMargin** is calculated from the start edge of the cross axis of each column. In other cases, it is calculated from the start edge of the cross axis of the list.| +| scrollBar | [BarState](ts-appendix-enums.md#barstate) | Scrollbar status.
Default value: **BarState.Off**
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
In API version 9 and earlier versions, the default value is **BarState.Off**. In API version 10, the default value is **BarState.Auto**.| +| cachedCount | number | Number of list items or list item groups to be preloaded (cached). It works only in [LazyForEach](../../quick-start/arkts-rendering-control-lazyforeach.md). A list item group is calculated as a whole, and all list items of the group are preloaded at the same time. For details, see [Minimizing White Blocks During Swiping](../../ui/arkts-performance-improvement-recommendation.md#minimizing-white-blocks-during-swiping).
Default value: **1**
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
In single-column mode, the number of the list items to be cached before and after the currently displayed one equals the value of **cachedCount**.
In multi-column mode, the number of the list items to be cached is the value of **cachedCount** multiplied by the number of columns.| +| editMode(deprecated) | boolean | Whether to enter editing mode.
This API is deprecated since API version 9. For details about how to implement deletion of a selected list item, see [Example 3](#example-3).
Default value: **false**| +| edgeEffect | [EdgeEffect](ts-appendix-enums.md#edgeeffect) | Scroll effect. The spring effect and shadow effect are supported.
Default value: **EdgeEffect.Spring**
Since API version 9, this API is supported in ArkTS widgets.| +| chainAnimation | boolean | Whether to display chained animations on this list when it slides or its top or bottom is dragged. The list items are separated with even space, and one item animation starts after the previous animation during basic sliding interactions. The chained animation effect is similar with spring physics.
Default value: **false**
- **false**: No chained animations are displayed.
- **true**: Chained animations are displayed.
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
When chained animations are in motion, the list divider is not displayed.
The following prerequisites must be met for the chained animations to take effect:
- The edge effect of the list is of the Spring type.
- The multi-column mode is not enabled for the list.| +| chainAnimationOptions10+ | [ChainAnimationOptions](#chainanimationoptions10) | Chained animation settings.
**System API**: This is a system API. | +| multiSelectable8+ | boolean | Whether to enable mouse frame selection.
Default value: **false**
- **false**: The mouse frame selection is disabled.
- **true**: The mouse frame selection is enabled.
Since API version 9, this API is supported in ArkTS widgets.| +| lanes9+ | number \| [LengthConstrain](ts-types.md#lengthconstrain) | In the following description, **listDirection** is set to **Axis.Vertical**:
Number of columns in which the list items are arranged along the cross axis.
Default value: **1**
The rules are as follows:
- If the value is set to a number, the column width is calculated by dividing the cross-axis width of the **\** component by the specified number.
- If the value is set to {minLength, maxLength}, the number of columns is adjusted adaptively based on the width of the **\** component, ensuring that the width respects the {minLength, maxLength} constraints during adaptation. The **minLength** constraint is prioritized.
- If the value is set to {minLength, maxLength}, and the cross-axis width constraint of the parent component is infinite, the parent component is arranged by column, and the column width is calculated based on the largest list item in the display area.
- Each list item group occupies one row in multi-column mode. Its child list items are arranged based on the **lanes** attribute of the list.
- If the value is set to {minLength, maxLength}, the number of columns is calculated based on the cross-axis width of the list item group. If the cross-axis width of the list item group is different from that of the list, the number of columns in the list item group may be different from that in the list.
This API is supported in ArkTS widgets.| +| alignListItem9+ | [ListItemAlign](#listitemalign9) | Alignment mode of list items along the cross axis when: Cross-axis width of the **\** component > Cross-axis width of list items x Value of **lanes**.
Default value: **ListItemAlign.Start**
This API is supported in ArkTS widgets.| +| sticky9+ | [StickyStyle](#stickystyle9) | Whether to pin the header to the top or the footer to the bottom in the **\** component. This attribute is used together with the **[\](ts-container-listitemgroup.md)** component.
Default value: **StickyStyle.None**
This API is supported in ArkTS widgets.
**NOTE**
The **sticky** attribute can be set to **StickyStyle.Header** or \| **StickyStyle.Footer** to support both the pin-to-top and pin-to-bottom features.| ## ListItemAlign9+ This API is supported in ArkTS widgets. -| Name | Description | -| ------ | -------------------------------------- | +| Name | Description | +| ------ | ------------------------- | | Start | The list items are packed toward the start edge of the **\** component along the cross axis.| | Center | The list items are centered in the **\** component along the cross axis.| | End | The list items are packed toward the end edge of the **\** component along the cross axis.| @@ -78,11 +78,11 @@ This API is supported in ArkTS widgets. This API is supported in ArkTS widgets. -| Name | Description | -| ------ | -------------------------------------- | -| None | In the **\** component, the header is not pinned to the top, and the footer is not pinned to the bottom.| -| Header | In the **\** component, the header is pinned to the top, and the footer is not pinned to the bottom.| -| Footer | In the **\** component, the footer is pinned to the bottom, and the header is not pinned to the top.| +| Name | Description | +| ------ | ---------------------------------- | +| None | In the **\** component, the header is not pinned to the top, and the footer is not pinned to the bottom.| +| Header | In the **\** component, the header is pinned to the top, and the footer is not pinned to the bottom. | +| Footer | In the **\** component, the footer is pinned to the bottom, and the header is not pinned to the top. | ## ChainEdgeEffect10+ @@ -90,10 +90,10 @@ Describes the chained animation edge effect. **System API**: This is a system API. -| Name | Description | -| ------ | -------------------------------------- | -| DEFAULT | Default effect. After the list is scrolled to the edge, a continued drag of the list will result in reduced spacing between the list items in the drag direction and increased spacing between the list items in the direction opposite to the drag direction.| -| STRETCH | After the list is scrolled to the edge, a continued drag of the list result in increased spacing between all the list items.| +| Name | Description | +| ------- | ---------------------------------------- | +| DEFAULT | Default effect. After the list is scrolled to the edge, a continued drag of the list will result in reduced spacing between the list items in the drag direction and increased spacing between the list items in the direction opposite to the drag direction.| +| STRETCH | After the list is scrolled to the edge, a continued drag of the list result in increased spacing between all the list items. | ## chainAnimationOptions10+ @@ -101,13 +101,13 @@ Provides the chained animation settings, which cover the maximum spacing, minimu **System API**: This is a system API. -| Name | Type | Mandatory | Description | -| ------ | ------ | ---- | --------------- | -| minSpace | [Length](ts-types.md#length) | Yes | Minimum spacing between the chained animations.| -| maxSpace | [Length](ts-types.md#length) | Yes | Maximum spacing between the chained animations.| -| conductivity | number | No | Conductivity of the chained animations. The value range is [0,1]. A larger value indicates higher conductivity.
Default value: **0.7** | -| intensity | number | No | Intensity of the chained animations. The value range is [0,1]. A larger value indicates more obvious animations.
Default value: **0.3**| -| edgeEffect | [ChainEdgeEffect](#chainedgeeffect10)| No| Chained animation edge effect.
Default value: **ChainEdgeEffect.DEFAULT**| +| Name | Type | Mandatory | Description | +| ------------ | ---------------------------------------- | ---- | ---------------------------------------- | +| minSpace | [Length](ts-types.md#length) | Yes | Minimum spacing between the chained animations. | +| maxSpace | [Length](ts-types.md#length) | Yes | Maximum spacing between the chained animations. | +| conductivity | number | No | Conductivity of the chained animations. The value range is [0,1]. A larger value indicates higher conductivity.
Default value: **0.7**| +| intensity | number | No | Intensity of the chained animations. The value range is [0,1]. A larger value indicates more obvious animations.
Default value: **0.3**| +| edgeEffect | [ChainEdgeEffect](#chainedgeeffect10)| No | Chained animation edge effect.
Default value: **ChainEdgeEffect.DEFAULT**| > **NOTE** > @@ -115,16 +115,16 @@ Provides the chained animation settings, which cover the maximum spacing, minimu ## Events -| Name| Description| -| -------- | -------- | +| Name | Description | +| ---------------------------------------- | ---------------------------------------- | | onItemDelete(deprecated)(event: (index: number) => boolean) | Triggered when a list item is deleted.
This API is deprecated since API version 9.
- **index**: index of the deleted list item.| | onScroll(event: (scrollOffset: number, scrollState: ScrollState) => void) | Triggered when the list scrolls.
- **scrollOffset**: scroll offset of each frame. The offset is positive when the list is scrolled up and negative when the list is scrolled down.
- **[scrollState](#scrollstate)**: current scroll state.
This event is not triggered when **ScrollEdge** and **ScrollToIndex** are called by using the controller. In other cases, this event is triggered when scrolling occurs.
Since API version 9, this API is supported in ArkTS widgets.| | onScrollIndex(event: (start: number, end: number) => void) | Triggered when a child component enters or leaves the list display area.
During index calculation, each **\** component is taken as a whole and assigned an index, and the indexes of the list items within are not included in the calculation.
- **start**: index of the scroll start position.
- **end**: index of the scroll end position.
This event is triggered once when the list is initialized and when the index of the first list item or the next list item in the list display area changes.
When the list edge effect is the spring effect, the **onScrollIndex** event is not triggered when the user scrolls the list to the edge or releases the list to rebound.
Since API version 9, this API is supported in ArkTS widgets.| -| onReachStart(event: () => void) | Triggered when the list reaches the start position.
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
This event is triggered once when **initialIndex** is **0** during list initialization and once when the list scrolls to the start position. When the list edge effect is the spring effect, this event is triggered once when the list passes the start position and is triggered again when the list returns to the start position.| -| onReachEnd(event: () => void) | Triggered when the list reaches the end position.
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
When the list edge effect is the spring effect, this event is triggered once when the list passes the end position and is triggered again when the list returns to the end position.| +| onReachStart(event: () => void) | Triggered when the list reaches the start position.
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
This event is triggered once when **initialIndex** is **0** during list initialization and once when the list scrolls to the start position. When the list edge effect is the spring effect, this event is triggered once when the list passes the start position and is triggered again when the list returns to the start position.| +| onReachEnd(event: () => void) | Triggered when the list reaches the end position.
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
When the list edge effect is the spring effect, this event is triggered once when the list passes the end position and is triggered again when the list returns to the end position.| | onScrollFrameBegin9+(event: (offset: number, state: ScrollState) => { offsetRemain }) | Triggered when the list starts to scroll. The input parameters indicate the amount by which the list will scroll. The event handler then works out the amount by which the list needs to scroll based on the real-world situation and returns the result.
\- **offset**: amount to scroll by, in vp.
\- **state**: current sliding status.
- **offsetRemain**: actual amount by which the list scrolls, in vp.
This event is triggered when the user starts dragging the list or the list starts inertial scrolling. This event is not triggered when the list rebounds or the scrolling controller is used.
This API is supported in ArkTS widgets.
**NOTE**
If **listDirection** is set to **Axis.Vertical**, the return value is the amount by which the list needs to scroll in the vertical direction. If **listDirection** is set to **Axis.Horizontal**, the return value is the amount by which the list needs to scroll in the horizontal direction.| | onScrollStart9+(event: () => void) | Triggered when the list starts scrolling initiated by the user's finger dragging the **\** component or its scrollbar. This event is also triggered when the animation contained in the scrolling triggered by [Scroller](ts-container-scroll.md#scroller) starts.
This API is supported in ArkTS widgets.| -| onScrollStop(event: () => void) | Triggered when the list stops scrolling after the user's finger leaves the screen. This event is also triggered when the animation contained in the scrolling triggered by [Scroller](ts-container-scroll.md#scroller) stops.
Since API version 9, this API is supported in ArkTS widgets.| +| onScrollStop(event: () => void) | Triggered when the list stops scrolling after the user's finger leaves the screen. This event is also triggered when the animation contained in the scrolling triggered by [Scroller](ts-container-scroll.md#scroller) stops.
Since API version 9, this API is supported in ArkTS widgets.| | onItemMove(event: (from: number, to: number) => boolean) | Triggered when a list item moves.
- **from**: index of the item before moving.
- **to**: index of the item after moving.| | onItemDragStart(event: (event: ItemDragInfo, itemIndex: number) => ((() => any) \| void) | Triggered when a list element starts to be dragged.
- **event**: See [ItemDragInfo](ts-container-grid.md#itemdraginfo).
- **itemIndex**: index of the dragged list element.| | onItemDragEnter(event: (event: ItemDragInfo) => void) | Triggered when the dragged item enters the drop target of the list.
- **event**: See [ItemDragInfo](ts-container-grid.md#itemdraginfo).| @@ -136,11 +136,11 @@ Provides the chained animation settings, which cover the maximum spacing, minimu Since API version 9, this API is supported in ArkTS widgets. -| Name | Description | -| ------ | ------------------------- | -| Idle | Not scrolling. Triggered when the API provided by the controller is used to scroll the list or when the scrollbar is dragged.| -| Scroll | Finger dragging. Triggered when the user drags the list to scroll.| -| Fling | Inertial scrolling. Triggered when inertial scrolling occurs or when the list bounces back after being released from a quick swipe.| +| Name | Description | +| ------ | ------------------------------ | +| Idle | Not scrolling. Triggered when the API provided by the controller is used to scroll the list or when the scrollbar is dragged. | +| Scroll | Finger dragging. Triggered when the user drags the list to scroll. | +| Fling | Inertial scrolling. Triggered when inertial scrolling occurs or when the list bounces back after being released from a quick swipe.| > **NOTE** > @@ -158,8 +158,9 @@ Since API version 9, this API is supported in ArkTS widgets. > > - The list item is bound to the **onDragStart** event and the event returns a floating UI during event callback. +## Example -## Example 1 +### Example 1 ```ts // xxx.ets @@ -180,6 +181,7 @@ struct ListExample { }, item => item) } .listDirection(Axis.Vertical) // Arrangement direction + .scrollBar(BarState.Off) .divider({ strokeWidth: 2, color: 0xFFFFFF, startMargin: 20, endMargin: 20 }) // Divider .edgeEffect(EdgeEffect.Spring) // No effect when the list scrolls to the edge. .onScrollIndex((firstIndex: number, lastIndex: number) => { @@ -199,7 +201,7 @@ struct ListExample { ![en-us_image_0000001174264378](figures/en-us_image_0000001174264378.gif) -## Example 2 +### Example 2 ```ts // xxx.ets @@ -230,6 +232,7 @@ struct ListLanesExample { .border({ width: 3, color: Color.Red }) .lanes({ minLength: 40, maxLength: 40 }) .alignListItem(this.alignListItem) + .scrollBar(BarState.Off) Button("Change alignListItem: "+ this.alignListItem).onClick(() => { if (this.alignListItem == ListItemAlign.Start) { @@ -248,7 +251,7 @@ struct ListLanesExample { ![list](figures/list1.gif) -## Example 3 +### Example 3 ```ts // xxx.ets @@ -288,6 +291,7 @@ struct ListExample{ } }, item => item) }.width('90%') + .scrollBar(BarState.Off) }.width('100%') Button('edit list') diff --git a/en/application-dev/web/web-in-page-app-function-invoking.md b/en/application-dev/web/web-in-page-app-function-invoking.md index 6ef1ed5fa8f5e5fad67e96d20189209ca51016e1..a4e78204bcffce326169d0ee3ff3ca1a8392a2b5 100644 --- a/en/application-dev/web/web-in-page-app-function-invoking.md +++ b/en/application-dev/web/web-in-page-app-function-invoking.md @@ -89,10 +89,10 @@ The following example registers the **test()** function with the frontend page. > **NOTE** > - > If you use [registerJavaScriptProxy()](../reference/apis/js-apis-webview.md#registerjavascriptproxy) to register a function, call **[refresh()]**(../reference/apis/js-apis-webview.md#refresh) for the function to take effect. + > If you use [registerJavaScriptProxy()](../reference/apis/js-apis-webview.md#registerjavascriptproxy) to register a function, call [refresh()](../reference/apis/js-apis-webview.md#refresh) for the function to take effect. -- Sample code for invoking application functions on the **index.htm** frontend page: +- Sample code for invoking application functions on the **index.html** frontend page: ```html diff --git a/en/device-dev/device-test/figures/smartperf_frame.png b/en/device-dev/device-test/figures/smartperf_frame.png new file mode 100644 index 0000000000000000000000000000000000000000..4cd602ed03837c570efee4dc3887272414b391e5 Binary files /dev/null and b/en/device-dev/device-test/figures/smartperf_frame.png differ diff --git a/en/device-dev/device-test/smartperf-host.md b/en/device-dev/device-test/smartperf-host.md new file mode 100644 index 0000000000000000000000000000000000000000..ec92a1ba4c2c5ca57957702de1e9fe9c8cb54c9c --- /dev/null +++ b/en/device-dev/device-test/smartperf-host.md @@ -0,0 +1,83 @@ +# Smartperf-Host +## Overview +Smartperf-Host is an intuitive performance and power optimization tool that offers in-depth data mining and fine-grained data visualization. In this tool, you can gain visibility into a multitude of metrics in terms of CPU scheduling, frequency, process and thread time slices, heap memory, frame rate, and more, in swimlanes. Better yet, you can analyze the collected data intuitively on the GUI. +## Architecture +![System Architecture](figures/smartperf_frame.png) + +Smartperf-Host consists of the device end and PC end, which exchange data with each other based on gRPC – a high-performance remote procedure call (RPC) framework. + +The device end consists of modules such as Native Hook (application-embedded component), hiprofiler_command (command-line tool), hiprofilerd (performance profiler service), a set of performance profiler plug-ins, and some system tools and kernels. The device end provides the plug-in extension capability by exposing plug-in interfaces for external systems. By drawing on this capability, you can integrate custom plug-ins into the framework. For details about the preset plug-ins, see [Performance Profiler Component](https://gitee.com/openharmony/developtools_profiler). + +The PC end is accessible from the Smartperf-Host website. It consists of modules such as Trace Streamer, SQLite, HDC device management, data import, UI drawing, and data analysis. +## Project Directory +``` +/smartperf_host +├── host # Smartperf-Host related code +│ ├── doc # Smartperf-Host documentation +│ ├── ide # Smartperf-Host IDE module +│ │ └── src # Profiler module +│ │ │ ├── base-ui # Basic components +│ │ │ └── Trace # Service logic +│ ├── trace_streamer # Trace Streamer module +│ │ ├── base # Basic functionality +│ │ ├── cfg # Configuration +│ │ ├── filter # Filter +│ │ ├── include # Header files +│ │ ├── multi_platform # Platform adaptation +│ │ ├── parser # Parsing service logic +│ │ │ ├── bytrace_parser # byTrace service logic +│ │ │ └── htrace_parser # hTrace service logic +│ │ ├── table # Table structure +│ │ ├── trace_data # Trace structure +│ │ ├── trace_streamer # Trace Streamer structure +│ │ │ └── kits # JS APIs and native APIs +``` +## Function Description +- Loading Trace Files on Web Pages + + Load local trace files (such as htrace and ftrace) and display the data in swimlanes. For details, see [Loading Trace Files on Web Pages](https://gitee.com/openharmony-sig/developtools_smartperf_host/blob/master/ide/src/doc/md/quickstart_systemtrace.md). +- Capturing Traces Online + + Use Smartperf_Host to capture traces online, with the content, duration, and save path all customizable. For details, see [Capturing Traces on Web Pages](https://gitee.com/openharmony-sig/developtools_smartperf_host/blob/master/ide/src/doc/md/quickstart_web_record.md). +- Capturing Traces on a Device + + Capture traces on the target device, with the content, duration, and save path all customizable. For details, see [Capturing Traces from a Device](https://gitee.com/openharmony-sig/developtools_smartperf_host/blob/master/ide/src/doc/md/quickstart_device_record.md). +- Using Ability Monitor + + With Ability Monitor in Smartperf_Host, you can learn the CPU, memory, disk I/O, and network usage of your application. For details, see [Ability Monitor Usage](https://gitee.com/openharmony-sig/developtools_smartperf_host/blob/master/ide/src/doc/md/quickstart_ability_monitor.md). +- Using Native Memory + + With Native Memory in Smartperf_Host, you can track the allocation and release of your application's native memory (specific to C and C++). For details, see [Native Memory Usage](https://gitee.com/openharmony-sig/developtools_smartperf_host/blob/master/ide/src/doc/md/quickstart_native_memory.md). +- Using Hiperf + + With Hiperf in Smartperf_Host, you can view the CPU usage of your application and the call stack. For details, see [Hiperf Usage](https://gitee.com/openharmony-sig/developtools_smartperf_host/blob/master/ide/src/doc/md/quickstart_hiperf.md). +- Using HiSystemEvent + + With HiSystemEvent in Smartperf_Host, you can inspect the power consumption of each category (CPU, network, and location, and more) of your application, resource application and usage records (WorkScheduler, Runninglock, Alarm, and Location Request), power consumption exceptions, and system states associated with the power consumption (battery level and screen status). For details, see [HiSystemEvent Usage](https://gitee.com/openharmony-sig/developtools_smartperf_host/blob/master/ide/src/doc/md/quickstart_hisystemevent.md). +- Collecting FileSystem Records + + In Smartperf_Host, you can find out the system invoking information and read/write invoking times of all file systems. For details, see [Usage of FileSystem Recording](https://gitee.com/openharmony-sig/developtools_smartperf_host/blob/master/ide/src/doc/md/quickstart_filesystem.md). +- Collecting Page Fault Records + + In Smartperf_Host, you can collect page fault records, covering various aspects such as start time, duration, triggering process, triggering thread, event type, memory address, and memory size of page memory events. For details, see [Usage of Page Fault Recording](https://gitee.com/openharmony-sig/developtools_smartperf_host/blob/master/ide/src/doc/md/quickstart_page_fault.md). +- Collecting BIO Records + + In Smartperf_Host, you can collect I/O operation records, which provide the following information: start time, total latency, process, average latency of every 4 KB data, thread, operation (write data, page swap-in, and metadata), access traffic, path, block number, priority, and backtrace call stack. For details, see [Usage of BIO Latency Recording](https://gitee.com/openharmony-sig/developtools_smartperf_host/blob/master/ide/src/doc/md/quickstart_bio.md). +- Collecting Smaps Records + + In Smartperf_Host, you can collect the smaps data (type, Pss, Rss, Vss, and more) on a process-by-process basis. The data source is **/proc/$pid/smaps**. For details, see [Smaps Usage](https://gitee.com/openharmony-sig/developtools_smartperf_host/blob/master/ide/src/doc/md/quickstart_smaps.md). +- Using SQL Analysis and Metrics + + You can use Query (SQL) and Metrics features to quickly locate the trace data. For details, see [SQL Analysis and Metrics Usage](https://gitee.com/openharmony-sig/developtools_smartperf_host/blob/master/ide/src/doc/md/quickstart_sql_metrics.md). +## Compilation Guidance +Project compilation includes Trace Streamer compilation and Smartperf-Host compilation and deployment. +### Prerequisites +- C++ version: 11 or later +- Node.js version: 16.15.1 or later +- npm version: 8.13.2 or later +- TypeScript version: 4.2.3 or later +- Go version: 1.13.8 or later +### Compiling Trace Streamer +To set up the Smartperf_Host website, you need to compile the WASM version of Trace Streamer for the web page to parse the original trace data. For details about the compilation process, see [Compiling Trace Streamer](https://gitee.com/openharmony-sig/developtools_smartperf_host/blob/master/trace_streamer/doc/compile_trace_streamer.md). +### Compiling and Deploying Smartperf-Host +For details about the compilation and deployment process, see [SmartPerf Compilation and Deployment Guide](https://gitee.com/openharmony-sig/developtools_smartperf_host/blob/master/ide/README_zh.md)). After successful deployment, you can start to use Smartperf_Host by visiting **https://[*IP address of the device where SmartPerf is deployed*]:9000/application/**.