提交 3459023e 编写于 作者: E ester.zhou

Update docs (9929)

Signed-off-by: Nester.zhou <ester.zhou@huawei.com>
上级 cffd13e8
......@@ -2,17 +2,15 @@
The **\<RichText>** component parses and displays HTML text.
> **NOTE**
> **NOTE**
>
> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
None
## Child Components
None
Not supported
## APIs
......@@ -20,9 +18,9 @@ RichText(content:string)
**Parameters**
| Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- |
| content | string | Yes| - | String in HTML format.|
| Name| Type| Mandatory | Description|
| ------- | -------- | ------------- | -------- |
| content | string | Yes | String in HTML format.|
## Events
......@@ -49,34 +47,38 @@ RichText(content:string)
| \<script>\</script> | Used to embed or reference a client-side script, such as JavaScript.| \<script>document.write("Hello World!")\</script> |
## Example
You can preview how this component looks on a real device. The preview is not yet available in the DevEco Studio Previewer.
```ts
// xxx.ets
@Entry
@Component
struct RichTextExample {
@State data: string = "<h1 style='text-align: center;'>h1 heading</h1>" +
"<h1 style='text-align: center;'><i>h1 italic</i></h1>" +
"<h1 style='text-align: center;'><u>h1 underlined</u></h1>" +
"<h2 style='text-align: center;'>h2 heading</h2>" +
"<h3 style='text-align: center;'>h3 heading</h3>" +
"<p style='text-align: center;'>Regular paragraph</p><hr/>" +
"<div style='width: 500px;height: 500px;border: 1px solid;margin: 0auto;'>" +
"<p style='font-size: 35px;text-align: center;font-weight: bold; color: rgb(24,78,228)'>Font size: 35px; line height: 45px</p>" +
"<p style='background-color: #e5e5e5;line-height: 45px;font-size: 35px;text-indent: 2em;'>" +
"<p>This is a paragraph. This is a paragraph. This is a paragraph. This is a paragraph. This is a paragraph. This is a paragraph. This is a paragraph. This is a paragraph. This is a paragraph.</p>"
@State data: string = '<h1 style="text-align: center;">h1 heading</h1>' +
'<h1 style="text-align: center;"><i>h1 italic</i></h1>' +
'<h1 style="text-align: center;"><u>h1 underlined</u></h1>' +
'<h2 style="text-align: center;">h2 heading</h2>' +
'<h3 style="text-align: center;">h3 heading</h3>' +
'<p style="text-align: center;">Regular paragraph</p><hr/>' +
'<div style="width: 500px;height: 500px;border: 1px solid;margin: 0auto;">' +
'<p style="font-size: 35px;text-align: center;font-weight: bold; color: rgb(24,78,228)">Font size: 35px; line height: 45px</p>' +
'<p style="background-color: #e5e5e5;line-height: 45px;font-size: 35px;text-indent: 2em;">' +
'<p>This is a paragraph. This is a paragraph. This is a paragraph. This is a paragraph. This is a paragraph. This is a paragraph. This is a paragraph. This is a paragraph. This is a paragraph.</p>';
build() {
Flex({direction: FlexDirection.Column,alignItems: ItemAlign.Center,
justifyContent: FlexAlign.Center }){
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center,
justifyContent: FlexAlign.Center }) {
RichText(this.data)
.onStart(()=>{
console.info("RichText onStart")
})
.onComplete(()=>{
console.info("RichText onComplete")
})
.onStart(() => {
console.info('RichText onStart');
})
.onComplete(() => {
console.info('RichText onComplete');
})
}
}
}
```
![richText](figures/richText.png)
......@@ -16,7 +16,7 @@ SwipeGesture(value?: { fingers?: number; direction?: SwipeDirection; speed?: num
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| fingers | number | No| Minimum number of fingers to trigger a swipe gesture. The value ranges from 1 to 10.<br>Default value: **1**|
| direction | SwipeDirection | No| Swipe direction.<br>Default value: **SwipeDirection.All**|
| direction | [swipeDirection](#swipedirection)| No| Swipe direction.<br>Default value: **SwipeDirection.All**|
| speed | number | No| Minimum speed of the swipe gesture, in vp/s.<br>Default value: **100**|
## SwipeDirection
......@@ -24,8 +24,8 @@ SwipeGesture(value?: { fingers?: number; direction?: SwipeDirection; speed?: num
| Name| Description|
| -------- | -------- |
| All | All directions.|
| Horizontal | Horizontal direction.|
| Vertical | Vertical direction.|
| Horizontal | Horizontal direction. The gesture event is triggered when the angle between the finger moving direction and the x-axis is less than 45 degrees.|
| Vertical | Vertical direction. The gesture event is triggered when the angle between the finger moving direction and the y-axis is less than 45 degrees.|
| None | Swiping disabled.|
......@@ -33,9 +33,8 @@ SwipeGesture(value?: { fingers?: number; direction?: SwipeDirection; speed?: num
| Name| Description|
| -------- | -------- |
| onAction(event:(event?: [GestureEvent](ts-gesture-settings.md)) =&gt; void) | Triggered when a swipe gesture is recognized.|
| onAction(event:(event?: [GestureEvent](ts-gesture-settings.md#gestureevent)) =&gt; void) | Triggered when a swipe gesture is recognized.|
![en-us_image_0000001231374661](figures/en-us_image_0000001231374661.png)
## Example
```ts
......@@ -43,27 +42,31 @@ SwipeGesture(value?: { fingers?: number; direction?: SwipeDirection; speed?: num
@Entry
@Component
struct SwipeGestureExample {
@State rotateAngle : number = 0
@State speed : number = 1
@State rotateAngle: number = 0;
@State speed: number = 1;
build() {
Column() {
Text("SwipGesture speed : " + this.speed)
Text("SwipGesture angle : " + this.rotateAngle)
}
.position({x: 80, y: 200})
.border({width:2})
.width(260).height(260)
.rotate({x: 0, y: 0, z: 1, angle: this.rotateAngle})
.gesture(
SwipeGesture({fingers: 1, direction: SwipeDirection.Vertical})
Column() {
Text("SwipeGesture speed\n" + this.speed)
Text("SwipeGesture angle\n" + this.rotateAngle)
}
.border({ width: 3 })
.width(300)
.height(200)
.margin(100)
.rotate({ angle: this.rotateAngle })
// The gesture event is triggered by swiping vertically with one finger.
.gesture(
SwipeGesture({ direction: SwipeDirection.Vertical })
.onAction((event: GestureEvent) => {
this.speed = event.speed
this.rotateAngle = event.angle
})
)
this.speed = event.speed;
this.rotateAngle = event.angle;
})
)
}.width('100%')
}
}
```
![en-us_image_0000001231374559](figures/en-us_image_0000001231374559.gif)
![en-us_image_0000001231374559.png](figures/en-us_image_0000001231374559.png)
......@@ -3,13 +3,10 @@
**Lottie** allows you to implement animation-specific operations.
> **NOTE**
>
> The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
None
## Modules to Import
......@@ -19,7 +16,7 @@ import lottie from '@ohos/lottieETS'
> **NOTE**
>
> In the **Terminal** window, run the `npm install @ohos/lottieETS` command to download Lottie.
> In the **Terminal** window, run the `npm install @ohos/lottieETS` command to download Lottie. The download requires the related permission.
>
> To install an OpenHarmony npm third-party package, run the `npm config set @ohos:registry=https://repo.harmonyos.com/npm/` command to set the repository address.
......@@ -32,16 +29,17 @@ path: string, container: object, render: string, loop: boolean, autoplay: boolea
Loads an animation. Before calling this method, declare the **Animator('\__lottie\_ets')** object and check that the canvas layout is complete. This method can be used together with a lifecycle callback of the **Canvas** component, for example, **onAppear()** and **onPageShow()**.
- Parameters
| Name | Type | Mandatory | Description |
| -------------- | --------------------------- | ---- | ---------------------------------------- |
| path | string | Yes | Path of the animation resource file in the HAP file. The resource file must be in JSON format. Example: **path: "common/lottie/data.json"**|
| container | object | Yes | Canvas drawing context. A **CanvasRenderingContext2D** object must be declared in advance.|
| render | string | Yes | Rendering type. The value can only be **"canvas"**. |
| loop | boolean \| number | No | If the value is of the Boolean type, this parameter indicates whether to repeat the animation cyclically after the animation ends; the default value is **true**. If the value is of the number type and is greater than or equal to 1, this parameter indicates the number of times the animation plays.|
| autoplay | boolean | No | Whether to automatically play the animation. The default value is **true**. |
| name | string | No | Custom animation name. In later versions, the name can be used to reference and control the animation. The default value is null. |
| initialSegment | [number, number] | No | Start frame and end frame of the animation, respectively. |
**Parameters**
| Name | Type | Mandatory | Description |
| -------------- | --------------------------- | ---- | ---------------------------------------- |
| path | string | Yes | Path of the animation resource file in the HAP file. The resource file must be in JSON format. Example: **path: "common/lottie/data.json"**|
| container | object | Yes | Canvas drawing context. A **CanvasRenderingContext2D** object must be declared in advance.|
| render | string | Yes | Rendering type. The value can only be **"canvas"**. |
| loop | boolean \| number | No | If the value is of the Boolean type, this parameter indicates whether to repeat the animation cyclically after the animation ends; the default value is **true**. If the value is of the number type and is greater than or equal to 1, this parameter indicates the number of times the animation plays.|
| autoplay | boolean | No | Whether to automatically play the animation. The default value is **true**. |
| name | string | No | Custom animation name. In later versions, the name can be used to reference and control the animation. The default value is null. |
| initialSegment | [number, number] | No | Start frame and end frame of the animation, respectively. |
## lottie.destroy
......@@ -50,12 +48,13 @@ destroy(name: string): void
Destroys the animation. This method must be called when a page exits. This method can be used together with a lifecycle callback of the **Canvas** component, for example, **onDisappear()** and **onPageHide()**.
- Parameters
| Name | Type | Mandatory | Description |
| ---- | ------ | ---- | ---------------------------------------- |
| name | string | Yes | Name of the animation to destroy, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are destroyed.|
**Parameters**
| Name | Type | Mandatory | Description |
| ---- | ------ | ---- | ---------------------------------------- |
| name | string | Yes | Name of the animation to destroy, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are destroyed.|
- Example
**Example**
```ts
// xxx.ets
import lottie from '@ohos/lottieETS'
......@@ -130,12 +129,14 @@ play(name: string): void
Plays a specified animation.
- Parameters
| Name | Type | Mandatory | Description |
| ---- | ------ | ---- | ---------------------------------------- |
| name | string | Yes | Name of the animation to play, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are played.|
**Parameters**
| Name | Type | Mandatory | Description |
| ---- | ------ | ---- | ---------------------------------------- |
| name | string | Yes | Name of the animation to play, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are played.|
**Example**
- Example
```ts
lottie.play(this.animateName)
```
......@@ -147,12 +148,14 @@ pause(name: string): void
Pauses a specified animation. The next time **lottie.play()** is called, the animation starts from the current frame.
- Parameters
| Name | Type | Mandatory | Description |
| ---- | ------ | ---- | ---------------------------------------- |
| name | string | Yes | Name of the animation to pause, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are paused.|
**Parameters**
| Name | Type | Mandatory | Description |
| ---- | ------ | ---- | ---------------------------------------- |
| name | string | Yes | Name of the animation to pause, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are paused.|
**Example**
- Example
```ts
lottie.pause(this.animateName)
```
......@@ -164,12 +167,14 @@ togglePause(name: string): void
Pauses or plays a specified animation. This method is equivalent to the switching between **lottie.play()** and **lottie.pause()**.
- Parameters
| Name | Type | Mandatory | Description |
| ---- | ------ | ---- | ---------------------------------------- |
| name | string | Yes | Name of the target animation, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are paused.|
**Parameters**
| Name | Type | Mandatory | Description |
| ---- | ------ | ---- | ---------------------------------------- |
| name | string | Yes | Name of the target animation, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are paused.|
**Example**
- Example
```ts
lottie.togglePause(this.animateName)
```
......@@ -181,12 +186,14 @@ stop(name: string): void
Stops the specified animation. The next time **lottie.play()** is called, the animation starts from the first frame.
- Parameters
| Name | Type | Mandatory | Description |
| ---- | ------ | ---- | ---------------------------------------- |
| name | string | Yes | Name of the target animation, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are paused.|
**Parameters**
| Name | Type | Mandatory | Description |
| ---- | ------ | ---- | ---------------------------------------- |
| name | string | Yes | Name of the target animation, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are paused.|
**Example**
- Example
```ts
lottie.stop(this.animateName)
```
......@@ -198,13 +205,15 @@ setSpeed(speed: number, name: string): void
Sets the playback speed of the specified animation.
- Parameters
| Name | Type | Mandatory | Description |
| ----- | ------ | ---- | ---------------------------------------- |
| speed | number | Yes | Playback speed. The value is a floating-point number. If the value is greater than 0, the animation plays in forward direction. If the value is less than 0, the animation plays in reversed direction. If the value is 0, the animation is paused. If the value is 1.0 or -1.0, the animation plays at the normal speed.|
| name | string | Yes | Name of the target animation, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are stopped.|
**Parameters**
| Name | Type | Mandatory | Description |
| ----- | ------ | ---- | ---------------------------------------- |
| speed | number | Yes | Playback speed. The value is a floating-point number. If the value is greater than 0, the animation plays in forward direction. If the value is less than 0, the animation plays in reversed direction. If the value is 0, the animation is paused. If the value is 1.0 or -1.0, the animation plays at the normal speed.|
| name | string | Yes | Name of the target animation, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are stopped.|
**Example**
- Example
```ts
lottie.setSpeed(5, this.animateName)
```
......@@ -216,13 +225,15 @@ setDirection(direction: AnimationDirection, name: string): void
Sets the direction in which the specified animation plays.
- Parameters
| Name | Type | Mandatory | Description |
| --------- | ------------------ | ---- | ---------------------------------------- |
| direction | AnimationDirection | Yes | Direction in which the animation plays. **1**: forwards; **-1**: backwards. When set to play backwards, the animation plays from the current playback progress to the first frame. When this setting is combined with **loop** being set to **true**, the animation plays backwards continuously. When the value of **speed** is less than 0, the animation also plays backwards.<br>AnimationDirection: 1 \| -1 |
| name | string | Yes | Name of the target animation, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are set.|
**Parameters**
| Name | Type | Mandatory | Description |
| --------- | ------------------ | ---- | ---------------------------------------- |
| direction | AnimationDirection | Yes | Direction in which the animation plays. **1**: forwards; **-1**: backwards. When set to play backwards, the animation plays from the current playback progress to the first frame. When this setting is combined with **loop** being set to **true**, the animation plays backwards continuously. When the value of **speed** is less than 0, the animation also plays backwards.<br>AnimationDirection: 1 \| -1 |
| name | string | Yes | Name of the target animation, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are set.|
**Example**
- Example
```ts
lottie.setDirection(-1, this.animateName)
```
......@@ -262,12 +273,14 @@ play(name?: string): void
Plays an animation.
- Parameters
| Name | Type | Mandatory | Description |
| ---- | ------ | ---- | --------------- |
| name | string | No | Name of the target animation. By default, the value is null.|
**Parameters**
| Name | Type | Mandatory | Description |
| ---- | ------ | ---- | --------------- |
| name | string | No | Name of the target animation. By default, the value is null.|
**Example**
- Example
```ts
this.animateItem.play()
```
......@@ -279,12 +292,14 @@ destroy(name?: string): void
Destroys an animation.
- Parameters
| Name | Type | Mandatory | Description |
| ---- | ------ | ---- | --------------- |
| name | string | No | Name of the target animation. By default, the value is null.|
**Parameters**
| Name | Type | Mandatory | Description |
| ---- | ------ | ---- | --------------- |
| name | string | No | Name of the target animation. By default, the value is null.|
**Example**
- Example
```ts
this.animateItem.destroy()
```
......@@ -296,12 +311,14 @@ pause(name?: string): void
Pauses an animation. When the **play** interface is called next time, the animation is played from the current frame.
- Parameters
| Name | Type | Mandatory | Description |
| ---- | ------ | ---- | --------------- |
| name | string | No | Name of the target animation. By default, the value is null.|
**Parameters**
| Name | Type | Mandatory | Description |
| ---- | ------ | ---- | --------------- |
| name | string | No | Name of the target animation. By default, the value is null.|
**Example**
- Example
```ts
this.animateItem.pause()
```
......@@ -313,12 +330,14 @@ togglePause(name?: string): void
Pauses or plays an animation. This method is equivalent to the switching between **play** and **pause**.
- Parameters
| Name | Type | Mandatory | Description |
| ---- | ------ | ---- | --------------- |
| name | string | No | Name of the target animation. By default, the value is null.|
**Parameters**
| Name | Type | Mandatory | Description |
| ---- | ------ | ---- | --------------- |
| name | string | No | Name of the target animation. By default, the value is null.|
**Example**
- Example
```ts
this.animateItem.togglePause()
```
......@@ -330,12 +349,14 @@ stop(name?: string): void
Stops an animation. When the **play** interface is called next time, the animation is played from the first frame.
- Parameters
| Name | Type | Mandatory | Description |
| ---- | ------ | ---- | --------------- |
| name | string | No | Name of the target animation. By default, the value is null.|
**Parameters**
| Name | Type | Mandatory | Description |
| ---- | ------ | ---- | --------------- |
| name | string | No | Name of the target animation. By default, the value is null.|
**Example**
- Example
```ts
this.animateItem.stop()
```
......@@ -347,12 +368,14 @@ setSpeed(speed: number): void
Sets the playback speed of an animation.
- Parameters
| Name | Type | Mandatory | Description |
| ----- | ------ | ---- | ---------------------------------------- |
| speed | number | Yes | Playback speed. The value is a floating-point number. If the value is greater than 0, the animation plays forward. If the value is less than 0, the animation plays backward. If the value is 0, the animation is paused.|If the value is **1.0** or **-1.0**, the animation plays at the normal speed.|
**Parameters**
| Name | Type | Mandatory | Description |
| ----- | ------ | ---- | ---------------------------------------- |
| speed | number | Yes | Playback speed. The value is a floating-point number. If the value is greater than 0, the animation plays forward. If the value is less than 0, the animation plays backward. If the value is 0, the animation is paused.|If the value is **1.0** or **-1.0**, the animation plays at the normal speed.|
**Example**
- Example
```ts
this.animateItem.setSpeed(5);
```
......@@ -364,12 +387,14 @@ setDirection(direction: AnimationDirection): void
Sets the playback direction of an animation.
- Parameters
| Name | Type | Mandatory | Description |
| --------- | ------------------ | ---- | ---------------------------------------- |
| direction | AnimationDirection | Yes | Direction in which the animation plays. **1**: forwards; **-1**: backwards. When set to play backwards, the animation plays from the current playback progress to the first frame. When this setting is combined with **loop** being set to **true**, the animation plays backwards continuously. When the value of **speed** is less than 0, the animation also plays backwards.<br>AnimationDirection: 1 \| -1.|
**Parameters**
| Name | Type | Mandatory | Description |
| --------- | ------------------ | ---- | ---------------------------------------- |
| direction | AnimationDirection | Yes | Direction in which the animation plays. **1**: forwards; **-1**: backwards. When set to play backwards, the animation plays from the current playback progress to the first frame. When this setting is combined with **loop** being set to **true**, the animation plays backwards continuously. When the value of **speed** is less than 0, the animation also plays backwards.<br>AnimationDirection: 1 \| -1.|
**Example**
- Example
```ts
this.animateItem.setDirection(-1)
```
......@@ -381,14 +406,16 @@ goToAndStop(value: number, isFrame?: boolean): void
Sets the animation to stop at the specified frame or time.
- Parameters
| Name | Type | Mandatory | Description |
| ------- | ------- | ---- | ---------------------------------------- |
| value | number | Yes | Frame ID (greater than or equal to 0) or time progress (ms) at which the animation will stop. |
| isFrame | boolean | No | Whether to set the animation to stop at the specified frame. The value **true** means to set the animation to stop at the specified frame, and **false** means to set the animation to stop at the specified time progress. The default value is **false**.|
| name | string | No | Name of the target animation. By default, the value is null. |
**Parameters**
| Name | Type | Mandatory | Description |
| ------- | ------- | ---- | ---------------------------------------- |
| value | number | Yes | Frame ID (greater than or equal to 0) or time progress (ms) at which the animation will stop. |
| isFrame | boolean | No | Whether to set the animation to stop at the specified frame. The value **true** means to set the animation to stop at the specified frame, and **false** means to set the animation to stop at the specified time progress. The default value is **false**.|
| name | string | No | Name of the target animation. By default, the value is null. |
**Example**
- Example
```ts
// Set the animation to stop at the specified frame.
this.animateItem.goToAndStop(25, true)
......@@ -403,14 +430,16 @@ goToAndPlay(value: number, isFrame: boolean, name?: string): void
Sets the animation to start from the specified frame or time progress.
- Parameters
| Name | Type | Mandatory | Description |
| ------- | ------- | ---- | ---------------------------------------- |
| value | number | Yes | Frame ID (greater than or equal to 0) or time progress (ms) at which the animation will start. |
| isFrame | boolean | Yes | Whether to set the animation to start from the specified frame. The value **true** means to set the animation to start from the specified frame, and **false** means to set the animation to start from the specified time progress. The default value is **false**.|
| name | string | No | Name of the target animation. By default, the value is null. |
**Parameters**
| Name | Type | Mandatory | Description |
| ------- | ------- | ---- | ---------------------------------------- |
| value | number | Yes | Frame ID (greater than or equal to 0) or time progress (ms) at which the animation will start. |
| isFrame | boolean | Yes | Whether to set the animation to start from the specified frame. The value **true** means to set the animation to start from the specified frame, and **false** means to set the animation to start from the specified time progress. The default value is **false**.|
| name | string | No | Name of the target animation. By default, the value is null. |
**Example**
- Example
```ts
// Set the animation to stop at the specified frame.
this.animateItem.goToAndPlay(25, true)
......@@ -425,13 +454,15 @@ playSegments(segments: AnimationSegment | AnimationSegment[], forceFlag: boolean
Sets the animation to play only the specified segment.
- Parameters
| Name | Type | Mandatory | Description |
| --------- | ---------------------------------------- | ---- | ---------------------------------------- |
| segments | AnimationSegment = [number, number] \| AnimationSegment[] | Yes | Segment or segment list.<br>If all segments in the segment list are played, only the last segment is played in the next cycle.|
| forceFlag | boolean | Yes | Whether the settings take effect immediately. The value **true** means the settings take effect immediately, and **false** means the settings take effect until the current cycle of playback is completed. |
**Parameters**
| Name | Type | Mandatory | Description |
| --------- | ---------------------------------------- | ---- | ---------------------------------------- |
| segments | AnimationSegment = [number, number] \| AnimationSegment[] | Yes | Segment or segment list.<br>If all segments in the segment list are played, only the last segment is played in the next cycle.|
| forceFlag | boolean | Yes | Whether the settings take effect immediately. The value **true** means the settings take effect immediately, and **false** means the settings take effect until the current cycle of playback is completed. |
**Example**
- Example
```ts
// Set the animation to play the specified segment.
this.animateItem.playSegments([10, 20], false)
......@@ -446,12 +477,14 @@ resetSegments(forceFlag: boolean): void
Resets the settings configured by the **playSegments** method to play all the frames.
- Parameters
| Name | Type | Mandatory | Description |
| --------- | ------- | ---- | ------------------------------ |
| forceFlag | boolean | Yes | Whether the settings take effect immediately. The value **true** means the settings take effect immediately, and **false** means the settings take effect until the current cycle of playback is completed.|
**Parameters**
| Name | Type | Mandatory | Description |
| --------- | ------- | ---- | ------------------------------ |
| forceFlag | boolean | Yes | Whether the settings take effect immediately. The value **true** means the settings take effect immediately, and **false** means the settings take effect until the current cycle of playback is completed.|
**Example**
- Example
```ts
this.animateItem.resetSegments(true)
```
......@@ -463,7 +496,8 @@ resize(): void
Resizes the animation layout.
- Example
**Example**
```ts
this.animateItem.resize()
```
......@@ -475,12 +509,14 @@ setSubframe(useSubFrame: boolean): void
Sets the precision of the **currentFrame** attribute to display floating-point numbers.
- Parameters
| Name | Type | Mandatory | Description |
| ------------ | ------- | ---- | ---------------------------------------- |
| useSubFrames | boolean | Yes | Whether the **currentFrame** attribute displays floating-point numbers. By default, the attribute displays floating-point numbers.<br>**true**: The **currentFrame** attribute displays floating-point numbers.<br>**false**: The **currentFrame** attribute displays an integer and does not display floating-point numbers.|
**Parameters**
| Name | Type | Mandatory | Description |
| ------------ | ------- | ---- | ---------------------------------------- |
| useSubFrames | boolean | Yes | Whether the **currentFrame** attribute displays floating-point numbers. By default, the attribute displays floating-point numbers.<br>**true**: The **currentFrame** attribute displays floating-point numbers.<br>**false**: The **currentFrame** attribute displays an integer and does not display floating-point numbers.|
**Example**
- Example
```ts
this.animateItem.setSubframe(false)
```
......@@ -492,12 +528,14 @@ getDuration(inFrames?: boolean): void
Obtains the duration (irrelevant to the playback speed) or number of frames for playing an animation sequence. The settings are related to the input parameter **initialSegment** of the **Lottie.loadAnimation** interface.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | ------- | ---- | ---------------------------------------- |
| inFrames | boolean | No | Whether to obtain the duration or number of frames.<br>**true**: number of frames.<br>**false**: duration, in ms. The default value is **false**.|
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ------- | ---- | ---------------------------------------- |
| inFrames | boolean | No | Whether to obtain the duration or number of frames.<br>**true**: number of frames.<br>**false**: duration, in ms.<br>Default value: **false**|
**Example**
- Example
```ts
this.animateItem.getDuration(true)
```
......@@ -509,13 +547,15 @@ addEventListener&lt;T = any&gt;(name: AnimationEventName, callback: AnimationEve
Adds an event listener. After the event is complete, the specified callback function is triggered. This method returns the function object that can delete the event listener.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | ------------------------------- | ---- | ---------------------------------------- |
| name | AnimationEventName | Yes | Animation event type. The available options are as follows:<br>'enterFrame', 'loopComplete', 'complete', 'segmentStart', 'destroy', 'config_ready', 'data_ready', 'DOMLoaded', 'error', 'data_failed', 'loaded_images'|
| callback | AnimationEventCallback&lt;T&gt; | Yes | Custom callback. |
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ------------------------------- | ---- | ---------------------------------------- |
| name | AnimationEventName | Yes | Animation event type. The available options are as follows:<br>'enterFrame', 'loopComplete', 'complete', 'segmentStart', 'destroy', 'config_ready', 'data_ready', 'DOMLoaded', 'error', 'data_failed', 'loaded_images'|
| callback | AnimationEventCallback&lt;T&gt; | Yes | Custom callback. |
**Example**
- Example
```ts
private callbackItem: any = function() {
console.log("grunt loopComplete")
......@@ -533,13 +573,15 @@ removeEventListener&lt;T = any&gt;(name: AnimationEventName, callback?: Animatio
Removes an event listener.
- Parameters
| Name | Type | Mandatory | Description |
| -------- | ------------------------------- | ---- | ---------------------------------------- |
| name | AnimationEventName | Yes | Animation event type. The available options are as follows:<br>'enterFrame', 'loopComplete', 'complete', 'segmentStart', 'destroy', 'config_ready', 'data_ready', 'DOMLoaded', 'error', 'data_failed', 'loaded_images'|
| callback | AnimationEventCallback&lt;T&gt; | No | Custom callback. By default, the value is null, meaning that all callbacks of the event will be removed. |
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ------------------------------- | ---- | ---------------------------------------- |
| name | AnimationEventName | Yes | Animation event type. The available options are as follows:<br>'enterFrame', 'loopComplete', 'complete', 'segmentStart', 'destroy', 'config_ready', 'data_ready', 'DOMLoaded', 'error', 'data_failed', 'loaded_images'|
| callback | AnimationEventCallback&lt;T&gt; | No | Custom callback. By default, the value is null, meaning that all callbacks of the event will be removed. |
**Example**
- Example
```ts
this.animateItem.removeEventListener('loopComplete', this.animateName)
```
......@@ -551,13 +593,15 @@ triggerEvent&lt;T = any&gt;(name: AnimationEventName, args: T): void
Directly triggers all configured callbacks of a specified event.
- Parameters
| Name | Type | Mandatory | Description |
| ---- | ------------------ | ---- | --------- |
| name | AnimationEventName | Yes | Animation event type. |
| args | any | Yes | Custom callback parameters.|
**Parameters**
| Name | Type | Mandatory | Description |
| ---- | ------------------ | ---- | --------- |
| name | AnimationEventName | Yes | Animation event type. |
| args | any | Yes | Custom callback parameters.|
**Example**
- Example
```ts
private triggerCallBack: any = function(item) {
console.log("trigger loopComplete, name:" + item.name)
......
......@@ -29,7 +29,7 @@ Creates a standard **\<Flex>** component.
| direction | [FlexDirection](ts-appendix-enums.md#flexdirection) | No | FlexDirection.Row | Direction in which child components are arranged in the **\<Flex>** component, that is, the direction of the main axis. |
| wrap | [FlexWrap](ts-appendix-enums.md#flexwrap) | No | FlexWrap.NoWrap | Whether the **\<Flex>** component has a single line or multiple lines. |
| justifyContent | [FlexAlign](ts-appendix-enums.md#flexalign) | No | FlexAlign.Start | Alignment mode of the child components in the **\<Flex>** component along the main axis. |
| alignItems | [ItemAlign](ts-appendix-enums.md#itemalign) | No | ItemAlign.Stretch | Alignment mode of the child components in the **\<Flex>** component along the cross axis. |
| alignItems | [ItemAlign](ts-appendix-enums.md#itemalign) | No | ItemAlign.Start | Alignment mode of the child components in the **\<Flex>** component along the cross axis. |
| alignContent | [FlexAlign](ts-appendix-enums.md#flexalign) | No | FlexAlign.Start | Alignment mode of the child components in a multi-line **<Flex>** component along the cross axis. This parameter is valid only when **wrap** is set to **Wrap** or **WrapReverse**.|
......@@ -240,9 +240,7 @@ struct FlexExample4 {
}
```
![en-us_image_0000001257138371](figures/en-us_image_0000001257138371.jpg)
![en-us_image_0000001212378426](figures/en-us_image_0000001212378426.gif)
![en-us_image_0000001174422904](figures/en-us_image_0000001174422904.jpg)
```ts
// xxx.ets
......
......@@ -6,7 +6,7 @@ The **\<Scroll>** component scrolls the content when the layout size of a compon
> - This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
> - When nesting a **\<List>** within this component, specify the width and height for the **\<List>** under scenarios where consistently high performance is required. If the width and height are not specified, this component will load all content of the **\<List>**.
> - This component can scroll only when the size on the main axis is less than the content size.
> - The prerequisite for the component to rebound is that the component is scrolled.
> - This component can produce a bounce effect only when there is more than one screen of content.
## Child Components
......@@ -24,11 +24,11 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| Name | Type | Description |
| -------------- | ---------------------------------------- | --------- |
| scrollable | ScrollDirection | Scroll direction.<br>Default value: **ScrollDirection.Vertical**|
| scrollable | [ScrollDirection](#scrolldirection) | Scroll direction.<br>Default value: **ScrollDirection.Vertical**|
| scrollBar | [BarState](ts-appendix-enums.md#barstate) | Scrollbar status.<br>Default value: **BarState.Off**|
| scrollBarColor | string \| number \| Color | Color of the scrollbar.|
| scrollBarColor | string \| number \| [Color](ts-appendix-enums.md#color) | Color of the scrollbar.|
| scrollBarWidth | string \| number | Width of the scrollbar.|
| edgeEffect | [EdgeEffect](ts-appendix-enums.md#edgeeffect) | Scroll effect. For details, see **EdgeEffect**.<br>Default value: **EdgeEffect.Spring**|
| edgeEffect | [EdgeEffect](ts-appendix-enums.md#edgeeffect) | Scroll effect. For details, see **EdgeEffect**.<br>Default value: **EdgeEffect.None**|
## ScrollDirection
| Name | Description |
......@@ -36,7 +36,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| Horizontal | Only horizontal scrolling is supported. |
| Vertical | Only vertical scrolling is supported. |
| None | Scrolling is disabled. |
| Free<sup>(deprecated) </sup> | Vertical or horizontal scrolling is supported.<br> This API is deprecated since API version 9.|
| Free<sup>(deprecated) </sup> | Vertical or horizontal scrolling is supported.<br>This API is deprecated since API version 9. |
## Events
......@@ -104,7 +104,7 @@ Scrolls to the next or previous page.
| Name | Type | Mandatory | Description |
| --------- | ------- | ---- | ------------------------------ |
| next | boolean | Yes | Whether to turn to the next page. The value **true** means to scroll to the next page, and **false** means to scroll to the previous page.|
| direction<sup>(deprecated) </sup> | [Axis](ts-appendix-enums.md#axis) | No | Scrolling direction: horizontal or vertical.<br> This API is deprecated since API version 9. |
| direction<sup>(deprecated) </sup> | [Axis](ts-appendix-enums.md#axis) | No | Scrolling direction: horizontal or vertical.<br>This API is deprecated since API version 9. |
### currentOffset
......@@ -161,14 +161,15 @@ Scrolls by the specified amount.
## Example
### Example 1
```ts
// xxx.ets
@Entry
@Component
struct ScrollExample {
scroller: Scroller = new Scroller()
private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
scroller: Scroller = new Scroller();
private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
build() {
Stack({ alignContent: Alignment.TopStart }) {
......@@ -186,38 +187,39 @@ struct ScrollExample {
}, item => item)
}.width('100%')
}
.scrollable(ScrollDirection.Vertical)
.scrollBar(BarState.On)
.scrollBarColor(Color.Gray)
.scrollBarWidth(30)
.scrollable(ScrollDirection.Vertical) // The scrollbar scrolls in the vertical direction.
.scrollBar(BarState.On) // The scrollbar is always displayed.
.scrollBarColor(Color.Gray) // Color of the scrollbar.
.scrollBarWidth(30) // Width of the scrollbar.
.edgeEffect(EdgeEffect.None)
.onScroll((xOffset: number, yOffset: number) => {
console.info(xOffset + ' ' + yOffset)
console.info(xOffset + ' ' + yOffset);
})
.onScrollEdge((side: Edge) => {
console.info('To the edge')
console.info('To the edge');
})
.onScrollEnd(() => {
console.info('Scroll Stop')
console.info('Scroll Stop');
})
Button('scroll 150')
.onClick(() => { // Click to scroll down to 150.0 vp.
this.scroller.scrollBy(0,150)
this.scroller.scrollBy(0,150);
})
.margin({ top: 10, left: 20 })
Button('scroll 100')
.onClick(() => { // Click to scroll down by 100.0 vp.
this.scroller.scrollTo({ xOffset: 0, yOffset: this.scroller.currentOffset().yOffset + 100 })
this.scroller.scrollTo({ xOffset: 0, yOffset: this.scroller.currentOffset().yOffset + 100 });
})
.margin({ top: 60, left: 20 })
Button('back top')
.onClick(() => { // Click to go back to the top.
this.scroller.scrollEdge(Edge.Top)
this.scroller.scrollEdge(Edge.Top);
})
.margin({ top: 110, left: 20 })
Button('next page')
.onClick(() => { // Click to go to the next page.
this.scroller.scrollPage({ next: true })
this.scroller.scrollPage({ next: true });
})
.margin({ top: 170, left: 20 })
}.width('100%').height('100%').backgroundColor(0xDCDCDC)
......@@ -227,14 +229,14 @@ struct ScrollExample {
![en-us_image_0000001256978363](figures/en-us_image_0000001256978363.gif)
### Example 2
```ts
@Entry
@Component
struct NestedScroll {
@State listPosition: number = 0 // 0 indicates scrolling to the top of the list, 1 indicates scrolling to the center of the list, and 2 indicates scrolling to the bottom of the list.
private arr: number[] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
private scroller: Scroller = new Scroller()
@State listPosition: number = 0; // 0 indicates scrolling to the top of the list, 1 indicates scrolling to the middle of the list, and 2 indicates scrolling to the bottom of the list.
private arr: number[] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
private scroller: Scroller = new Scroller();
build() {
Flex() {
......@@ -255,18 +257,18 @@ struct NestedScroll {
}
.width("100%").height("50%").edgeEffect(EdgeEffect.None)
.onReachStart(() => {
this.listPosition = 0
this.listPosition = 0;
})
.onReachEnd(() => {
this.listPosition = 2
this.listPosition = 2;
})
.onScrollBegin((dx: number, dy: number) => {
if ((this.listPosition == 0 && dy >= 0) || (this.listPosition == 2 && dy <= 0)) {
this.scroller.scrollBy(0, -dy)
return { dxRemain: dx, dyRemain: 0 }
this.scroller.scrollBy(0, -dy);
return { dxRemain: dx, dyRemain: 0 };
}
this.listPosition = 1;
return { dxRemain: dx, dyRemain: dy }
return { dxRemain: dx, dyRemain: dy };
})
Text("Scroll Area")
......
# Time Picker Dialog Box
A time picker dialog box is a dialog box that allows users to select a time from the given range, which is from 00:00 to 23:59 by default.
A time picker dialog box is a dialog box that allows users to select a time from the 24-hour range.
> **NOTE**
>
> The APIs of this module are supported since API version 9. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
None
> The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
## TimePickerDialog.show
......@@ -18,71 +13,63 @@ show(options?: TimePickerDialogOptions)
Shows a time picker dialog box.
- TimePickerDialogOptions
| Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- |
| selected | Date | No| Current system time| Time of the selected item.|
| useMilitaryTime | boolean | No| false | Whether to display time in 24-hour format.|
| onAccept | (value: [TimePickerResult](ts-basic-components-timepicker.md#TimePickerResult)) => void | No| - | Callback invoked when the OK button in the dialog box is clicked.|
| onCancel | () => void | No| - | Callback invoked when the Cancel button in the dialog box is clicked.|
| onChange | (value: [TimePickerResult](ts-basic-components-timepicker.md#TimePickerResult)) => void | No| - | Callback invoked when the selected item in the picker changes.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| selected | Date | No| Selected time.<br>Default value: current system time|
| useMilitaryTime | boolean | No| Whether to display time in 24-hour format. The 12-hour format is used by default.<br>Default value: **false**|
| onAccept | (value: [TimePickerResult](ts-basic-components-timepicker.md#TimePickerResult)) => void | No| Callback invoked when the OK button in the dialog box is clicked.|
| onCancel | () => void | No| Callback invoked when the Cancel button in the dialog box is clicked.|
| onChange | (value: [TimePickerResult](ts-basic-components-timepicker.md#TimePickerResult)) => void | No| Callback invoked when the selected time changes.|
## Example
### Time Picker Sample Code (24-Hour Clock)
```ts
// xxx.ets
@Entry
@Component
struct TimePickerDialogExample01 {
@State isUseMilitaryTime: boolean = true
struct TimePickerDialogExample {
private selectTime: Date = new Date('2020-12-25T08:30:00')
build() {
Flex({direction: FlexDirection.Column, alignItems: ItemAlign.Center,
justifyContent: FlexAlign.Center }) {
Button("TimePickerDialog").onClick(() => {
TimePickerDialog.show({
useMilitaryTime: this.isUseMilitaryTime,
onAccept: (value: TimePickerResult) => {
console.info("TimePickerDialog:onAccept()" + JSON.stringify(value))
},
onCancel: () => {
console.info("TimePickerDialog:onCancel()")
},
onChange: (value: TimePickerResult) => {
console.info("TimePickerDialog:onChange()" + JSON.stringify(value))
}
Column() {
Button ("TimePickerDialog 12-hour format")
.margin(20)
.onClick(() => {
TimePickerDialog.show({
selected: this.selectTime,
onAccept: (value: TimePickerResult) => {
//Set selectTime to the time when the OK button is clicked. In this way, when the dialog box is displayed again, the selected time is the time when the operation was confirmed last time.
this.selectTime.setHours(value.hour, value.minute)
console.info("TimePickerDialog:onAccept()" + JSON.stringify(value));
},
onCancel: () => {
console.info("TimePickerDialog:onCancel()");
},
onChange: (value: TimePickerResult) => {
console.info("TimePickerDialog:onChange()" + JSON.stringify(value));
}
})
})
})
}
}
}
```
### Time Picker Sample Code (12-Hour Clock)
```ts
// xxx.ets
@Entry
@Component
struct TimePickerDialogExample02 {
@State isUseMilitaryTime: boolean = false
build() {
Flex({direction: FlexDirection.Column, alignItems: ItemAlign.Center,
justifyContent: FlexAlign.Center }) {
Button("TimePickerDialog").onClick(() => {
TimePickerDialog.show({
useMilitaryTime: this.isUseMilitaryTime,
onAccept: (value: TimePickerResult) => {
console.info("TimePickerDialog:onAccept()" + JSON.stringify(value))
},
onCancel: () => {
console.info("TimePickerDialog:onCancel()")
},
onChange: (value: TimePickerResult) => {
console.info("TimePickerDialog:onChange()" + JSON.stringify(value))
}
Button ("TimePickerDialog 24-hour format")
.margin(20)
.onClick(() => {
TimePickerDialog.show({
selected: this.selectTime,
useMilitaryTime: true,
onAccept: (value: TimePickerResult) => {
this.selectTime.setHours(value.hour, value.minute)
console.info("TimePickerDialog:onAccept()" + JSON.stringify(value));
},
onCancel: () => {
console.info("TimePickerDialog:onCancel()");
},
onChange: (value: TimePickerResult) => {
console.info("TimePickerDialog:onChange()" + JSON.stringify(value));
}
})
})
})
}
}.width('100%')
}
}
```
......@@ -77,7 +77,7 @@ Sends a touch event.
| Name | Type | Mandatory | Description |
| ----- | ----------- | ---- | ------------------------------------------------------------ |
| event | TouchObject | Yes | Location where a touch event is triggered. For details, see [TouchEvent](ts-universal-events-touch.md#touchevent).|
| event | [TouchObject](ts-universal-events-touch.md#touchobject) | Yes | Location where a touch event is triggered. For details, see [TouchEvent](ts-universal-events-touch.md#touchevent).|
**Return value**
......@@ -95,7 +95,7 @@ Sends a key event.
| Name | Type | Mandatory | Description |
| ----- | -------- | ---- | ------------------------------------------------------------ |
| event | KeyEvent | Yes | Key event. For details, see [KeyEvent](ts-universal-events-key.md#keyevent).|
| event | [KeyEvent](ts-universal-events-key.md#keyevent) | Yes | Key event. For details, see [KeyEvent](ts-universal-events-key.md#keyevent).|
**Return value**
......@@ -113,7 +113,7 @@ Sends a mouse event.
| Name | Type | Mandatory | Description |
| ----- | ---------- | ---- | --------------------------------------- |
| event | MouseEvent | Yes | Mouse event. For details, see [MouseEvent](ts-universal-mouse-key.md#mouseevent).|
| event | [MouseEvent](ts-universal-mouse-key.md#mouseevent) | Yes | Mouse event. For details, see [MouseEvent](ts-universal-mouse-key.md#mouseevent).|
**Return value**
......@@ -132,6 +132,7 @@ class Utils {
static rect_bottom;
static rect_value;
// Obtain the coordinates of the rectangular area occupied by the component.
static getComponentRect(key) {
let strJson = getInspectorByKey(key);
let obj = JSON.parse(strJson);
......@@ -171,7 +172,7 @@ struct IdExample {
console.info(getInspectorTree())
this.text = "Button 'click to start' is clicked"
setTimeout(() => {
sendEventByKey("longClick", 11, "")
sendEventByKey("longClick", 11, "") // Send a long-click event to the component whose ID is "longClick".
}, 2000)
}).id('click')
......@@ -183,18 +184,18 @@ struct IdExample {
console.info('long clicked')
this.text = "Button 'longClick' is longclicked"
setTimeout(() => {
let rect = Utils.getComponentRect('onTouch')
let rect = Utils.getComponentRect('onTouch') // Obtain the coordinates of the rectangular area occupied by the component whose ID is "onTouch".
let touchPoint: TouchObject = {
id: 1,
x: rect.left + (rect.right - rect.left) / 2,
y: rect.top + (rect.bottom - rect.top) / 2,
x: rect.left + (rect.right - rect.left) / 2, // X coordinate of the component center.
y: rect.top + (rect.bottom - rect.top) / 2, // Y coordinate of the component center.
type: TouchType.Down,
screenX: rect.left + (rect.right - rect.left) / 2,
screenY: rect.left + (rect.right - rect.left) / 2,
screenX: rect.left + (rect.right - rect.left) / 2, // X coordinate of the component center.
screenY: rect.left + (rect.right - rect.left) / 2, // Y coordinate of the component center.
}
sendTouchEvent(touchPoint)
sendTouchEvent(touchPoint) // Send a touch event.
touchPoint.type = TouchType.Up
sendTouchEvent(touchPoint)
sendTouchEvent(touchPoint) // Send a touch event.
}, 2000)
})).id('longClick')
......@@ -205,14 +206,14 @@ struct IdExample {
console.info('onTouch is clicked')
this.text = "Button 'onTouch' is clicked"
setTimeout(() => {
let rect = Utils.getComponentRect('onMouse')
let rect = Utils.getComponentRect('onMouse') // Obtain the coordinates of the rectangular area occupied by the component whose ID is "onMouse".
let mouseEvent: MouseEvent = {
button: MouseButton.Left,
action: MouseAction.Press,
x: rect.left + (rect.right - rect.left) / 2,
y: rect.top + (rect.bottom - rect.top) / 2,
screenX: rect.left + (rect.right - rect.left) / 2,
screenY: rect.top + (rect.bottom - rect.top) / 2,
x: rect.left + (rect.right - rect.left) / 2, // X coordinate of the component center.
y: rect.top + (rect.bottom - rect.top) / 2, // Y coordinate of the component center.
screenX: rect.left + (rect.right - rect.left) / 2, // X coordinate of the component center.
screenY: rect.top + (rect.bottom - rect.top) / 2, // Y coordinate of the component center.
timestamp: 1,
target: {
area: {
......@@ -230,7 +231,7 @@ struct IdExample {
},
source: SourceType.Mouse
}
sendMouseEvent(mouseEvent)
sendMouseEvent(mouseEvent) // Send a mouse event.
}, 2000)
}).id('onTouch')
......@@ -250,7 +251,7 @@ struct IdExample {
metaKey: 0,
timestamp: 0
}
sendKeyEvent(keyEvent)
sendKeyEvent(keyEvent) // Send a key event.
}, 2000)
}).id('onMouse')
......
......@@ -23,7 +23,6 @@
@Entry
@Component
struct FlexExample {
build() {
Column({ space: 5 }) {
Text('flexBasis').fontSize(9).fontColor(0xCCCCCC).width('90%')
......@@ -31,11 +30,18 @@ struct FlexExample {
// The value of flexBasis() can be 'auto' or a number, which is equivalent to .width()/.height().
Flex() {
Text('flexBasis(100)')
.flexBasis('100').height(100).lineHeight(70)
.backgroundColor(0xF5DEB3).textAlign(TextAlign.Center)
.flexBasis('100')
.height(100)
.lineHeight(70)
.backgroundColor(0xF5DEB3)
.textAlign(TextAlign.Center)
Text('flexBasis("auto")')
.flexBasis('auto').width('60%').height(100).lineHeight(70)
.backgroundColor(0xD2B48C).textAlign(TextAlign.Center)
.flexBasis('auto')
.width('60%')
.height(100)
.lineHeight(70)
.backgroundColor(0xD2B48C)
.textAlign(TextAlign.Center)
}.width('90%').height(120).padding(10).backgroundColor(0xAFEEEE)
Text('flexGrow').fontSize(9).fontColor(0xCCCCCC).width('90%')
......@@ -43,11 +49,17 @@ struct FlexExample {
// flexGrow() specifies the percentage of the remaining space allocated to the component.
Flex() {
Text('flexGrow(2)')
.flexGrow(2).height(100).lineHeight(70)
.backgroundColor(0xF5DEB3).textAlign(TextAlign.Center)
.flexGrow(2)
.height(100)
.lineHeight(70)
.backgroundColor(0xF5DEB3)
.textAlign(TextAlign.Center)
Text('flexGrow(1)')
.flexGrow(1).height(100).lineHeight(70)
.backgroundColor(0xD2B48C).textAlign(TextAlign.Center)
.flexGrow(1)
.height(100)
.lineHeight(70)
.backgroundColor(0xD2B48C)
.textAlign(TextAlign.Center)
}.width('90%').height(120).padding(10).backgroundColor(0xAFEEEE)
Text('flexShrink').fontSize(9).fontColor(0xCCCCCC).width('90%')
......@@ -55,13 +67,25 @@ struct FlexExample {
// The ratio of text1 is 0, and the default values of other parameters are 1. If the components cannot be completely displayed, the last two components are shrunk proportionally. The first component is not shrunk.
Flex({ direction: FlexDirection.Row }) {
Text('flexShrink(0)')
.flexShrink(0).width('50%').height(100).lineHeight(70)
.backgroundColor(0xF5DEB3).textAlign(TextAlign.Center)
.flexShrink(0)
.width('50%')
.height(100)
.lineHeight(70)
.backgroundColor(0xF5DEB3)
.textAlign(TextAlign.Center)
Text('no flexShrink')
.width('40%').height(100).lineHeight(70).backgroundColor(0xD2B48C).textAlign(TextAlign.Center)
.width('40%')
.height(100)
.lineHeight(70)
.backgroundColor(0xD2B48C)
.textAlign(TextAlign.Center)
Text('flexShrink(2)')
.flexShrink(2).width('40%').height(100) .lineHeight(70)
.backgroundColor(0xF5DEB3).textAlign(TextAlign.Center)
.flexShrink(2)
.width('40%')
.height(100)
.lineHeight(70)
.backgroundColor(0xF5DEB3)
.textAlign(TextAlign.Center)
}.width('90%').height(120).padding(10).backgroundColor(0xAFEEEE)
Text('alignSelf').fontSize(9).fontColor(0xCCCCCC).width('90%')
......@@ -70,8 +94,12 @@ struct FlexExample {
Text('no alignSelf,height:80').width('33%').height(80)
.backgroundColor(0xF5DEB3).textAlign(TextAlign.Center)
Text('alignSelf stretch')
.alignSelf(ItemAlign.Stretch).width('33%').height(80).lineHeight(70)
.backgroundColor(0xD2B48C).textAlign(TextAlign.Center)
.alignSelf(ItemAlign.Stretch)
.width('33%')
.height(80)
.lineHeight(70)
.backgroundColor(0xD2B48C)
.textAlign(TextAlign.Center)
Text('no alignSelf,height:100').width('34%').height(100)
.backgroundColor(0xF5DEB3).textAlign(TextAlign.Center)
}.width('90%').height(120).padding(10).backgroundColor(0xAFEEEE)
......
......@@ -12,7 +12,7 @@ You can set the opacity of a component.
| Name | Type | Description |
| ------- | ---------------------------------------- | ---------------------------------------- |
| opacity | number \| [Resource](ts-types.md#resource) | Opacity of a component. The value ranges from **0** to **1**. The value **1** means opaque, and **0** means completely transparent.<br>Default value: **1**|
| opacity | number \| [Resource](ts-types.md#resource) | Opacity of the component. The value ranges from 0 to 1. The value **1** means opaque, and **0** means completely transparent. When being completely transparent, the component is hidden, but still takes up space in the layout.<br>**NOTE**<br>A child component can inherit this attribute of its parent component. Default value: **1**|
## Example
......@@ -30,6 +30,10 @@ struct OpacityExample {
Text().width('90%').height(50).opacity(0.7).backgroundColor(0xAFEEEE)
Text('opacity(0.4)').fontSize(9).width('90%').fontColor(0xCCCCCC)
Text().width('90%').height(50).opacity(0.4).backgroundColor(0xAFEEEE)
Text('opacity(0.1)').fontSize(9).width('90%').fontColor(0xCCCCCC)
Text().width('90%').height(50).opacity(0.1).backgroundColor(0xAFEEEE)
Text('opacity(0)').fontSize(9).width('90%').fontColor(0xCCCCCC)
Text().width('90%').height(50).opacity(0).backgroundColor(0xAFEEEE)
}
.width('100%')
.padding({ top: 5 })
......@@ -37,4 +41,4 @@ struct OpacityExample {
}
```
![en-us_image_0000001256858385](figures/en-us_image_0000001256858385.gif)
![opacity.png](figures/opacity.png)
# Visible Area Change Event
The visible area change event of a component refers to the change in the visual portion of a component on the screen. It can be used to determine whether the component is completely or partially displayed on the screen. It is usually applicable to scenarios such as advertisement exposure tracing.
The visible area change event of a component refers to the change in the visual portion of the component on the screen. It can be used to determine whether the component is completely or partially displayed on the screen. It is usually applicable to scenarios such as advertisement exposure tracing.
> **NOTE**
>
......@@ -23,8 +23,8 @@ The visible area change event of a component refers to the change in the visual
struct ScrollExample {
scroller: Scroller = new Scroller()
private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
@State testTextStr: string = "test"
@State testRowStr: string = "test"
@State testTextStr: string = 'test'
@State testRowStr: string = 'test'
build() {
Column() {
......@@ -46,22 +46,22 @@ struct ScrollExample {
.height(200)
.margin({ top: 50, bottom: 20 })
.backgroundColor(Color.Green)
// Set ratios to [0.0, 1.0] to invoke the callback when the component is fully visible or invisible on screen.
// Set ratios to [0.0, 1.0] to invoke the callback when the component is fully visible or invisible on screen.
.onVisibleAreaChange([0.0, 1.0], (isVisible: boolean, currentRatio: number) => {
console.info("Test Text isVisible: " + isVisible + ", currentRatio:" + currentRatio)
console.info('Test Text isVisible: ' + isVisible + ', currentRatio:' + currentRatio)
if (isVisible && currentRatio >= 1.0) {
console.info("Test Text is fully visible. currentRatio:" + currentRatio)
this.testTextStr = "Test Text is fully visible"
console.info('Test Text is fully visible. currentRatio:' + currentRatio)
this.testTextStr = 'Test Text is fully visible'
}
if (!isVisible && currentRatio <= 0.0) {
console.info("Test Text is completely invisible.")
this.testTextStr = "Test Text is completely invisible"
console.info('Test Text is completely invisible.')
this.testTextStr = 'Test Text is completely invisible'
}
})
Row() {
Text("Test Row Visible Change")
Text('Test Row Visible Change')
.fontSize(20)
.margin({ bottom: 20 })
......@@ -69,15 +69,15 @@ struct ScrollExample {
.height(200)
.backgroundColor(Color.Yellow)
.onVisibleAreaChange([0.0, 1.0], (isVisible: boolean, currentRatio: number) => {
console.info("Test Row isVisible:" + isVisible + ", currentRatio:" + currentRatio)
console.info('Test Row isVisible:' + isVisible + ', currentRatio:' + currentRatio)
if (isVisible && currentRatio >= 1.0) {
console.info("Test Row is fully visible.")
this.testRowStr = "Test Row is fully visible"
console.info('Test Row is fully visible.')
this.testRowStr = 'Test Row is fully visible'
}
if (!isVisible && currentRatio <= 0.0) {
console.info("Test Row is is completely invisible.")
this.testRowStr = "Test Row is is completely invisible"
console.info('Test Row is is completely invisible.')
this.testRowStr = 'Test Row is is completely invisible'
}
})
......
# Adding Title and Paragraph Text
The &lt;text&gt; component is most commonly used to display text in title and paragraph areas. You can set attributes and styles for a &lt;text&gt; component and add the text to be displayed between the &lt;text&gt; and &lt;/text&gt; tags. For details about the attributes and styles, see [text](../reference/arkui-js/js-components-basic-text.md). The following is an example of adding title and paragraph text on a page:
The **\<text>** component is most commonly used to display text in title and paragraph areas. You can set attributes and styles for a **\<text>** component and add the text to be displayed between the **\<text>** and **\</text>** tags. For details about the attributes and styles, see [text](../reference/arkui-js/js-components-basic-text.md). The following is an example of adding title and paragraph text on a page:
```html
......@@ -26,8 +25,10 @@ The &lt;text&gt; component is most commonly used to display text in title and pa
font-size: 50px;
margin-top: 40px;
margin-bottom: 20px;
font-weight: 700;
}
.paragraph-text {
width: 95%;
color: #000000;
font-size: 35px;
line-height: 60px;
......@@ -39,9 +40,11 @@ The &lt;text&gt; component is most commonly used to display text in title and pa
// xxx.js
export default {
data: {
headTitle: 'Capture the Beauty in This Moment',
headTitle: 'Capture the Beauty in Moment',
paragraphFirst: 'Capture the beauty of light during the transition and fusion of ice and water. At the instant of movement and stillness, softness and rigidity, force and beauty, condensing moving moments.',
paragraphSecond: 'Reflecting the purity of nature, the innovative design upgrades your visual entertainment and ergonomic comfort. Effortlessly capture what you see and let it speak for what you feel.',
},
}
```
![en-us_image_0000001118642600](figures/en-us_image_0000001118642600.PNG)
# &lt;grid-container&gt; Development
# Grid Layout
The **&lt;grid-container&gt;** component is the root container of the grid layout. Within the root container, you can use **&lt;grid-row&gt;** and **&lt;grid-col&gt;** for the grid layout. For details, see [grid-container](../reference/arkui-js/js-components-grid-container.md).
The **\<grid-container>** component is the root container of the grid layout. Within the root container, you can use **\<grid-row>** and **\<grid-col>** for the grid layout. For details, see [Grid-container](../reference/arkui-js/js-components-grid-container.md).
## Creating a &lt;grid-container&gt; Component
## Creating a \<grid-container> Component
Create a **&lt;grid-container&gt;** component in the .hml file under **pages/index** and add a [**&lt;grid-row&gt;**](../reference/arkui-js/js-components-grid-row.md) child component.
Create a **\<grid-container>** component in the .hml file under **pages/index** and add a [\<Grid-row>](../reference/arkui-js/js-components-grid-row.md) child component.
```html
......@@ -37,12 +37,12 @@ Create a **&lt;grid-container&gt;** component in the .hml file under **pages/ind
> **NOTE**
>
> **&lt;grid-container&gt;** supports only **&lt;grid-row&gt;** as a child component.
> **\<grid-container>** supports only **\<grid-row>** as a child component.
## Methods
Click the **&lt;grid-container&gt;** component to call the **getColumns**, **getColumnWidth**, and **getGutterWidth** methods to return the number of columns in the grid container, and column width and gutter width of the grid container. Press and hold the component to call the **getSizeType** method to return the size-responsive type of the grid container (**xs**|**sm**|**md**|**lg**).
Touch the **\<grid-container>** component to call the **getColumns**, **getColumnWidth**, and **getGutterWidth** methods to return the number of columns in the grid container, and column width and gutter width of the grid container. Press and hold the component to call the **getSizeType** method to return the size-responsive type of the grid container (**xs**|**sm**|**md**|**lg**).
```html
......@@ -109,9 +109,9 @@ export default {
![en-us_image_0000001231843088](figures/en-us_image_0000001231843088.gif)
## Adding &lt;grid-col&gt;
## Adding \<grid-col>
After adding a **&lt;grid-row&gt;** child component to **&lt;grid-container&gt;**, add a **&lt;grid-col&gt;** child component to **&lt;grid-row&gt;** to form a layout.
After adding a **\<grid-row>** child component to **\<grid-container>**, add a **\<grid-col>** child component to **\<grid-row>** to form a layout.
```html
......@@ -168,7 +168,7 @@ text{
> **NOTE**
>
> **&lt;grid-row&gt;** supports only **&lt;grid-col&gt;** as a child component. You can add content only to **&lt;grid-col&gt;**.
> **\<grid-row>** supports only **\<grid-col>** as a child component. You can add content only to **\<grid-col>**.
## Example Scenario
......@@ -243,4 +243,4 @@ export default {
```
![en-us_image_0000001276003501](figures/en-us_image_0000001276003501.gif)
![en-us_image_0000001276003501](figures/en-us_image_0000001276003501.gif)
\ No newline at end of file
# OffscreenCanvasRenderingContext2D
**OffscreenCanvasRenderingContext2D** allows you to draw rectangles, text, images, and other objects on an offscreen canvas. For details, see [OffscreenCanvasRenderingContext2D](../reference/arkui-js/js-offscreencanvasrenderingcontext2d.md).
**OffscreenCanvasRenderingContext2D** allows you to draw rectangles, text, images, and other objects on an offscreen canvas, which is a new buffer created by the GPU outside of the current buffer. For details, see [OffscreenCanvasRenderingContext2D](../reference/arkui-js/js-offscreencanvasrenderingcontext2d.md).
Create an **OffscreenCanvas** and then a **getContext2d** object on the canvas. Then, create an image and set the **filter** attribute to change the image style.
In the following example, you first create an offscreen canvas, and then create a **getContext2d** object on the canvas, which is an image, and finally set the **filter** attribute for the image.
```html
<!-- xxx.hml -->
......@@ -86,7 +86,7 @@ export default {
## Determining the Position
Use **isPointInPath** and **isPointInStroke** to determine and show whether a coordinate is within the path area and whether a coordinate is on the edge of the path.
Use **isPointInPath** to determine whether a coordinate is within the path area and use **isPointInStroke** to determine whether a coordinate is on the edge of the path.
```html
......@@ -181,4 +181,4 @@ export default {
}
```
![en-us_image_0000001276003489](figures/en-us_image_0000001276003489.gif)
![en-us_image_0000001178084014](figures/en-us_image_0000001178084014.gif)
# Creating a Simple Page
In this section, we will develop an infographic food details page, by building custom components through the container components **\<Stack>** and **\<Flex>** as well as basic components **\<Image>** and **\<Text>**.
......@@ -9,7 +8,7 @@ In this section, we will develop an infographic food details page, by building c
1. Create a food name.
Delete the code of the **build** method in the project template, create a **\<Stack>** component, and place the **\<Text>** component in the braces of the **\<Stack>** component. When the **\<Stack>** component contains multiple child components, the latter child component overwrites the former one.
```
@Entry
@Component
......@@ -24,11 +23,11 @@ In this section, we will develop an infographic food details page, by building c
}
```
![en-us_image_0000001222967780](figures/en-us_image_0000001222967780.png)
![en-us_image_0000001222967780](figures/en-us_image_0000001222967780.png)
2. Display food pictures.
Create an **\<Image>** component and specify a URL for it. The **\<Image>** and **\<Text>** components are mandatory. To display the **\<Text>** component above the **\<Image>** component, you need to declare the **\<Image>** component first. Image resources are stored in the **rawfile** folder in **resources**. When referencing the resources in the **rawfile** folder, use the `"$rawfile('filename')"` format, where **filename** indicates the relative path of the file in the **rawfile** folder. Currently, `$rawfile` only allows the **\<Image>** component to reference image resources.
Create an **\<Image>** component and specify a URL for it. To display the **\<Text>** component above the **\<Image>** component, declare the **\<Image>** component first. Image resources are stored in the **rawfile** folder in **resources**. When referencing the resources in the **rawfile** folder, use the `$rawfile('filename')` format, where **filename** indicates the relative path of the file in the **rawfile** folder. Currently,` $rawfile` only allows the **\<Image>** component to reference image resources.
```
@Entry
......@@ -45,17 +44,17 @@ In this section, we will develop an infographic food details page, by building c
}
```
![en-us_image_0000001267887861](figures/en-us_image_0000001267887861.png)
3. Access images through resources.
In addition to specifying the image path, you can also use the media resource symbol `$r` to reference resources in the **resources** folder based on the resource qualifier rules. Right-click the **resources** folder, choose **New** &gt; **Resource Directory**, and set **Resource Type** to **Media (image resource)**.
Place **Tomato.png** in the **media** folder. You can then can reference the application resource in the `$r('app.type.name')` format, that is, `$r('app.media.Tomato')`.
![en-us_image_0000001267887861](figures/en-us_image_0000001267887861.png)
3. Access images through resources.
In addition to specifying the image path, you can also use the media resource symbol **$r** to reference resources based on the resource qualifier rules in the **resources** folder. Right-click the **resources** folder, choose **New** > **Resource Directory** from the shortcut menu, and set **Resource Type** to **Media** (image resource).
Place **Tomato.png** in the **media** folder. You can then reference the application resources in the `$r('app.type.name')` format, which is `$r('app.media.Tomato')` in this example.
```
@Entry
```
@Entry
@Component
struct MyComponent {
build() {
......@@ -69,15 +68,18 @@ In this section, we will develop an infographic food details page, by building c
}
}
}
```
```
4. Set the width and height of the image, and set the **objectFit** attribute of the image to **ImageFit.Contain**, which means to keep the aspect ratio of the image to ensure that the image is completely displayed within the boundary. If the image fills the entire screen, the possible causes are as follows:
4. Set the width and height of the image, and set the **objectFit** attribute of the image to **ImageFit.Contain**, which means to keep the aspect ratio of the image to ensure that the image is completely displayed within the boundary.
1. The width and height of the image are not set.
2. The default attribute of **objectFit** of the image is **ImageFit.Cover**, that is, the image is zoomed in or zoomed out to fill the entire display boundary with the aspect ratio locked.
```
@Entry
If the image fills the entire screen, the possible causes are as follows:
- The width and height of the image are not set.
- The default attribute of **objectFit** of the image is **ImageFit.Cover**, that is, the image is zoomed in or zoomed out to fill the entire display boundary with the aspect ratio locked.
```
@Entry
@Component
struct MyComponent {
build() {
......@@ -91,14 +93,17 @@ In this section, we will develop an infographic food details page, by building c
}
}
}
```
```
![en-us_image_0000001223127732](figures/en-us_image_0000001223127732.png)
![en-us_image_0000001223127732](figures/en-us_image_0000001223127732.png)
5. Set the food image and name layout. Set **alignContent** to **Alignment.BottomStart**. Similar to **FontWeight**, **Alignment** is a built-in enumeration type provided by the framework.
5. Set the food image and name layout.
Set **alignContent** of the **\<Stack>** component to **Alignment.BottomStart**. Similar to **FontWeight**, **Alignment** is a built-in enumeration type provided by the framework.
```
@Entry
@Entry
@Component
struct MyComponent {
build() {
......@@ -114,15 +119,19 @@ In this section, we will develop an infographic food details page, by building c
}
```
![en-us_image_0000001267647873](figures/en-us_image_0000001267647873.png)
6. You can change the background color of the food image by setting the background color of the **\<Stack>** component in either of the following ways:
1. Using the built-in **Color** enums provided by the framework. For example, **backgroundColor(Color.Red)** indicates that the background color is set to red.
2. Using the string-type parameter. The supported color formats are rgb, rgba, and HEX. For example, you can set the background color to blue by setting **backgroundColor(??\#0000FF??)** and set the background color to white by setting **backgroundColor(??rgb(255, 255, 255)??)**.
![en-us_image_0000001267647873](figures/en-us_image_0000001267647873.png)
6. You can change the background color of the food image by setting the background color of the **\<Stack>** component in any of the following ways:
1. Using a built-in enumeration value of **Color** provided by the framework. For example, **backgroundColor(Color.Red)** indicates that the background color is set to red.
2. Using a value of the string type. The supported color formats are rgb, rgba, and HEX. For example, you can set the background color to blue through **backgroundColor(??#0000FF??)** and set the background color to white through **backgroundColor(??rgb(255, 255, 255)??)**.
3. Using a value of the number type. Hexadecimal color values are supported. For example, **backgroundColor(0xFF0000)** indicates that the background color is red.
4. Using a value of the Resource type. For details about the Resource type, see [Resource Access](ts-resource-access.md).
```
@Entry
```
@Entry
@Component
struct MyComponent {
build() {
......@@ -136,18 +145,19 @@ In this section, we will develop an infographic food details page, by building c
}
.backgroundColor('#FFedf2f5')
}
}
```
}
```
![en-us_image_0000001222967772](figures/en-us_image_0000001222967772.png)
7. Adjust the left and bottom margin of the **\<Text>** component. **Margin** is a shorthand attribute. You can specify the margins of the four edges in a unified manner or separately. The configuration method is as follows:
1. To set the margins of the four edges in a unified manner, use the **Margin(Length)** format. For example, **margin(20)** indicates that the outer margins of the top, right, bottom, and left edges are all 20.
2. To set the margins of the four edges separately, use the **{top?: Length, right?: Length, bottom?: Length, left?:Length}** format. For example, **margin({ left: 26, bottom: 17.4 })** indicates that the left margin is 26 and the bottom margin is 17.4.
![en-us_image_0000001222967772](figures/en-us_image_0000001222967772.png)
7. Adjust the left and bottom margin of the **\<Text>** component. Margin is a shorthand attribute. You can specify the margins of the four edges in a unified manner or separately.
- To set the margins of the four edges in a unified manner, use the **Margin(Length)** format. For example, **margin(20)** indicates that the margins of the top, right, bottom, and left edges are all 20.
- To set the margins of the four edges separately, use the **{top?: Length, right?: Length, bottom?: Length, left?:Length}** format. For example, **margin({ left: 26, bottom: 17.4 })** indicates that the left margin is 26 and the bottom margin is 17.4.
```
@Entry
```
@Entry
@Component
struct MyComponent {
build() {
......@@ -163,17 +173,17 @@ In this section, we will develop an infographic food details page, by building c
.backgroundColor('#FFedf2f5')
}
}
```
```
![en-us_image_0000001222967776](figures/en-us_image_0000001222967776.png)
8. Adjust the structure between components and semanticize component names. Create the **FoodDetail** page entry component, create a column in **FoodDetail**, and set the alignment to **alignItems(HorizontalAlign.Center)**. Change the name of the **MyComponent** component to **FoodImageDisplay**, which is a child component of the **FoodDetail** component.
A column is a container component whose child components are vertically arranged. It is a linear layout in essence. Therefore, only the alignment in the cross axis direction can be set.
8. Adjust the structure between components and semanticize component names. Create the **FoodDetail** page entry component, create a **\<Column>** component in **FoodDetail**, and set the alignment to **alignItems(HorizontalAlign.Center)**. Change the name of the **MyComponent** component to **FoodImageDisplay**, which is a child component of the **FoodDetail** component.
The **\<Column>** component is a container whose child components are vertically arranged. It is in linear layout in essence. Therefore, only the alignment in the cross axis direction can be set.
```
@Component
```
@Component
struct FoodImageDisplay {
build() {
Stack({ alignContent: Alignment.BottomStart }) {
......@@ -199,17 +209,18 @@ In this section, we will develop an infographic food details page, by building c
.alignItems(HorizontalAlign.Center)
}
}
```
```
## Building the Flex Layout
You can use the Flex layout to build a food composition table. In this way you do not need to worry about the width and height calculation. The size of different cells can be flexibly set based on the proportion.
Use the **Flex** layout to build a food composition table. In this way, cell sizes are flexibly set based on the proportion, eliminating the need for width and height calculation.
1. Create a **ContentTable** component as a child component of the **FoodDetail** component.
```
@Component
```
@Component
struct FoodImageDisplay {
build() {
Stack({ alignContent: Alignment.BottomStart }) {
......@@ -241,19 +252,19 @@ You can use the Flex layout to build a food composition table. In this way you d
.alignItems(HorizontalAlign.Center)
}
}
```
```
2. Create a Flex component to display two food composition categories in the tomato: **Calories** and **Nutrition**.
2. Create a **\<Flex>** component to display two food composition categories in the tomato: **Calories** and **Nutrition**.
**Calories** contains information about calories. **Nutrition** contains information about protein, fat, carbohydrates, and vitamin C.
Create the **Calories** class. Create a Flex component and set its height to 280, and the top, right, and left margins to 30. The Flex component contains three **\<Text>** child components, which represent the category name (**Calories**), content name (**Calories**), and contain value (**17 kcal**), respectively. By default, child components in the Flex component are arranged horizontally.
Create the **Calories** class. Create a **\<Flex>** component and set its height to **280**, and the top, right, and left margins to **30**. The **Flex** component contains three **\<Text>** child components, which represent the category name (**Calories**), content name (**Calories**), and contain value (**17 kcal**), respectively. By default, child components in the **Flex** component are arranged horizontally.
In the following example, code of **FoodImageDisplay** is omitted, and only code of **ContentTable** is provided.
```
@Component
```
@Component
struct ContentTable {
build() {
Flex() {
......@@ -281,14 +292,15 @@ You can use the Flex layout to build a food composition table. In this way you d
.alignItems(HorizontalAlign.Center)
}
}
```
```
![en-us_image_0000001267767869](figures/en-us_image_0000001267767869.png)
3. Adjust the layout and set the proportion (**layoutWeight**) of each part. Set the proportion of the category name to **1**, and the total proportion of content name and content value to **2**. The content name and content value are in a same Flex, and the content name occupies all remaining space **flexGrow(1)**.
3. Adjust the layout and set the proportion (**layoutWeight**) of each part. Set **layoutWeight** of the category name to **1**, and **layoutWeight** of the content name and content value to **2**. The content name and content value are in a same **Flex**, and the content name occupies all remaining space **flexGrow(1)**.
```
@Component
```
@Component
struct FoodImageDisplay {
build() {
Stack({ alignContent: Alignment.BottomStart }) {
......@@ -337,7 +349,8 @@ You can use the Flex layout to build a food composition table. In this way you d
.alignItems(HorizontalAlign.Center)
}
}
```
```
![en-us_image_0000001267607901](figures/en-us_image_0000001267607901.png)
......@@ -345,9 +358,8 @@ You can use the Flex layout to build a food composition table. In this way you d
Set **FlexDirection.Column**, **FlexAlign.SpaceBetween**, and **ItemAlign.Start**.
```
@Component
```
@Component
struct ContentTable {
build() {
Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.SpaceBetween, alignItems: ItemAlign.Start }) {
......@@ -438,19 +450,19 @@ You can use the Flex layout to build a food composition table. In this way you d
.alignItems(HorizontalAlign.Center)
}
}
```
```
5. Use the custom constructor @Builder to simplify the code. It can be found that the food groups in each food composition table are actually of the same UI structure.
5. Use the custom constructor **\@Builder** to simplify the code. It can be found that the food groups in each food composition table are actually of the same UI structure.
![en-us_image_0000001223287704](figures/en-us_image_0000001223287704.png)
Currently, all food groups are declared, resulting in code duplication and redundancy. You can use **\@Builder** to build a custom method and abstract the same UI structure declaration. The **\@Builder** decorated method and the **build** method for the **@Component** decorated component are used to declare some UI rendering structures and comply with the same ArkTS syntax. You can define one or more methods decorated by **\@Builder**, but a component decorated by **@Component** can have only one **build** method.
Declare the **IngredientItem** method decorated by **\@Builder** in **ContentTable** to declare the UI descriptions for the category name, content name, and content value.
Currently, all food groups are declared, resulting in code duplication and redundancy. You can use @Builder to build a custom method and abstract the same UI structure declaration. The @Builder decorated method and the build method for the @Component decorated component are used to declare some UI rendering structures and comply with the same eTS syntax. You can define one or more methods decorated by @Builder, but a component decorated by @Component can have only one build method.
Declare the **IngredientItem** method decorated by @Builder in **ContentTable** to declare the UI descriptions for the category name, content name, and content value.
```
@Component
```
@Component
struct ContentTable {
@Builder IngredientItem(title:string, name: string, value: string) {
Flex() {
......@@ -469,13 +481,13 @@ You can use the Flex layout to build a food composition table. In this way you d
}
}
}
```
```
When the `IngredientItem` API is called in the **build** method of **ContentTable**, `this` needs to be used to invoke the method in the scope of the component to distinguish the global method call.
When the **IngredientItem** API is called in the **build** method of **ContentTable**, **this** needs to be used to invoke the method in the scope of the component to distinguish the global method call.
```
@Component
```
@Component
struct ContentTable {
......
build() {
......@@ -490,13 +502,13 @@ You can use the Flex layout to build a food composition table. In this way you d
.padding({ top: 30, right: 30, left: 30 })
}
}
```
```
The overall code of the **ContentTable** component is as follows:
The overall code of the **ContentTable** component is as follows:
```
@Component
```
@Component
struct ContentTable {
@Builder IngredientItem(title:string, name: string, value: string) {
Flex() {
......@@ -514,18 +526,19 @@ You can use the Flex layout to build a food composition table. In this way you d
.layoutWeight(2)
}
}
build() {
Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.SpaceBetween, alignItems: ItemAlign.Start }) {
this.IngredientItem('Calories', 'Calories', '17kcal')
this.IngredientItem('Nutrition', 'Protein', '0.9g')
this.IngredientItem('', 'Fat', '0.2g')
this.IngredientItem('', 'Carbohydrates', '3.9g')
this.IngredientItem('', 'VitaminC', '17.8mg')
}
.height(280)
.padding({ top: 30, right: 30, left: 30 })
}
build() {
Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.SpaceBetween, alignItems: ItemAlign.Start }) {
this.IngredientItem('Calories', 'Calories', '17kcal')
this.IngredientItem('Nutrition', 'Protein', '0.9g')
this.IngredientItem('', 'Fat', '0.2g')
this.IngredientItem('', 'Carbohydrates', '3.9g')
this.IngredientItem('', 'VitaminC', '17.8mg')
}
.height(280)
.padding({ top: 30, right: 30, left: 30 })
}
}
@Entry
......@@ -539,8 +552,9 @@ You can use the Flex layout to build a food composition table. In this way you d
.alignItems(HorizontalAlign.Center)
}
}
```
```
![en-us_image_0000001222807792](figures/en-us_image_0000001222807792.png)
![en-us_image_0000001222807792](figures/en-us_image_0000001222807792.png)
You've learned how to build a simple food details page. Read on to learn how to define the page layout and connection.
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册