arkts-shared-element-transition.md 22.3 KB
Newer Older
E
ester.zhou 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667
# Shared Element Transition


Shared element transition is a type of transition achieved by animating the size and position between styles of the same or similar elements during page switching. It is typically used with the modal transition for combined effects. When used with transition and attribute animations, it can make its way into a wider range of use cases.


## Implementation with transition and Attribute Animation

This example implements a shared element transition for the scenario where, as a component is expanded, sibling components in the same container disappear or appear. Specifically, attribute animations are applied to width and height changes of a component before and after the expansion; enter/exit animations are applied to the sibling components as they disappear or disappear.

1. Build the component to be expanded, and build two pages for it through state variables: one for the normal state and one for the expanded state.
  
   ```ts
   // Build two pages for the normal and expanded states of the same component, which are then used based on the declared state variables.
   @Component
   export struct MyExtendView {
     // Declare the isExpand variable to be synced with the parent component.
     @Link isExpand: boolean;
     @State cardList: Array<CardData> = xxxx;
   
     build() {
       List() {
         // Customize the expanded component as required.
         if (this.isExpand) {
           Text('expand')
             .transition(TransitionEffect.translate(y:300).animation({ curve: curves.springMotion(0.6, 0.8) }))
         }
   
         ForEach(this.cardList, (item: CradData) => {
           MyCard({ cardData: item })
         })
       }
       .width(this.isExpand ? 200 : 500) // Define the attributes of the expanded component.
       .animation({ curve: curves.springMotion()}) // Bind an animation to component attributes.
     }
   }
   ```

2. Expand the component to be expanded. Use state variables to control the disappearance or appearance of sibling components, and apply the enter/exit transition to the disappearance and appearance.
  
   ```ts
   @State isExpand: boolean = false
   
   ...
   List() {
     // Control the appearance or disappearance of sibling components through the isExpand variable, and configure the enter/exit transition.
     if (!this.isExpand) {
       Text ('I appear in normal state')
         .transition(TransitionEffect.translate(y:300).animation({ curve: curves.springMotion(0.6, 0.9) }))
     }
   
     MyExtendView({ isExpand: $isExpand })
       .onClick(() => {
         this.isExpand = !this.isExpand;
       })
   
     // Control the appearance or disappearance of sibling components through the isExpand variable, and configure the enter/exit transition.
     if (this.isExpand) {
       Text ('I appear in expanded state')
         .transition(TransitionEffect.translate(y:300).animation({ curve: curves.springMotion() }))
     }
   }
   
   ...
   ```


Below is the complete sample code and effect.



```ts
// utils.ets
import curves from '@ohos.curves';

// Build two pages for the normal and expanded states of the same component, which are then used based on the declared state variables.
@Component
export struct share_transition_expand {
  // Declare the isExpand variable to be synced with the parent component.
  // Expand the component.
  @Link isExpand: boolean;
  // Currently expanded component.
  @State curIndex: number = 0;
  private listArray: Array<number> = [1, 2, 3, 4, 5, 6];

  build() {
    Column() {
      List() {
        ForEach(this.listArray, (item, index) => {
          // Customize the expanded component as required.
          if (!this.isExpand || this.curIndex == index) {
            ListItem() {
              Column() {
                Row() {
                  Row()
                    .backgroundColor(Color.Pink)
                    .borderRadius(20)
                    .width(80)
                    .height(80)

                  Column() {
                    Text ('Click to expand Item' + item)
                      .fontSize(20)
                    Text ('Shared element transition')
                      .fontSize(12)
                      .fontColor(0x909399)
                  }
                  .alignItems(HorizontalAlign.Start)
                  .justifyContent(FlexAlign.SpaceAround)
                  .margin({ left: 10 })
                  .height(80)
                }
                .width('90%')
                .height(100)

                if (this.isExpand) {
                  Row() {
                    Text('Expanded state')
                      .fontSize(28)
                      .fontColor(0x909399)
                      .textAlign(TextAlign.Center)
                      .transition(TransitionEffect.OPACITY.animation({ curve: curves.springMotion(0.6, 0.9) }))
                  }
                  .width('90%')
                  .justifyContent(FlexAlign.Center)
                }
              }
              .onClick(() => {
                // Define the animation parameters for expanding and collapsing.
                animateTo({ curve: curves.springMotion(0.6, 0.9) }, () => {
                  this.curIndex = index;
                  this.isExpand = !this.isExpand;
                })
              })
              .width('90%')
              .height(this.isExpand && this.curIndex == index ? '85%' : 100) // Define the attributes of the expanded component as required.
              .alignItems(HorizontalAlign.Center)
              .borderRadius(10)
              .margin({ top: 15 })
              .backgroundColor(Color.White)
              .shadow({ radius: 20, color: 0x909399, offsetX: 20, offsetY: 10 })
              // Control the appearance or disappearance of sibling components through the isExpand variable, and configure the enter/exit transition.
              .transition(TransitionEffect.scale({ x: 0, y: 0 }).animation({ curve: curves.springMotion(0.3, 1.5) }))
            }
            .zIndex(this.curIndex == index ? 1 : 0)
          }
        })
      }
      .height('100%')
      .alignListItem(ListItemAlign.Center)
    }
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Start)
  }
}
```



```ts
// Index.ets
import { share_transition_expand } from './utils';

@Entry
@Component
struct ShareTransitionDemo {
  @State isExpand: boolean = false;

  build() {
    Column() {
      Text('Sibling nodes appear and disappear.')
        .fontWeight(FontWeight.Bold)
        .fontSize(30)
        .fontColor(Color.Black)
        .margin(10)

      share_transition_expand({ isExpand: $isExpand })

    }
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Start)
  }
}
```



![en-us_image_0000001600653160](figures/en-us_image_0000001600653160.gif)


## Implementation with transition and zIndex

This example implements a shared element transition for the scenario where, as a component is expanded, it is displayed on the top of the container while sibling components in the same container stay. This is achieved with the use of **zIndex**. Specifically:

- Build two pages for the normal and expanded states of the same component, which are then used based on the declared state variables.

- Change the display level of components through the **zIndex** attribute. Set this attribute to **1** for the component in the expanded state and retain the default value **0** for other sibling components. In this way, the component in the expanded state will be displayed over the sibling components.

- With the **translate** attribute, move the component to the top of the parent container when it is expanded.

- Use a placeholder container so that the location of the sibling components remains unchanged. The outer container is placed as a placeholder, and the internal container changes the size.

Below is the complete sample code and effect.


```ts
// utils.ets
import curves from '@ohos.curves';

// Build two pages for the normal and expanded states of the same component, which are then used based on the declared state variables.
@Component
export struct share_zIndex_expand {
  // Declare the isExpand variable to be synced with the parent component.
  @Link isExpand: boolean;
  @Link curIndex: number;
  @State listArray: Array<number> = [1, 2, 3, 4, 5, 6];
  private parentScroller: Scroller; // Upper-layer scroller controller.

  build() {
    Column() {
      List() {
        ForEach(this.listArray, (item, index) => {
          // Customize the expanded component as required.
          if (!this.isExpand || this.curIndex == index) {
            ListItem() {
              Column() {
                Row() {
                  Row()
                    .backgroundColor(Color.Pink)
                    .borderRadius(20)
                    .width(80)
                    .height(80)

                  Column() {
                    Text ('Click to expand Item' + item)
                      .fontSize(20)
                    Text ('Shared element transition')
                      .fontSize(12)
                      .fontColor(0x909399)
                  }
                  .alignItems(HorizontalAlign.Start)
                  .justifyContent(FlexAlign.SpaceAround)
                  .margin({ left: 10 })
                  .height(80)
                }
                .width('90%')
                .height(100)

                if (this.isExpand && this.curIndex == index) {
                  Row() {
                    Text('Expanded state')
                      .fontSize(28)
                      .fontColor(0x909399)
                      .textAlign(TextAlign.Center)
                      .transition(TransitionEffect.OPACITY.animation({ curve: curves.springMotion(0.6, 0.9) }))
                  }
                  .width('90%')
                  .justifyContent(FlexAlign.Center)
                }
              }
              .width('90%')
              .height(this.isExpand && this.curIndex == index ? 750 : 100)
              .alignItems(HorizontalAlign.Center)
              .borderRadius(10)
              .margin({ top: 15 })
              .backgroundColor(Color.White)
              .shadow({ radius: 20, color: 0x909399, offsetX: 20, offsetY: 10 })
            }
            .onClick(() => {
              // Define the animation parameters for expanding and collapsing.
              animateTo({ curve: curves.springMotion(0.6, 0.9) }, () => {
                this.curIndex = index;
                this.isExpand = !this.isExpand;
              })
            })
            .zIndex(this.curIndex == index? 1: 0) // When the current list item is selected, its zIndex attribute is set to 1, and it is displayed over other sibling components whose zIndex is 0.
            .translate({ // Move the list item to the top of the parent container through translate.
              y: this.isExpand && this.curIndex == index ? -60 - this.parentScroller.currentOffset()['yOffset'] : 0
            })
          }
        })
      }
      .clip(false)
      .height('100%') // Fixed size of the placeholder container.
      .alignListItem(ListItemAlign.Center)
    }
    .zIndex(1)
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Start)
  }
}
```


```ts
// Index.ets
import { share_zIndex_expand } from './utils'

@Entry
@Component
struct ShareZIndexDemo {
  @State isExpand: boolean = false;
  @State curIndex: number = 0;
  scroller: Scroller = new Scroller();

  build() {
    Scroll(this.scroller) {
      Column() {
        Text ('zIndex changes z-axis')
          .fontWeight(FontWeight.Bold)
          .fontSize(30)
          .fontColor(Color.Black)
          .zIndex(0)
          .margin(10)

        share_zIndex_expand({ isExpand: $isExpand, curIndex: $curIndex, parentScroller: this.scroller })
      }
      .width('100%')
      .height('100%')
      .justifyContent(FlexAlign.Start)
    }
  }
}
```

![en-us_image_0000001600332176](figures/en-us_image_0000001600332176.gif)


## Implementation with geometryTransition

This example implements a shared element transition with [geometryTransition](../reference/arkui-ts/ts-transition-animation-geometrytransition.md), which is used for implicit shared element transitions during component switching.

Below is the complete sample code and effect for using **geometryTransition** and the **if/else** syntax to implement a shared element transition:


```ts
@Entry
@Component
struct IfElseGeometryTransition {
  @State isShow: boolean = false;

  build() {
    Stack({ alignContent: Alignment.Center }) {
      if (this.isShow) {
        Image($r('app.media.test'))
          .autoResize(false)
          .clip(true)
          .width(300)
          .height(400)
          .offset({ y: 100 })
          .geometryTransition("picture")
          .transition(TransitionEffect.OPACITY)
      } else {
        // geometryTransition is bound to a container. Therefore, a relative layout must be configured for the child components of the container.
        // The multiple levels of containers here are used to demonstrate passing of relative layout constraints.
        Column() {
          Column() {
            Image($r('app.media.icon'))
              .width('100%').height('100%')
          }.width('100%').height('100%')
        }
        .width(80)
        .height(80)
        // geometryTransition synchronizes rounded corner settings, but only for the bound component, which is the container in this example.
        // In other words, rounded corner settings of the container are synchronized, and those of the child components are not.
        .borderRadius(20)
        .clip(true)
        .geometryTransition("picture")
        // transition ensures that the component is not destructed immediately when it exits. You can customize the transition effect.
        .transition(TransitionEffect.OPACITY)
      }
    }
    .onClick(() => {
      animateTo({ duration: 1000 }, () => {
        this.isShow = !this.isShow;
      })
    })
  }
}
```

![en-us_image_0000001599644878](figures/en-us_image_0000001599644878.gif)

Below is the sample code and effect for using **geometryTransition** and a modal transition API to implement a shared element transition:


```ts
import curves from '@ohos.curves';

@Entry
@Component
struct GeometryTransitionDemo {
  // Define the state variable used to control modal transition.
  @State isPresent: boolean = false;

  // Use @Builder to build the modal.
  @Builder
  MyBuilder() {
    Column() {
      Text(this.isPresent ? 'Page 2' : 'Page 1')
        .fontWeight(FontWeight.Bold)
        .fontSize(30)
        .fontColor(Color.Black)
        .margin(20)

      Row() {
        Text('Shared component 1')
          .fontWeight(FontWeight.Bold)
          .fontSize(20)
          .fontColor(Color.White)
      }
      .justifyContent(FlexAlign.Center)
      .borderRadius(10)
      .backgroundColor(0xf56c6c)
      .width('100%')
      .aspectRatio(1)
      .margin({ bottom: 20 })
      // New shared element, <Row, whose ID is share1.
      .geometryTransition('share1')

      Column() {
        Text ('Expanded page')
          .textAlign(TextAlign.Center)
          .fontSize(15)
          .fontColor(this.isPresent ? Color.White : Color.Transparent)
          .margin(20)

        Text('Click anywhere to return')
          .textAlign(TextAlign.Center)
          .fontSize(15)
          .fontColor(this.isPresent ? Color.White : Color.Transparent)
      }
      .width('100%')
      .transition(TransitionEffect.OPACITY.animation({ curve: curves.springMotion(0.6, 1.2) }))

    }
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Start)
    .transition(TransitionEffect.opacity(0.99))
    .backgroundColor(this.isPresent ? 0x909399 : Color.Transparent)
    .clip(true)
    .onClick(() => {
      animateTo({ duration: 1000 }, () => {
        this.isPresent = !this.isPresent;
      })
    })
  }

  build() {
    Column() {
      Text('Page 1')
        .fontWeight(FontWeight.Bold)
        .fontSize(30)
        .fontColor(Color.Black)
        .margin(20)

      Row() {
        Text('Shared component 1')
          .fontWeight(FontWeight.Bold)
          .fontSize(20)
          .fontColor(Color.White)
      }
      .justifyContent(FlexAlign.Center)
      .borderRadius(10)
      .backgroundColor(0xf56c6c)
      .width(150)
      .height(150)
      .margin(20)
      // Modal transition component
      .bindContentCover($$this.isPresent, this.MyBuilder, ModalTransition.NONE)
      // The <Row> component is assigned the ID share1 and configured to have the shared element effect.
      .geometryTransition('share1')
      .onClick(() => {
        animateTo({ curve: curves.springMotion(0.6, 1.2) }, () => {
          // Change the state variable in the closure to display the modal.
          this.isPresent = !this.isPresent;
        })
      })

      Text('Component 2')
        .fontWeight(FontWeight.Bold)
        .fontSize(20)
        .fontColor(Color.White)
        .textAlign(TextAlign.Center)
        .borderRadius(10)
        .backgroundColor(0x67C23A)
        .width(150)
        .height(150)
        .margin(20)
    }
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Start)
    .backgroundColor(Color.White)
  }
}
```

![en-us_image_0000001597320326](figures/en-us_image_0000001597320326.gif)



## Implementation with Attribute Animation


```ts
import curves from '@ohos.curves';

@Entry
@Component
struct AutoAchieveShareTransitionDemo {
  private items: string[] = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'];

  // Specify whether the component is expanded.
  @State expand: boolean = false;

  // Attributes related to the shared element.
  @State rect_top: number = 0; // Position of the shared element.
  @State rect_bottom: number = 0;
  @State rect_left: number = 0;
  @State rect_right: number = 0;

  // Attributes related to the newly created element.
  @State item: string = ''; // Record the expanded element.
  @State cardHeight: number = 300; // Widget height.
  @State cardOpacity: number = 1; // Widget opacity.
  @State layoutHeight: number = 300; // Height of the expanded page.
  @State layoutWidth: string = '90%'; // Width of the expanded page.
  @State layoutOffset: number = 0; // Offset of the expanded page.
  @State layoutOpacity: number = 0; // Opacity of the expanded page.

  // In the callback invoked when the transition is complete.
  @State count: number = 0;

  build() {
    Stack() {
      Scroll() {
        Column({ space: 20 }) {
          ForEach(this.items, (item, index) => {
            Row() {
              Column() {
                Text('Shared element ' + item)
                  .fontSize(30)
                  .fontColor(Color.Black)
                  .fontWeight(FontWeight.Bolder)
                Text ('Expand widget')
                  .fontSize(20)
                  .fontColor(0x909399)
              }
              .width('100%')
              .height('100%')
              .justifyContent(FlexAlign.Center)
            }
            .width('90%')
            .height(this.cardHeight)
            .padding(20)
            .backgroundColor(Color.Pink)
            .borderRadius(10)
            .shadow({ radius: 10, color: 0x909399, offsetX: 10, offsetY: 10 })
            .opacity(this.expand && this.item == item ? 0 : 1)
            // Set a unique ID and obtain the attribute information of the component corresponding to the ID.
            .id(item)
            .onClick(() => {
              // Obtain the position and size of the corresponding component.
              let strJson = getInspectorByKey(item);
              let obj = JSON.parse(strJson);
              let rectInfo = JSON.parse('[' + obj.$rect + ']');
              let rect_left = JSON.parse('[' + rectInfo[0] + ']')[0];
              let rect_top = JSON.parse('[' + rectInfo[0] + ']')[1];
              let rect_right = JSON.parse('[' + rectInfo[1] + ']')[0];
              let rect_bottom = JSON.parse('[' + rectInfo[1] + ']')[1];
              let rect_value = {
                "left": rect_left, "top": rect_top, "right": rect_right, "bottom": rect_bottom
              };

              // Set the location, content, and status of the shared element.
              this.rect_top = rect_top;
              this.item = item;
              this.expand = true;
              this.count += 1;

              animateTo({ curve: curves.springMotion() }, () => {
                this.layoutHeight = 2772 / 3.5;
                this.layoutWidth = '100%';
                this.layoutOffset = -((rect_top - 136) / 3.5);
              })
            })
          })
        }
        .width('100%')
        .margin({ top: 20 })
      }
      .height('100%')

      // Create an element that is the same as the component based on the obtained component information.
      if (this.expand) {
        Column() {
          // Share element.
          Row() {
            Column() {
              Text('Shared element ' + this.item)
                .fontSize(30)
                .fontColor(Color.Black)
                .fontWeight(FontWeight.Bolder)
              Text ('Expand widget')
                .fontSize(20)
                .fontColor(0x909399)
            }
            .width('100%')
            .height('100%')
            .justifyContent(FlexAlign.Center)
          }
          .width('100%')
          .height(this.cardHeight)
          .padding(20)
          .backgroundColor(Color.Pink)

          // New element.
          Text('Expanded page\n\nExpanded page\n\nExpanded page\n\nExpanded page\n\nExpanded page\n\nExpanded page\n\nExpanded page\n\nExpanded page')
            .fontSize(20)
            .fontColor(0xcccccc)
            .margin({ top: 20 })

        }
        .borderRadius(this.layoutWidth == '100%' ? 0 : 10)
        .shadow({ radius: 10, color: 0x909399, offsetX: 10, offsetY: 10 })
        .width(this.layoutWidth)
        .height(this.layoutHeight)
        .clip(true)
        .backgroundColor(Color.White)
        // Work out the absolute position of the new element.
        .position({
          x: this.layoutWidth == '90%' ? '5%' : 0,
          y: (this.rect_top - 136) / 3.5
        })
        .translate({
          y: this.layoutOffset
        })
        .onClick(() => {
          this.count -= 1;

          animateTo({
            curve: curves.springMotion(),
            onFinish: (() => {
              if (this.count == 0) {
                this.expand = false;
              }
            })
          }, () => {
            this.layoutHeight = this.cardHeight;
            this.layoutWidth = '90%';
            this.layoutOffset = 0;
          })
        })
      }
    }
  }
}
```



![en-us_image_0000001599374166](figures/en-us_image_0000001599374166.gif)