文档管理中心

共享元素转场 (一镜到底)

共享元素转场是一种界面切换时对相同或者相似的两个元素做的一种位置和大小匹配的过渡动画效果,也称一镜到底动效。

如下例所示,在点击图片后,该图片消失,同时在另一个位置出现新的图片,二者之间内容相同,可以对它们添加一镜到底动效。左图为不添加一镜到底动效的效果,右图为添加一镜到底动效的效果,一镜到底的效果能够让二者的出现消失产生联动,使得内容切换过程显得灵动自然而不生硬。

展开
一帧切换效果 一镜到底效果

一镜到底的动效有多种实现方式,在实际开发过程中,应根据具体场景选择合适的方法进行实现。

以下是不同实现方式的对比:

展开
一镜到底实现方式 特点 适用场景
不新建容器直接变化原容器 不发生路由跳转,需要在一个组件中实现展开及关闭两种状态的布局,展开后组件层级不变。 适用于转场开销小的简单场景,如点开页面无需加载大量数据及组件。
新建容器并跨容器迁移组件 通过使用NodeController,将组件从一个容器迁移到另一个容器,在开始迁移时,需要根据前后两个布局的位置大小等信息对组件添加位移及缩放,确保迁移开始时组件能够对齐初始布局,避免出现视觉上的跳变现象。之后再添加动画将位移及缩放等属性复位,实现组件从初始布局到目标布局的一镜到底过渡效果。 适用于新建对象开销大的场景,如视频直播组件点击转为全屏等。
使用geometryTransition共享元素转场 利用系统能力,转场前后两个组件调用geometryTransition接口绑定同一id,同时将转场逻辑置于animateTo动画闭包内,这样系统侧会自动为二者添加一镜到底的过渡效果。 系统将调整绑定的两个组件的宽高及位置至相同值,并切换二者的透明度,以实现一镜到底过渡效果。因此,为了实现流畅的动画效果,需要确保对绑定geometryTransition的节点添加宽高动画不会有跳变。此方式适用于创建新节点开销小的场景。

不新建容器并直接变化原容器

该方法不新建容器,通过在已有容器上增删组件触发transition,搭配组件属性动画实现一镜到底效果。

对于同一个容器展开,容器内兄弟组件消失或者出现的场景,可通过对同一个容器展开前后进行宽高位置变化并配置属性动画,对兄弟组件配置出现消失转场动画实现一镜到底效果。基本步骤为:

  1. 构建需要展开的页面,并通过状态变量构建好普通状态和展开状态的界面。

  2. 将需要展开的页面展开,通过状态变量控制兄弟组件消失或出现,并通过绑定出现消失转场实现兄弟组件转场效果。

以点击卡片后显示卡片内容详情场景为例:

收起
自动换行
深色代码主题
复制
  1. import { common } from '@kit.AbilityKit';
  2. class PostData {
  3. // 请将$r('app.media.flower')替换为实际资源文件
  4. avatar: Resource = $r('app.media.flower');
  5. name: string = '';
  6. message: ResourceStr = '';
  7. images: Resource[] = [];
  8. }
  9. @Entry
  10. @Component
  11. struct Index {
  12. @State isExpand: boolean = false;
  13. @State @Watch('onItemClicked') selectedIndex: number = -1;
  14. private context = this.getUIContext().getHostContext() as common.UIAbilityContext;
  15. // 数组中图片均使用Resource资源,需用户自定义
  16. private allPostData: PostData[] = [
  17. {
  18. // 请将$r('app.media.flower')替换为实际资源文件
  19. avatar: $r('app.media.flower'),
  20. name: 'Alice',
  21. // 请将$r('app.string.shareTransition_text1')替换为实际资源文件,在本示例中该资源文件的value值为"天气晴朗"
  22. message: $r('app.string.shareTransition_text1'),
  23. // 请将$r('app.media.spring')替换为实际资源文件
  24. // 请将$r('app.media.tall_tree')替换为实际资源文件
  25. images: [$r('app.media.spring'), $r('app.media.tall_tree')]
  26. },
  27. {
  28. // 请将$r('app.media.sunset_sky')替换为实际资源文件
  29. avatar: $r('app.media.sunset_sky'),
  30. name: 'Bob',
  31. // 请将$r('app.string.shareTransition_text2')替换为实际资源文件,在本示例中该资源文件的value值为"你好世界"
  32. message: $r('app.string.shareTransition_text2'),
  33. // 请将$r('app.media.island')替换为实际资源文件
  34. images: [$r('app.media.island')]
  35. },
  36. {
  37. // 请将$r('app.media.tall_tree')替换为实际资源文件
  38. avatar: $r('app.media.tall_tree'),
  39. name: 'Carl',
  40. // 请将$r('app.string.shareTransition_text3')替换为实际资源文件,在本示例中该资源文件的value值为"万物生长"
  41. message: $r('app.string.shareTransition_text3'),
  42. // 请将$r('app.media.flower')替换为实际资源文件
  43. // 请将$r('app.media.sunset_sky')替换为实际资源文件
  44. // 请将$r('app.media.spring')替换为实际资源文件
  45. images: [$r('app.media.flower'), $r('app.media.sunset_sky'), $r('app.media.spring')]
  46. }];
  47. private onItemClicked(): void {
  48. if (this.selectedIndex < 0) {
  49. return;
  50. }
  51. this.getUIContext()?.animateTo({
  52. duration: 350,
  53. curve: Curve.Friction
  54. }, () => {
  55. this.isExpand = !this.isExpand;
  56. });
  57. }
  58. build() {
  59. Column({ space: 20 }) {
  60. ForEach(this.allPostData, (postData: PostData, index: number) => {
  61. // 当点击了某个post后,会使其余的post消失下树
  62. if (!this.isExpand || this.selectedIndex === index) {
  63. Column() {
  64. Post({ data: postData, selectedIndex: this.selectedIndex, index: index })
  65. }
  66. .width('100%')
  67. // 对出现消失的post添加透明度转场和位移转场效果
  68. .transition(TransitionEffect.OPACITY
  69. .combine(TransitionEffect.translate({ y: index < this.selectedIndex ? -250 : 250 }))
  70. .animation({ duration: 350, curve: Curve.Friction }))
  71. }
  72. }, (postData: PostData, index: number) => index.toString())
  73. }
  74. .size({ width: '100%', height: '100%' })
  75. .backgroundColor('#40808080')
  76. }
  77. }
  78. @Component
  79. export default struct Post {
  80. @Link selectedIndex: number;
  81. @Prop data: PostData;
  82. @Prop index: number;
  83. @State itemHeight: number = 250;
  84. @State isExpand: boolean = false;
  85. @State expandImageSize: number = 100;
  86. @State avatarSize: number = 50;
  87. build() {
  88. Column({ space: 20 }) {
  89. Row({ space: 10 }) {
  90. Image(this.data.avatar)
  91. .size({ width: this.avatarSize, height: this.avatarSize })
  92. .borderRadius(this.avatarSize / 2)
  93. .clip(true)
  94. Text(this.data.name)
  95. }
  96. .justifyContent(FlexAlign.Start)
  97. Text(this.data.message)
  98. Row({ space: 15 }) {
  99. ForEach(this.data.images, (imageResource: Resource, index: number) => {
  100. Image(imageResource)
  101. .size({ width: this.expandImageSize, height: this.expandImageSize })
  102. }, (imageResource: Resource, index: number) => index.toString())
  103. }
  104. // 展开态下组件增加的内容
  105. if (this.isExpand) {
  106. Column() {
  107. // 请将$r('app.string.shareTransition_text4')替换为实际资源文件,在本示例中该资源文件的value值为"评论区"
  108. Text($r('app.string.shareTransition_text4'))
  109. // 对评论区文本添加出现消失转场效果
  110. .transition(TransitionEffect.OPACITY
  111. .animation({ duration: 350, curve: Curve.Friction }))
  112. .padding({ top: 10 })
  113. }
  114. .transition(TransitionEffect.asymmetric(
  115. TransitionEffect.opacity(0.99)
  116. .animation({ duration: 350, curve: Curve.Friction }),
  117. TransitionEffect.OPACITY.animation({ duration: 0 })
  118. ))
  119. .size({ width: '100%' })
  120. }
  121. }
  122. .backgroundColor(Color.White)
  123. .size({ width: '100%', height: this.itemHeight })
  124. .alignItems(HorizontalAlign.Start)
  125. .padding({ left: 10, top: 10 })
  126. .onClick(() => {
  127. this.selectedIndex = -1;
  128. this.selectedIndex = this.index;
  129. this.getUIContext()?.animateTo({
  130. duration: 350,
  131. curve: Curve.Friction
  132. }, () => {
  133. // 对展开的post做宽高动画,并对头像尺寸和图片尺寸加动画
  134. this.isExpand = !this.isExpand;
  135. this.itemHeight = this.isExpand ? 780 : 250;
  136. this.avatarSize = this.isExpand ? 75 : 50;
  137. this.expandImageSize = (this.isExpand && this.data.images.length > 0)
  138. ? (360 - (this.data.images.length + 1) * 15) / this.data.images.length : 100;
  139. })
  140. })
  141. }
  142. }

新建容器并跨容器迁移组件

通过NodeContainer自定义占位节点,利用NodeController实现组件的跨节点迁移,配合属性动画给组件的迁移过程赋予一镜到底效果。这种一镜到底的实现方式可以结合多种转场方式使用,如导航转场(Navigation)、半模态转场(bindSheet)等。

结合Stack使用

可以利用Stack内后定义组件位于最上方的特性,控制组件在跨节点迁移后的顺序位置最高。以展开收起卡片的场景为例,实现步骤为:

  • 展开卡片时,获取被点击卡片A的位置信息,将被点击卡片A迁移到与卡片A位置一致的展开页B处,展开页B的层级高于被点击卡片A的层级。

  • 对展开页B添加属性动画,使之展开并运动到展开后的位置,完成一镜到底的动画效果。

  • 收起卡片时,对展开页B添加属性动画,使之收起并运动到收起时的位置,即被点击卡片A的位置,实现一镜到底的动画效果。

  • 在动画结束回调函数中将展开页B中的组件迁移回被点击卡片A处。

收起
自动换行
深色代码主题
复制
  1. // Index.ets
  2. import { createPostNode, getPostNode, PostNode } from './PostNode';
  3. import { componentUtils, curves, UIContext } from '@kit.ArkUI';
  4. @Entry
  5. @Component
  6. struct Index {
  7. // 新建一镜到底动画类
  8. private uiContext: UIContext = this.getUIContext();
  9. @State animationProperties: AnimationProperties = new AnimationProperties(this.uiContext);
  10. private listArray: Array<number> = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
  11. build() {
  12. // 卡片折叠态,展开态的共同父组件
  13. Stack() {
  14. List({ space: 20 }) {
  15. ForEach(this.listArray, (item: number) => {
  16. ListItem() {
  17. // 卡片折叠态
  18. PostItem({ index: item, animationProperties: this.animationProperties })
  19. }
  20. })
  21. }
  22. .clip(false)
  23. .alignListItem(ListItemAlign.Center)
  24. if (this.animationProperties.isExpandPageShow) {
  25. // 卡片展开态
  26. ExpandPage({ animationProperties: this.animationProperties })
  27. }
  28. }
  29. .key('rootStack')
  30. .enabled(this.animationProperties.isEnabled)
  31. }
  32. }
  33. @Component
  34. struct PostItem {
  35. @Prop index: number
  36. @Link animationProperties: AnimationProperties;
  37. @State nodeController: PostNode | undefined = undefined;
  38. // 折叠时详细内容隐藏
  39. private showDetailContent: boolean = false;
  40. aboutToAppear(): void {
  41. this.nodeController = createPostNode(this.getUIContext(), this.index.toString(), this.showDetailContent);
  42. if (this.nodeController != undefined) {
  43. // 设置回调,当卡片从展开态回到折叠态时触发
  44. this.nodeController.setCallback(this.resetNode.bind(this));
  45. }
  46. }
  47. resetNode() {
  48. this.nodeController = getPostNode(this.index.toString());
  49. }
  50. build() {
  51. Stack() {
  52. NodeContainer(this.nodeController)
  53. }
  54. .width('100%')
  55. .height(100)
  56. .key(this.index.toString())
  57. .onClick(() => {
  58. if (this.nodeController != undefined) {
  59. // 卡片从折叠态节点下树
  60. this.nodeController.onRemove();
  61. }
  62. // 触发卡片从折叠到展开态的动画
  63. this.animationProperties.expandAnimation(this.index);
  64. })
  65. }
  66. }
  67. @Component
  68. struct ExpandPage {
  69. @Link animationProperties: AnimationProperties;
  70. @State nodeController: PostNode | undefined = undefined;
  71. // 展开时详细内容出现
  72. private showDetailContent: boolean = true;
  73. aboutToAppear(): void {
  74. // 获取对应序号的卡片组件
  75. this.nodeController = getPostNode(this.animationProperties.curIndex.toString());
  76. // 更新为详细内容出现
  77. this.nodeController?.update(this.animationProperties.curIndex.toString(), this.showDetailContent);
  78. }
  79. build() {
  80. Stack() {
  81. NodeContainer(this.nodeController)
  82. }
  83. .width('100%')
  84. .height(this.animationProperties.changedHeight ? '100%' : 100)
  85. .translate({ x: this.animationProperties.translateX, y: this.animationProperties.translateY })
  86. .position({ x: this.animationProperties.positionX, y: this.animationProperties.positionY })
  87. .onClick(() => {
  88. this.getUIContext()?.animateTo({
  89. curve: curves.springMotion(0.6, 0.9),
  90. onFinish: () => {
  91. if (this.nodeController != undefined) {
  92. // 执行回调,折叠态节点获取卡片组件
  93. this.nodeController.callCallback();
  94. // 当前展开态节点的卡片组件下树
  95. this.nodeController.onRemove();
  96. }
  97. // 卡片展开态节点下树
  98. this.animationProperties.isExpandPageShow = false;
  99. this.animationProperties.isEnabled = true;
  100. }
  101. }, () => {
  102. // 卡片从展开态回到折叠态
  103. this.animationProperties.isEnabled = false;
  104. this.animationProperties.translateX = 0;
  105. this.animationProperties.translateY = 0;
  106. this.animationProperties.changedHeight = false;
  107. // 更新为详细内容消失
  108. this.nodeController?.update(this.animationProperties.curIndex.toString(), false);
  109. })
  110. })
  111. }
  112. }
  113. class RectInfo {
  114. left: number = 0;
  115. top: number = 0;
  116. right: number = 0;
  117. bottom: number = 0;
  118. width: number = 0;
  119. height: number = 0;
  120. }
  121. // 封装的一镜到底动画类
  122. @Observed
  123. class AnimationProperties {
  124. public isExpandPageShow: boolean = false;
  125. // 控制组件是否响应点击事件
  126. public isEnabled: boolean = true;
  127. // 展开卡片的序号
  128. public curIndex: number = -1;
  129. public translateX: number = 0;
  130. public translateY: number = 0;
  131. public positionX: number = 0;
  132. public positionY: number = 0;
  133. public changedHeight: boolean = false;
  134. private calculatedTranslateX: number = 0;
  135. private calculatedTranslateY: number = 0;
  136. // 设置卡片展开后相对父组件的位置
  137. private expandTranslateX: number = 0;
  138. private expandTranslateY: number = 0;
  139. private uiContext: UIContext;
  140. constructor(uiContext: UIContext) {
  141. this.uiContext = uiContext
  142. }
  143. public expandAnimation(index: number): void {
  144. // 记录展开态卡片的序号
  145. if (index != undefined) {
  146. this.curIndex = index;
  147. }
  148. // 计算折叠态卡片相对父组件的位置
  149. this.calculateData(index.toString());
  150. // 展开态卡片上树
  151. this.isExpandPageShow = true;
  152. // 卡片展开的属性动画
  153. this.uiContext?.animateTo({
  154. curve: curves.springMotion(0.6, 0.9)
  155. }, () => {
  156. this.translateX = this.calculatedTranslateX;
  157. this.translateY = this.calculatedTranslateY;
  158. this.changedHeight = true;
  159. })
  160. }
  161. // 获取需要跨节点迁移的组件的位置,及迁移前后节点的公共父节点的位置,用以计算做动画组件的动画参数
  162. public calculateData(key: string): void {
  163. let clickedImageInfo = this.getRectInfoById(this.uiContext, key);
  164. let rootStackInfo = this.getRectInfoById(this.uiContext, 'rootStack');
  165. this.positionX = this.uiContext.px2vp(clickedImageInfo.left - rootStackInfo.left);
  166. this.positionY = this.uiContext.px2vp(clickedImageInfo.top - rootStackInfo.top);
  167. this.calculatedTranslateX = this.uiContext.px2vp(rootStackInfo.left - clickedImageInfo.left) +
  168. this.expandTranslateX;
  169. this.calculatedTranslateY = this.uiContext.px2vp(rootStackInfo.top - clickedImageInfo.top) + this.expandTranslateY;
  170. }
  171. // 根据组件的id获取组件的位置信息
  172. private getRectInfoById(context: UIContext, id: string): RectInfo {
  173. let componentInfo: componentUtils.ComponentInfo = context.getComponentUtils().getRectangleById(id);
  174. if (!componentInfo) {
  175. throw Error('object is empty');
  176. }
  177. let rstRect: RectInfo = new RectInfo();
  178. const widthScaleGap = componentInfo.size.width * (1 - componentInfo.scale.x) / 2;
  179. const heightScaleGap = componentInfo.size.height * (1 - componentInfo.scale.y) / 2;
  180. rstRect.left = componentInfo.translate.x + componentInfo.windowOffset.x + widthScaleGap;
  181. rstRect.top = componentInfo.translate.y + componentInfo.windowOffset.y + heightScaleGap;
  182. rstRect.right =
  183. componentInfo.translate.x + componentInfo.windowOffset.x + componentInfo.size.width - widthScaleGap;
  184. rstRect.bottom =
  185. componentInfo.translate.y + componentInfo.windowOffset.y + componentInfo.size.height - heightScaleGap;
  186. rstRect.width = rstRect.right - rstRect.left;
  187. rstRect.height = rstRect.bottom - rstRect.top;
  188. return {
  189. left: rstRect.left,
  190. right: rstRect.right,
  191. top: rstRect.top,
  192. bottom: rstRect.bottom,
  193. width: rstRect.width,
  194. height: rstRect.height
  195. }
  196. }
  197. }
收起
自动换行
深色代码主题
复制
  1. // PostNode.ets
  2. // 跨容器迁移能力
  3. import { UIContext, curves, NodeController, BuilderNode, FrameNode } from '@kit.ArkUI';
  4. import { common } from '@kit.AbilityKit';
  5. class Data {
  6. public item: string | null = null;
  7. public isExpand: boolean = false;
  8. }
  9. let context: undefined | common.UIAbilityContext = undefined;
  10. @Builder
  11. function postBuilder(data: Data) {
  12. // 跨容器迁移组件置于@Builder内
  13. Column() {
  14. Row() {
  15. Row()
  16. .backgroundColor(Color.Pink)
  17. .borderRadius(20)
  18. .width(80)
  19. .height(80)
  20. Column() {
  21. // 请在resources\base\element\string.json文件中配置name为'shareTransition_text5',value为非空字符串的资源
  22. Text((context as common.UIAbilityContext)?.resourceManager.getStringByNameSync('shareTransition_text5') + data.item)
  23. .fontSize(20)
  24. // 请将$r('app.string.shareTransition_text6')替换为实际资源文件,在本示例中该资源文件的value值为"共享元素转场"
  25. Text($r('app.string.shareTransition_text6'))
  26. .fontSize(12)
  27. .fontColor(0x909399)
  28. }
  29. .alignItems(HorizontalAlign.Start)
  30. .justifyContent(FlexAlign.SpaceAround)
  31. .margin({ left: 10 })
  32. .height(80)
  33. }
  34. .width('90%')
  35. .height(100)
  36. // 展开后显示细节内容
  37. if (data.isExpand) {
  38. Row() {
  39. // 请将$r('app.string.shareTransition_text7')替换为实际资源文件,在本示例中该资源文件的value值为"展开态"
  40. Text($r('app.string.shareTransition_text7'))
  41. .fontSize(28)
  42. .fontColor(0x909399)
  43. .textAlign(TextAlign.Center)
  44. .transition(TransitionEffect.OPACITY.animation({ curve: curves.springMotion(0.6, 0.9) }))
  45. }
  46. .width('90%')
  47. .justifyContent(FlexAlign.Center)
  48. }
  49. }
  50. .width('90%')
  51. .height('100%')
  52. .alignItems(HorizontalAlign.Center)
  53. .borderRadius(10)
  54. .margin({ top: 15 })
  55. .backgroundColor(Color.White)
  56. .shadow({
  57. radius: 20,
  58. color: 0x909399,
  59. offsetX: 20,
  60. offsetY: 10
  61. })
  62. }
  63. class InternalValue {
  64. public flag: boolean = false;
  65. };
  66. export class PostNode extends NodeController {
  67. private node: BuilderNode<Data[]> | null = null;
  68. private isRemove: InternalValue = new InternalValue();
  69. private callback: Function | undefined = undefined;
  70. private data: Data | null = null;
  71. makeNode(uiContext: UIContext): FrameNode | null {
  72. if (this.isRemove.flag === true) {
  73. return null;
  74. }
  75. if (this.node != null) {
  76. return this.node.getFrameNode();
  77. }
  78. return null;
  79. }
  80. init(uiContext: UIContext, id: string, isExpand: boolean) {
  81. if (this.node != null) {
  82. return;
  83. }
  84. // 创建节点,需要uiContext
  85. this.node = new BuilderNode(uiContext);
  86. context = uiContext.getHostContext() as common.UIAbilityContext;
  87. // 创建离线组件
  88. this.data = { item: id, isExpand: isExpand };
  89. this.node.build(wrapBuilder<Data[]>(postBuilder), this.data);
  90. }
  91. update(id: string, isExpand: boolean) {
  92. if (this.node !== null) {
  93. // 调用update进行更新。
  94. this.data = { item: id, isExpand: isExpand };
  95. this.node.update(this.data);
  96. }
  97. }
  98. setCallback(callback: Function | undefined) {
  99. this.callback = callback;
  100. }
  101. callCallback() {
  102. if (this.callback != undefined) {
  103. this.callback();
  104. }
  105. }
  106. onRemove() {
  107. this.isRemove.flag = true;
  108. // 组件迁移出节点时触发重建
  109. this.rebuild();
  110. this.isRemove.flag = false;
  111. }
  112. }
  113. let gNodeMap: Map<string, PostNode | undefined> = new Map();
  114. export const createPostNode =
  115. (uiContext: UIContext, id: string, isExpand: boolean): PostNode | undefined => {
  116. let node = new PostNode();
  117. node.init(uiContext, id, isExpand);
  118. gNodeMap.set(id, node);
  119. return node;
  120. }
  121. export const getPostNode = (id: string): PostNode | undefined => {
  122. if (!gNodeMap.has(id)) {
  123. return undefined;
  124. }
  125. return gNodeMap.get(id);
  126. }
  127. export const deleteNode = (id: string) => {
  128. gNodeMap.delete(id);
  129. }

结合Navigation使用

可以利用Navigation的自定义导航转场动画能力(customNavContentTransition,可参考Navigation示例3)实现一镜到底动效。共享元素转场期间,组件由消失页面迁移至出现页面。

以展开收起缩略图的场景为例,实现步骤为:

  • 通过customNavContentTransition配置PageOne与PageTwo的自定义导航转场动画。

  • 自定义的共享元素转场效果由属性动画实现,具体实现方式为抓取页面内组件相对窗口的位置信息从而正确匹配组件在PageOne与PageTwo的位置、缩放等,即动画开始和结束的属性信息。

  • 点击缩略图后共享元素组件从PageOne被迁移至PageTwo,随后触发由PageOne至PageTwo的自定义转场动画,即PageTwo的共享元素组件从原来的缩略图状态做动画到全屏状态。

  • 由全屏状态返回到缩略图时,触发由PageTwo至PageOne的自定义转场动画,即PageTwo的共享元素组件从全屏状态做动画到原PageOne的缩略图状态,转场结束后共享元素组件从PageTwo被迁移回PageOne。

收起
自动换行
深色代码主题
复制
  1. ├──entry/src/main/ets // 代码区
  2. │ ├──CustomTransition
  3. │ │ ├──AnimationProperties.ets // 一镜到底转场动画封装
  4. │ │ └──CustomNavigationUtils.ets // Navigation自定义转场动画配置
  5. │ ├──entryability
  6. │ │ └──EntryAbility.ets // 程序入口类
  7. │ ├──NodeContainer
  8. │ │ └──CustomComponent.ets // 自定义占位节点
  9. │ ├──pages
  10. │ │ ├──Index.ets // 导航页面
  11. │ │ ├──PageOne.ets // 缩略图页面
  12. │ │ └──PageTwo.ets // 全屏展开页面
  13. │ └──utils
  14. │ ├──ComponentAttrUtils.ets // 组件位置获取
  15. │ └──WindowUtils.ets // 窗口信息
  16. └──entry/src/main/resources // 资源文件
收起
自动换行
深色代码主题
复制
  1. // Index.ets
  2. import { AnimateCallback, CustomTransition } from '../../../CustomTransition/CustomNavigationUtils';
  3. import { hilog } from '@kit.PerformanceAnalysisKit';
  4. const TAG: string = 'Index';
  5. const DOMAIN = 0xF811;
  6. @Entry
  7. @Component
  8. struct Index {
  9. private pageInfos: NavPathStack = new NavPathStack();
  10. // 允许进行自定义转场的页面名称
  11. private allowedCustomTransitionFromPageName: string[] = ['PageOne'];
  12. private allowedCustomTransitionToPageName: string[] = ['PageTwo'];
  13. aboutToAppear(): void {
  14. this.pageInfos.pushPath({ name: 'PageOne' });
  15. }
  16. private isCustomTransitionEnabled(fromName: string, toName: string): boolean {
  17. // 点击和返回均需要进行自定义转场,因此需要分别判断
  18. if ((this.allowedCustomTransitionFromPageName.includes(fromName) &&
  19. this.allowedCustomTransitionToPageName.includes(toName)) ||
  20. (this.allowedCustomTransitionFromPageName.includes(toName) &&
  21. this.allowedCustomTransitionToPageName.includes(fromName))) {
  22. return true;
  23. }
  24. return false;
  25. }
  26. build() {
  27. Navigation(this.pageInfos)
  28. .hideNavBar(true)
  29. .customNavContentTransition((from: NavContentInfo, to: NavContentInfo, operation: NavigationOperation) => {
  30. if ((!from || !to) || (!from.name || !to.name)) {
  31. return undefined;
  32. }
  33. // 通过from和to的name对自定义转场路由进行管控
  34. if (!this.isCustomTransitionEnabled(from.name, to.name)) {
  35. return undefined;
  36. }
  37. // 需要对转场页面是否注册了animation进行判断,来决定是否进行自定义转场
  38. let fromParam: AnimateCallback = CustomTransition.getInstance().getAnimateParam(from.index);
  39. let toParam: AnimateCallback = CustomTransition.getInstance().getAnimateParam(to.index);
  40. if (!fromParam.animation || !toParam.animation) {
  41. return undefined;
  42. }
  43. // 一切判断完成后,构造customAnimation给系统侧调用,执行自定义转场动画
  44. let customAnimation: NavigationAnimatedTransition = {
  45. onTransitionEnd: (isSuccess: boolean) => {
  46. hilog.info(DOMAIN, 'current transition result is', 'isSuccess: %s', isSuccess.toString());
  47. },
  48. timeout: 2000,
  49. transition: (transitionProxy: NavigationTransitionProxy) => {
  50. hilog.info(DOMAIN, TAG, 'trigger transition callback');
  51. if (fromParam.animation) {
  52. fromParam.animation(operation === NavigationOperation.PUSH, true, transitionProxy);
  53. }
  54. if (toParam.animation) {
  55. toParam.animation(operation === NavigationOperation.PUSH, false, transitionProxy);
  56. }
  57. }
  58. };
  59. return customAnimation;
  60. })
  61. }
  62. }
收起
自动换行
深色代码主题
复制
  1. // PageOne.ets
  2. import { CustomTransition } from '../../../CustomTransition/CustomNavigationUtils';
  3. import { MyNodeController, createMyNode, getMyNode } from '../../../NodeContainer/CustomComponent';
  4. import { ComponentAttrUtils, RectInfoInPx } from '../../../utils/ComponentAttrUtils';
  5. import { WindowUtils } from '../../../utils/WindowUtils';
  6. @Builder
  7. export function PageOneBuilder() {
  8. PageOne();
  9. }
  10. @Component
  11. export struct PageOne {
  12. private pageInfos: NavPathStack = new NavPathStack();
  13. private pageId: number = -1;
  14. @State myNodeController: MyNodeController | undefined = new MyNodeController(false);
  15. aboutToAppear(): void {
  16. let node = getMyNode();
  17. if (node === undefined) {
  18. // 新建自定义节点
  19. createMyNode(this.getUIContext());
  20. }
  21. this.myNodeController = getMyNode();
  22. }
  23. private doFinishTransition(): void {
  24. // PageTwo结束转场时将节点从PageTwo迁移回PageOne
  25. this.myNodeController = getMyNode();
  26. }
  27. private registerCustomTransition(): void {
  28. // 注册自定义动画协议
  29. CustomTransition.getInstance().registerNavParam(this.pageId,
  30. (isPush: boolean, isExit: boolean, transitionProxy: NavigationTransitionProxy) => {
  31. }, 500);
  32. }
  33. private onCardClicked(): void {
  34. let cardItemInfo: RectInfoInPx =
  35. ComponentAttrUtils.getRectInfoById(WindowUtils.window.getUIContext(), 'card');
  36. let param: Record<string, Object> = {};
  37. param['cardItemInfo'] = cardItemInfo;
  38. param['doDefaultTransition'] = (myController: MyNodeController) => {
  39. this.doFinishTransition();
  40. };
  41. this.pageInfos.pushPath({ name: 'PageTwo', param: param });
  42. // 自定义节点从PageOne下树
  43. if (this.myNodeController != undefined) {
  44. (this.myNodeController as MyNodeController).onRemove();
  45. }
  46. }
  47. build() {
  48. NavDestination() {
  49. Stack() {
  50. Column({ space: 20 }) {
  51. Row({ space: 10 }) {
  52. // 请将$r('app.media.avatar')替换为实际资源文件
  53. Image($r('app.media.avatar'))
  54. .size({ width: 50, height: 50 })
  55. .borderRadius(25)
  56. .clip(true)
  57. Text('Alice')
  58. }
  59. .justifyContent(FlexAlign.Start)
  60. // 请将$r('app.string.shareTransition_text2')替换为实际资源文件,在本示例中该资源文件的value值为"你好世界"
  61. Text($r('app.string.shareTransition_text2'))
  62. NodeContainer(this.myNodeController)
  63. .size({ width: 320, height: 250 })
  64. .onClick(() => {
  65. this.onCardClicked();
  66. })
  67. }
  68. .alignItems(HorizontalAlign.Start)
  69. .margin(30)
  70. }
  71. }
  72. .onReady((context: NavDestinationContext) => {
  73. this.pageInfos = context.pathStack;
  74. this.pageId = this.pageInfos.getAllPathName().length - 1;
  75. this.registerCustomTransition();
  76. })
  77. .onDisAppear(() => {
  78. CustomTransition.getInstance().unRegisterNavParam(this.pageId);
  79. // 自定义节点从PageOne下树
  80. if (this.myNodeController != undefined) {
  81. (this.myNodeController as MyNodeController).onRemove();
  82. }
  83. })
  84. }
  85. }
收起
自动换行
深色代码主题
复制
  1. // PageTwo.ets
  2. import { CustomTransition } from '../../../CustomTransition/CustomNavigationUtils';
  3. import { AnimationProperties } from '../../../CustomTransition/AnimationProperties';
  4. import { RectInfoInPx } from '../../../utils/ComponentAttrUtils';
  5. import { getMyNode, MyNodeController } from '../../../NodeContainer/CustomComponent';
  6. @Builder
  7. export function PageTwoBuilder() {
  8. PageTwo();
  9. }
  10. @Component
  11. export struct PageTwo {
  12. @State pageInfos: NavPathStack = new NavPathStack();
  13. @State animationProperties: AnimationProperties = new AnimationProperties(this.getUIContext());
  14. @State myNodeController: MyNodeController | undefined = new MyNodeController(false);
  15. private pageId: number = -1;
  16. private shouldDoDefaultTransition: boolean = false;
  17. private prePageDoFinishTransition: () => void = () => {};
  18. private cardItemInfo: RectInfoInPx = new RectInfoInPx();
  19. @StorageProp('windowSizeChanged') @Watch('unRegisterNavParam') windowSizeChangedTime: number = 0;
  20. @StorageProp('onConfigurationUpdate') @Watch('unRegisterNavParam') onConfigurationUpdateTime: number = 0;
  21. aboutToAppear(): void {
  22. // 迁移自定义节点至当前页面
  23. this.myNodeController = getMyNode();
  24. }
  25. private unRegisterNavParam(): void {
  26. this.shouldDoDefaultTransition = true;
  27. }
  28. private onBackPressed(): boolean {
  29. if (this.shouldDoDefaultTransition) {
  30. CustomTransition.getInstance().unRegisterNavParam(this.pageId);
  31. this.pageInfos.pop();
  32. this.prePageDoFinishTransition();
  33. this.shouldDoDefaultTransition = false;
  34. return true;
  35. }
  36. this.pageInfos.pop();
  37. return true;
  38. }
  39. build() {
  40. NavDestination() {
  41. // Stack需要设置alignContent为TopStart,否则在高度变化过程中,截图和内容都会随高度重新布局位置
  42. Stack({ alignContent: Alignment.TopStart }) {
  43. Stack({ alignContent: Alignment.TopStart }) {
  44. Column({ space: 20 }) {
  45. NodeContainer(this.myNodeController);
  46. if (this.animationProperties.showDetailContent) {
  47. // 请将$r('app.string.shareTransition_text8')替换为实际资源文件,在本示例中该资源文件的value值为"展开态内容"
  48. Text($r('app.string.shareTransition_text8'))
  49. .fontSize(20)
  50. .transition(TransitionEffect.OPACITY)
  51. .margin(30)
  52. }
  53. }
  54. .alignItems(HorizontalAlign.Start)
  55. }
  56. .position({ y: this.animationProperties.positionValue });
  57. }
  58. .scale({ x: this.animationProperties.scaleValue, y: this.animationProperties.scaleValue })
  59. .translate({ x: this.animationProperties.translateX, y: this.animationProperties.translateY })
  60. .width(this.animationProperties.clipWidth)
  61. .height(this.animationProperties.clipHeight)
  62. .borderRadius(this.animationProperties.radius)
  63. // expandSafeArea使得Stack做沉浸式效果,向上扩到状态栏,向下扩到导航条
  64. .expandSafeArea([SafeAreaType.SYSTEM])
  65. // 对高度进行裁切
  66. .clip(true)
  67. }
  68. .backgroundColor(this.animationProperties.navDestinationBgColor)
  69. .hideTitleBar(true)
  70. .onReady((context: NavDestinationContext) => {
  71. this.pageInfos = context.pathStack;
  72. this.pageId = this.pageInfos.getAllPathName().length - 1;
  73. let param = context.pathInfo?.param as Record<string, Object>;
  74. this.prePageDoFinishTransition = param['doDefaultTransition'] as () => void;
  75. this.cardItemInfo = param['cardItemInfo'] as RectInfoInPx;
  76. CustomTransition.getInstance().registerNavParam(this.pageId,
  77. (isPush: boolean, isExit: boolean, transitionProxy: NavigationTransitionProxy) => {
  78. this.animationProperties.doAnimation(
  79. this.cardItemInfo, isPush, isExit, transitionProxy, 0,
  80. this.prePageDoFinishTransition, this.myNodeController);
  81. }, 500);
  82. })
  83. .onBackPressed(() => {
  84. return this.onBackPressed();
  85. })
  86. .onDisAppear(() => {
  87. CustomTransition.getInstance().unRegisterNavParam(this.pageId);
  88. })
  89. }
  90. }
收起
自动换行
深色代码主题
复制
  1. // CustomNavigationUtils.ets
  2. // 配置Navigation自定义转场动画
  3. export interface AnimateCallback {
  4. animation: ((isPush: boolean, isExit: boolean, transitionProxy: NavigationTransitionProxy) => void | undefined)
  5. | undefined;
  6. timeout: (number | undefined) | undefined;
  7. }
  8. const customTransitionMap: Map<number, AnimateCallback> = new Map();
  9. export class CustomTransition {
  10. private constructor() {
  11. };
  12. static delegate = new CustomTransition();
  13. static getInstance() {
  14. return CustomTransition.delegate;
  15. }
  16. // 注册页面的动画回调,name是注册页面的动画的回调
  17. // animationCallback是需要执行的动画内容,timeout是转场结束的超时时间
  18. registerNavParam(
  19. name: number,
  20. animationCallback: (operation: boolean, isExit: boolean, transitionProxy: NavigationTransitionProxy) => void,
  21. timeout: number): void {
  22. if (customTransitionMap.has(name)) {
  23. let param = customTransitionMap.get(name);
  24. if (param != undefined) {
  25. param.animation = animationCallback;
  26. param.timeout = timeout;
  27. return;
  28. }
  29. }
  30. let params: AnimateCallback = { timeout: timeout, animation: animationCallback };
  31. customTransitionMap.set(name, params);
  32. }
  33. unRegisterNavParam(name: number): void {
  34. customTransitionMap.delete(name);
  35. }
  36. getAnimateParam(name: number): AnimateCallback {
  37. let result: AnimateCallback = {
  38. animation: customTransitionMap.get(name)?.animation,
  39. timeout: customTransitionMap.get(name)?.timeout,
  40. };
  41. return result;
  42. }
  43. }
收起
自动换行
深色代码主题
复制
  1. // 工程配置文件module.json5中配置 {"routerMap": "$profile:route_map"}
  2. // route_map.json
  3. {
  4. "routerMap": [
  5. {
  6. "name": "PageOne",
  7. "pageSourceFile": "src/main/ets/pages/PageOne.ets",
  8. "buildFunction": "PageOneBuilder"
  9. },
  10. {
  11. "name": "PageTwo",
  12. "pageSourceFile": "src/main/ets/pages/PageTwo.ets",
  13. "buildFunction": "PageTwoBuilder"
  14. }
  15. ]
  16. }
收起
自动换行
深色代码主题
复制
  1. // AnimationProperties.ets
  2. // 一镜到底转场动画封装
  3. import { curves, UIContext } from '@kit.ArkUI';
  4. import { RectInfoInPx } from '../utils/ComponentAttrUtils';
  5. import { WindowUtils } from '../utils/WindowUtils';
  6. import { MyNodeController } from '../NodeContainer/CustomComponent';
  7. import { hilog } from '@kit.PerformanceAnalysisKit';
  8. const TAG: string = 'AnimationProperties';
  9. const DOMAIN = 0xF811;
  10. const DEVICE_BORDER_RADIUS: number = 34;
  11. // 将自定义一镜到底转场动画进行封装,其他界面也需要做自定义一镜到底转场的话,可以直接复用,减少工作量
  12. @Observed
  13. export class AnimationProperties {
  14. public navDestinationBgColor: ResourceColor = Color.Transparent;
  15. public translateX: number = 0;
  16. public translateY: number = 0;
  17. public scaleValue: number = 1;
  18. public clipWidth: Dimension = 0;
  19. public clipHeight: Dimension = 0;
  20. public radius: number = 0;
  21. public positionValue: number = 0;
  22. public showDetailContent: boolean = false;
  23. private uiContext: UIContext;
  24. constructor(uiContext: UIContext) {
  25. this.uiContext = uiContext;
  26. }
  27. public doAnimation(cardItemInfoPx: RectInfoInPx, isPush: boolean, isExit: boolean,
  28. transitionProxy: NavigationTransitionProxy, extraTranslateValue: number,
  29. prePageOnFinish: (index: MyNodeController) => void, myNodeController: MyNodeController | undefined): void {
  30. // 首先计算卡片的宽高与窗口宽高的比例
  31. let widthScaleRatio = cardItemInfoPx.width / WindowUtils.windowWidthPx;
  32. let heightScaleRatio = cardItemInfoPx.height / WindowUtils.windowHeightPx;
  33. let isUseWidthScale = widthScaleRatio > heightScaleRatio;
  34. let initScale: number = isUseWidthScale ? widthScaleRatio : heightScaleRatio;
  35. let initTranslateX: number = 0;
  36. let initTranslateY: number = 0;
  37. let initClipWidth: Dimension = 0;
  38. let initClipHeight: Dimension = 0;
  39. // 使得PageTwo卡片向上扩到状态栏
  40. let initPositionValue: number = -this.uiContext.px2vp(WindowUtils.topAvoidAreaHeightPx + extraTranslateValue);
  41. if (isUseWidthScale) {
  42. initTranslateX = this.uiContext.px2vp(cardItemInfoPx.left -
  43. (WindowUtils.windowWidthPx - cardItemInfoPx.width) / 2);
  44. initClipWidth = '100%';
  45. initClipHeight = this.uiContext.px2vp((cardItemInfoPx.height) / initScale);
  46. initTranslateY = this.uiContext.px2vp(cardItemInfoPx.top - ((this.uiContext.vp2px(initClipHeight) -
  47. this.uiContext.vp2px(initClipHeight) * initScale) / 2));
  48. } else {
  49. initTranslateY = this.uiContext.px2vp(cardItemInfoPx.top -
  50. (WindowUtils.windowHeightPx - cardItemInfoPx.height) / 2);
  51. initClipHeight = '100%';
  52. initClipWidth = this.uiContext.px2vp((cardItemInfoPx.width) / initScale);
  53. initTranslateX = this.uiContext.px2vp(cardItemInfoPx.left -
  54. (WindowUtils.windowWidthPx / 2 - cardItemInfoPx.width / 2));
  55. }
  56. // 转场动画开始前通过计算scale、translate、position和clip height & width,确定节点迁移前后位置一致
  57. hilog.info(DOMAIN, TAG, 'initScale: ' + initScale + ' initTranslateX ' + initTranslateX +
  58. ' initTranslateY ' + initTranslateY + ' initClipWidth ' + initClipWidth +
  59. ' initClipHeight ' + initClipHeight + ' initPositionValue ' + initPositionValue);
  60. // 转场至新页面
  61. if (isPush && !isExit) {
  62. this.scaleValue = initScale;
  63. this.translateX = initTranslateX;
  64. this.clipWidth = initClipWidth;
  65. this.clipHeight = initClipHeight;
  66. this.translateY = initTranslateY;
  67. this.positionValue = initPositionValue;
  68. this.uiContext?.animateTo({
  69. curve: curves.interpolatingSpring(0, 1, 328, 36),
  70. onFinish: () => {
  71. if (transitionProxy) {
  72. transitionProxy.finishTransition();
  73. }
  74. }
  75. }, () => {
  76. this.scaleValue = 1.0;
  77. this.translateX = 0;
  78. this.translateY = 0;
  79. this.clipWidth = '100%';
  80. this.clipHeight = '100%';
  81. // 页面圆角与系统圆角一致
  82. this.radius = DEVICE_BORDER_RADIUS;
  83. this.showDetailContent = true;
  84. })
  85. this.uiContext?.animateTo({
  86. duration: 100,
  87. curve: Curve.Sharp,
  88. }, () => {
  89. // 页面由透明逐渐变为设置背景色
  90. this.navDestinationBgColor = '#00ffffff';
  91. })
  92. // 返回旧页面
  93. } else if (!isPush && isExit) {
  94. this.uiContext?.animateTo({
  95. duration: 350,
  96. curve: Curve.EaseInOut,
  97. onFinish: () => {
  98. if (transitionProxy) {
  99. transitionProxy.finishTransition();
  100. }
  101. prePageOnFinish(myNodeController);
  102. // 自定义节点从PageTwo下树
  103. if (myNodeController != undefined) {
  104. (myNodeController as MyNodeController).onRemove();
  105. }
  106. }
  107. }, () => {
  108. this.scaleValue = initScale;
  109. this.translateX = initTranslateX;
  110. this.translateY = initTranslateY;
  111. this.radius = 0;
  112. this.clipWidth = initClipWidth;
  113. this.clipHeight = initClipHeight;
  114. this.showDetailContent = false;
  115. })
  116. this.uiContext?.animateTo({
  117. duration: 200,
  118. delay: 150,
  119. curve: Curve.Friction,
  120. }, () => {
  121. this.navDestinationBgColor = Color.Transparent;
  122. })
  123. }
  124. }
  125. }
收起
自动换行
深色代码主题
复制
  1. // ComponentAttrUtils.ets
  2. // 获取组件相对窗口的位置
  3. import { componentUtils, UIContext } from '@kit.ArkUI';
  4. import { JSON } from '@kit.ArkTS';
  5. export class ComponentAttrUtils {
  6. // 根据组件的id获取组件的位置信息
  7. public static getRectInfoById(context: UIContext, id: string): RectInfoInPx {
  8. if (!context || !id) {
  9. throw Error('object is empty');
  10. }
  11. let componentInfo: componentUtils.ComponentInfo = context.getComponentUtils().getRectangleById(id);
  12. if (!componentInfo) {
  13. throw Error('object is empty');
  14. }
  15. let rstRect: RectInfoInPx = new RectInfoInPx();
  16. const widthScaleGap = componentInfo.size.width * (1 - componentInfo.scale.x) / 2;
  17. const heightScaleGap = componentInfo.size.height * (1 - componentInfo.scale.y) / 2;
  18. rstRect.left = componentInfo.translate.x + componentInfo.windowOffset.x + widthScaleGap;
  19. rstRect.top = componentInfo.translate.y + componentInfo.windowOffset.y + heightScaleGap;
  20. rstRect.right =
  21. componentInfo.translate.x + componentInfo.windowOffset.x + componentInfo.size.width - widthScaleGap;
  22. rstRect.bottom =
  23. componentInfo.translate.y + componentInfo.windowOffset.y + componentInfo.size.height - heightScaleGap;
  24. rstRect.width = rstRect.right - rstRect.left;
  25. rstRect.height = rstRect.bottom - rstRect.top;
  26. return {
  27. left: rstRect.left,
  28. right: rstRect.right,
  29. top: rstRect.top,
  30. bottom: rstRect.bottom,
  31. width: rstRect.width,
  32. height: rstRect.height
  33. }
  34. }
  35. }
  36. export class RectInfoInPx {
  37. public left: number = 0;
  38. public top: number = 0;
  39. public right: number = 0;
  40. public bottom: number = 0;
  41. public width: number = 0;
  42. public height: number = 0;
  43. }
  44. export class RectJson {
  45. public $rect: Array<number> = [];
  46. }
收起
自动换行
深色代码主题
复制
  1. // WindowUtils.ets
  2. // 窗口信息
  3. import { window } from '@kit.ArkUI';
  4. export class WindowUtils {
  5. public static window: window.Window;
  6. public static windowWidthPx: number;
  7. public static windowHeightPx: number;
  8. public static topAvoidAreaHeightPx: number;
  9. public static navigationIndicatorHeightPx: number;
  10. }
收起
自动换行
深色代码主题
复制
  1. // EntryAbility.ets
  2. // 程序入口处的onWindowStageCreate增加对窗口宽高等的抓取
  3. import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit';
  4. import { WindowUtils } from '../utils/WindowUtils';
  5. import { display, window } from '@kit.ArkUI';
  6. import { hilog } from '@kit.PerformanceAnalysisKit';
  7. const DOMAIN = 0x0000;
  8. const TAG: string = 'EntryAbility';
  9. export default class EntryAbility extends UIAbility {
  10. private currentBreakPoint: string = '';
  11. onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
  12. hilog.info(DOMAIN, TAG, '%{public}s', 'Ability onCreate');
  13. }
  14. onDestroy(): void {
  15. hilog.info(DOMAIN, TAG, '%{public}s', 'Ability onDestroy');
  16. }
  17. onWindowStageCreate(windowStage: window.WindowStage): void {
  18. // Main window is created, set main page for this ability
  19. hilog.info(DOMAIN, TAG, '%{public}s', 'Ability onWindowStageCreate');
  20. // ...
  21. // 获取窗口宽高
  22. WindowUtils.window = windowStage.getMainWindowSync();
  23. WindowUtils.windowWidthPx = WindowUtils.window.getWindowProperties().windowRect.width;
  24. WindowUtils.windowHeightPx = WindowUtils.window.getWindowProperties().windowRect.height;
  25. this.updateBreakpoint(WindowUtils.windowWidthPx);
  26. // 获取上方避让区(状态栏等)高度
  27. let avoidArea = WindowUtils.window.getWindowAvoidArea(window.AvoidAreaType.TYPE_SYSTEM);
  28. WindowUtils.topAvoidAreaHeightPx = avoidArea.topRect.height;
  29. // 获取导航条高度
  30. let navigationArea = WindowUtils.window.getWindowAvoidArea(window.AvoidAreaType.TYPE_NAVIGATION_INDICATOR);
  31. WindowUtils.navigationIndicatorHeightPx = navigationArea.bottomRect.height;
  32. hilog.info(DOMAIN, TAG, 'the width is ' + WindowUtils.windowWidthPx + ' ' + WindowUtils.windowHeightPx + ' ' +
  33. WindowUtils.topAvoidAreaHeightPx + ' ' + WindowUtils.navigationIndicatorHeightPx);
  34. // 监听窗口尺寸、状态栏高度及导航条高度的变化并更新
  35. try {
  36. WindowUtils.window.on('windowSizeChange', (data) => {
  37. hilog.info(DOMAIN, TAG, 'on windowSizeChange, the width is ' + data.width + ', the height is ' + data.height);
  38. WindowUtils.windowWidthPx = data.width;
  39. WindowUtils.windowHeightPx = data.height;
  40. this.updateBreakpoint(data.width);
  41. AppStorage.setOrCreate('windowSizeChanged', Date.now());
  42. })
  43. WindowUtils.window.on('avoidAreaChange', (data) => {
  44. if (data.type === window.AvoidAreaType.TYPE_SYSTEM) {
  45. let topRectHeight = data.area.topRect.height;
  46. hilog.info(DOMAIN, TAG, 'on avoidAreaChange, the top avoid area height is ' + topRectHeight);
  47. WindowUtils.topAvoidAreaHeightPx = topRectHeight;
  48. } else if (data.type === window.AvoidAreaType.TYPE_NAVIGATION_INDICATOR) {
  49. let bottomRectHeight = data.area.bottomRect.height;
  50. hilog.info(DOMAIN, TAG, 'on avoidAreaChange, the navigation indicator height is ' + bottomRectHeight);
  51. WindowUtils.navigationIndicatorHeightPx = bottomRectHeight;
  52. }
  53. })
  54. } catch (exception) {
  55. hilog.error(DOMAIN, TAG, `register failed. code: ${exception.code}, message: ${exception.message}`);
  56. }
  57. windowStage.loadContent('pages/Index', (err) => {
  58. if (err.code) {
  59. hilog.error(DOMAIN, TAG, 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
  60. return;
  61. }
  62. hilog.info(DOMAIN, TAG, 'Succeeded in loading the content.');
  63. });
  64. }
  65. updateBreakpoint(width: number) {
  66. let windowWidthVp = width / (display.getDefaultDisplaySync().densityDPI / 160);
  67. let newBreakPoint: string = '';
  68. if (windowWidthVp < 400) {
  69. newBreakPoint = 'xs';
  70. } else if (windowWidthVp < 600) {
  71. newBreakPoint = 'sm';
  72. } else if (windowWidthVp < 800) {
  73. newBreakPoint = 'md';
  74. } else {
  75. newBreakPoint = 'lg';
  76. }
  77. if (this.currentBreakPoint !== newBreakPoint) {
  78. this.currentBreakPoint = newBreakPoint;
  79. // 使用状态变量记录当前断点值
  80. AppStorage.setOrCreate('currentBreakpoint', this.currentBreakPoint);
  81. }
  82. }
  83. onWindowStageDestroy(): void {
  84. // Main window is destroyed, release UI related resources
  85. hilog.info(DOMAIN, TAG, '%{public}s', 'Ability onWindowStageDestroy');
  86. }
  87. onForeground(): void {
  88. // Ability has brought to foreground
  89. hilog.info(DOMAIN, TAG, '%{public}s', 'Ability onForeground');
  90. }
  91. onBackground(): void {
  92. // Ability has back to background
  93. hilog.info(DOMAIN, TAG, '%{public}s', 'Ability onBackground');
  94. }
  95. }
收起
自动换行
深色代码主题
复制
  1. // CustomComponent.ets
  2. // 自定义占位节点,跨容器迁移能力
  3. import { BuilderNode, FrameNode, NodeController } from '@kit.ArkUI';
  4. @Builder
  5. function cardBuilder() {
  6. // 请将$r('app.media.card')替换为实际资源文件
  7. Image($r('app.media.card'))
  8. .width('100%')
  9. .id('card')
  10. }
  11. export class MyNodeController extends NodeController {
  12. private cardNode: BuilderNode<[]> | null = null;
  13. private wrapBuilder: WrappedBuilder<[]> = wrapBuilder(cardBuilder);
  14. private needCreate: boolean = false;
  15. private isRemove: boolean = false;
  16. constructor(create: boolean) {
  17. super();
  18. this.needCreate = create;
  19. }
  20. makeNode(uiContext: UIContext): FrameNode | null {
  21. if (this.isRemove === true) {
  22. return null;
  23. }
  24. if (this.needCreate && this.cardNode === null) {
  25. this.cardNode = new BuilderNode(uiContext);
  26. this.cardNode.build(this.wrapBuilder);
  27. }
  28. if (this.cardNode === null) {
  29. return null;
  30. }
  31. return this.cardNode!.getFrameNode()!;
  32. }
  33. getNode(): BuilderNode<[]> | null {
  34. return this.cardNode;
  35. }
  36. setNode(node: BuilderNode<[]> | null) {
  37. this.cardNode = node;
  38. this.rebuild();
  39. }
  40. onRemove() {
  41. this.isRemove = true;
  42. this.rebuild();
  43. this.isRemove = false;
  44. }
  45. init(uiContext: UIContext) {
  46. this.cardNode = new BuilderNode(uiContext);
  47. this.cardNode.build(this.wrapBuilder);
  48. }
  49. }
  50. let myNode: MyNodeController | undefined;
  51. export const createMyNode =
  52. (uiContext: UIContext) => {
  53. myNode = new MyNodeController(false);
  54. myNode.init(uiContext);
  55. }
  56. export const getMyNode = (): MyNodeController | undefined => {
  57. return myNode;
  58. }

结合BindSheet使用

想实现半模态转场(bindSheet)的同时,组件从初始界面做一镜到底动画到半模态页面的效果,可以使用这样的设计思路。将SheetOptions中的mode设置为SheetMode.EMBEDDED,该模式下新起的页面可以覆盖在半模态弹窗上,页面返回后该半模态依旧存在,半模态面板内容不丢失。在半模态转场的同时设置一全模态转场(bindContentCover)页面无转场出现,该页面仅有需要做共享元素转场的组件,通过属性动画,展示组件从初始界面至半模态页面的一镜到底动效,并在动画结束时关闭页面,并将该组件迁移至半模态页面。

以点击图片展开半模态页的场景为例,实现步骤为:

  • 在初始界面挂载半模态转场和全模态转场两个页面,半模态页按需布局,全模态页面仅放置一镜到底动效需要的组件,抓取布局信息,使其初始位置为初始界面图片的位置。点击初始界面图片时,同时触发半模态和全模态页面出现,因设置为SheetMode.EMBEDDED模式,此时全模态页面层级最高。

  • 设置不可见的占位图片置于半模态页上,作为一镜到底动效结束时图片的终止位置。利用布局回调监听该占位图片布局完成的时候,此时执行回调抓取占位图片的位置信息,随后全模态页面上的图片利用属性动画开始进行共享元素转场。

  • 全模态页面的动画结束时触发结束回调,关闭全模态页面,将共享元素图片的节点迁移至半模态页面,替换占位图片。

  • 需注意,半模态页面的弹起高度不同,其页面起始位置也有所不同,而全模态则是全屏显示,两者存在一高度差,做一镜到底动画时,需要计算差值并进行修正,具体可见demo。

  • 还可以配合一镜到底动画,给初始界面图片也增加一个从透明到出现的动画,使得动效更为流畅。

收起
自动换行
深色代码主题
复制
  1. ├──entry/src/main/ets // 代码区
  2. │ ├──entryability
  3. │ │ └──EntryAbility.ets // 程序入口类
  4. │ ├──NodeContainer
  5. │ │ └──CustomComponent.ets // 自定义占位节点
  6. │ ├──pages
  7. │ │ └──Index.ets // 进行共享元素转场的主页面
  8. │ └──utils
  9. │ ├──ComponentAttrUtils.ets // 组件位置获取
  10. │ └──WindowUtils.ets // 窗口信息
  11. └──entry/src/main/resources // 资源文件
收起
自动换行
深色代码主题
复制
  1. // Index.ets
  2. import { MyNodeController, createMyNode, getMyNode } from '../NodeContainer/CustomComponent';
  3. import { ComponentAttrUtils, RectInfoInPx } from '../utils/ComponentAttrUtils';
  4. import { WindowUtils } from '../utils/WindowUtils';
  5. import { inspector } from '@kit.ArkUI'
  6. class AnimationInfo {
  7. scale: number = 0;
  8. translateX: number = 0;
  9. translateY: number = 0;
  10. clipWidth: Dimension = 0;
  11. clipHeight: Dimension = 0;
  12. }
  13. @Entry
  14. @Component
  15. struct Index {
  16. @State isShowSheet: boolean = false;
  17. @State isShowImage: boolean = false;
  18. @State isShowOverlay: boolean = false;
  19. @State isAnimating: boolean = false;
  20. @State isEnabled: boolean = true;
  21. @State scaleValue: number = 0;
  22. @State translateX: number = 0;
  23. @State translateY: number = 0;
  24. @State clipWidth: Dimension = 0;
  25. @State clipHeight: Dimension = 0;
  26. @State radius: number = 0;
  27. // 原图的透明度
  28. @State opacityDegree: number = 1;
  29. // 抓取照片原位置信息
  30. private originInfo: AnimationInfo = new AnimationInfo;
  31. // 抓取照片在半模态页上位置信息
  32. private targetInfo: AnimationInfo = new AnimationInfo;
  33. // 半模态高度
  34. private bindSheetHeight: number = 450;
  35. // 半模态上图片圆角
  36. private sheetRadius: number = 20;
  37. // 设置半模态上图片的布局监听
  38. listener:inspector.ComponentObserver = this.getUIContext().getUIInspector().createComponentObserver('target');
  39. aboutToAppear(): void {
  40. // 设置半模态上图片的布局完成回调
  41. let onLayoutComplete:()=>void=():void=>{
  42. // 目标图片布局完成时抓取布局信息
  43. this.targetInfo = this.calculateData('target');
  44. // 仅半模态正确布局且此时无动画时触发一镜到底动画
  45. if (this.targetInfo.scale != 0 && this.targetInfo.clipWidth != 0 && this.targetInfo.clipHeight != 0 && !this.isAnimating) {
  46. this.isAnimating = true;
  47. // 用于一镜到底的模态页的属性动画
  48. this.getUIContext()?.animateTo({
  49. duration: 1000,
  50. curve: Curve.Friction,
  51. onFinish: () => {
  52. // 模态转场页(overlay)上的自定义节点下树
  53. this.isShowOverlay = false;
  54. // 半模态上的自定义节点上树,由此完成节点迁移
  55. this.isShowImage = true;
  56. }
  57. }, () => {
  58. this.scaleValue = this.targetInfo.scale;
  59. this.translateX = this.targetInfo.translateX;
  60. this.clipWidth = this.targetInfo.clipWidth;
  61. this.clipHeight = this.targetInfo.clipHeight;
  62. // 修正因半模态高度和缩放导致的高度差
  63. this.translateY = this.targetInfo.translateY +
  64. (this.getUIContext().px2vp(WindowUtils.windowHeightPx) - this.bindSheetHeight
  65. - this.getUIContext().px2vp(WindowUtils.navigationIndicatorHeightPx) - this.getUIContext().px2vp(WindowUtils.topAvoidAreaHeightPx));
  66. // 修正因缩放导致的圆角差异
  67. this.radius = this.sheetRadius / this.scaleValue
  68. })
  69. // 原图从透明到出现的动画
  70. this.getUIContext()?.animateTo({
  71. duration: 2000,
  72. curve: Curve.Friction,
  73. }, () => {
  74. this.opacityDegree = 1;
  75. })
  76. }
  77. }
  78. // 打开布局监听
  79. this.listener.on('layout', onLayoutComplete)
  80. }
  81. // 获取对应id的组件相对窗口左上角的属性
  82. calculateData(id: string): AnimationInfo {
  83. let itemInfo: RectInfoInPx =
  84. ComponentAttrUtils.getRectInfoById(WindowUtils.window.getUIContext(), id);
  85. // 首先计算图片的宽高与窗口宽高的比例
  86. let widthScaleRatio = itemInfo.width / WindowUtils.windowWidthPx;
  87. let heightScaleRatio = itemInfo.height / WindowUtils.windowHeightPx;
  88. let isUseWidthScale = widthScaleRatio > heightScaleRatio;
  89. let itemScale: number = isUseWidthScale ? widthScaleRatio : heightScaleRatio;
  90. let itemTranslateX: number = 0;
  91. let itemClipWidth: Dimension = 0;
  92. let itemClipHeight: Dimension = 0;
  93. let itemTranslateY: number = 0;
  94. if (isUseWidthScale) {
  95. itemTranslateX = this.getUIContext().px2vp(itemInfo.left - (WindowUtils.windowWidthPx - itemInfo.width) / 2);
  96. itemClipWidth = '100%';
  97. itemClipHeight = this.getUIContext().px2vp((itemInfo.height) / itemScale);
  98. itemTranslateY = this.getUIContext().px2vp(itemInfo.top - ((this.getUIContext().vp2px(itemClipHeight) - this.getUIContext().vp2px(itemClipHeight) * itemScale) / 2));
  99. } else {
  100. itemTranslateY = this.getUIContext().px2vp(itemInfo.top - (WindowUtils.windowHeightPx - itemInfo.height) / 2);
  101. itemClipHeight = '100%';
  102. itemClipWidth = this.getUIContext().px2vp((itemInfo.width) / itemScale);
  103. itemTranslateX = this.getUIContext().px2vp(itemInfo.left - (WindowUtils.windowWidthPx / 2 - itemInfo.width / 2));
  104. }
  105. return {
  106. scale: itemScale,
  107. translateX: itemTranslateX ,
  108. translateY: itemTranslateY,
  109. clipWidth: itemClipWidth,
  110. clipHeight: itemClipHeight,
  111. }
  112. }
  113. // 照片页
  114. build() {
  115. Column() {
  116. Text('照片')
  117. .textAlign(TextAlign.Start)
  118. .width('100%')
  119. .fontSize(30)
  120. .padding(20)
  121. // 图片使用Resource资源,需用户自定义
  122. Image($r("app.media.flower"))
  123. .opacity(this.opacityDegree)
  124. .width('90%')
  125. .id('origin')// 挂载半模态页
  126. .enabled(this.isEnabled)
  127. .onClick(() => {
  128. // 获取原始图像的位置信息,将模态页上图片移动缩放至该位置
  129. this.originInfo = this.calculateData('origin');
  130. this.scaleValue = this.originInfo.scale;
  131. this.translateX = this.originInfo.translateX;
  132. this.translateY = this.originInfo.translateY;
  133. this.clipWidth = this.originInfo.clipWidth;
  134. this.clipHeight = this.originInfo.clipHeight;
  135. this.radius = 0;
  136. this.opacityDegree = 0;
  137. // 启动半模态页和模态页
  138. this.isShowSheet = true;
  139. this.isShowOverlay = true;
  140. // 设置原图为不可交互抗打断
  141. this.isEnabled = false;
  142. })
  143. }
  144. .width('100%')
  145. .height('100%')
  146. .padding({ top: 20 })
  147. .alignItems(HorizontalAlign.Center)
  148. .bindSheet(this.isShowSheet, this.mySheet(), {
  149. // Embedded模式使得其他页面可以高于半模态页
  150. mode: SheetMode.EMBEDDED,
  151. height: this.bindSheetHeight,
  152. onDisappear: () => {
  153. // 保证半模态消失时状态正确
  154. this.isShowImage = false;
  155. this.isShowSheet = false;
  156. // 设置一镜到底动画又进入可触发状态
  157. this.isAnimating = false;
  158. // 原图重新变为可交互状态
  159. this.isEnabled = true;
  160. }
  161. }) // 挂载模态页作为一镜到底动画的实现页
  162. .bindContentCover(this.isShowOverlay, this.overlayNode(), {
  163. // 模态页面设置为无转场
  164. transition: TransitionEffect.IDENTITY,
  165. })
  166. }
  167. // 半模态页面
  168. @Builder
  169. mySheet() {
  170. Column({space: 20}) {
  171. Text('半模态页面')
  172. .fontSize(30)
  173. Row({space: 40}) {
  174. Column({space: 20}) {
  175. ForEach([1, 2, 3, 4], () => {
  176. Stack()
  177. .backgroundColor(Color.Pink)
  178. .borderRadius(20)
  179. .width(60)
  180. .height(60)
  181. })
  182. }
  183. Column() {
  184. if (this.isShowImage) {
  185. // 半模态页面的自定义图片节点
  186. ImageNode()
  187. }
  188. else {
  189. // 抓取布局和占位用,实际不显示
  190. // 图片使用Resource资源,需用户自定义
  191. Image($r("app.media.flower"))
  192. .visibility(Visibility.Hidden)
  193. }
  194. }
  195. .height(300)
  196. .width(200)
  197. .borderRadius(20)
  198. .clip(true)
  199. .id('target')
  200. }
  201. .alignItems(VerticalAlign.Top)
  202. }
  203. .alignItems(HorizontalAlign.Start)
  204. .height('100%')
  205. .width('100%')
  206. .margin(40)
  207. }
  208. @Builder
  209. overlayNode() {
  210. // Stack需要设置alignContent为TopStart,否则在高度变化过程中,截图和内容都会随高度重新布局位置
  211. Stack({ alignContent: Alignment.TopStart }) {
  212. ImageNode()
  213. }
  214. .scale({ x: this.scaleValue, y: this.scaleValue, centerX: undefined, centerY: undefined})
  215. .translate({ x: this.translateX, y: this.translateY })
  216. .width(this.clipWidth)
  217. .height(this.clipHeight)
  218. .borderRadius(this.radius)
  219. .clip(true)
  220. }
  221. }
  222. @Component
  223. struct ImageNode {
  224. @State myNodeController: MyNodeController | undefined = new MyNodeController(false);
  225. aboutToAppear(): void {
  226. // 获取自定义节点
  227. let node = getMyNode();
  228. if (node == undefined) {
  229. // 新建自定义节点
  230. createMyNode(this.getUIContext());
  231. }
  232. this.myNodeController = getMyNode();
  233. }
  234. aboutToDisappear(): void {
  235. if (this.myNodeController != undefined) {
  236. // 节点下树
  237. this.myNodeController.onRemove();
  238. }
  239. }
  240. build() {
  241. NodeContainer(this.myNodeController)
  242. }
  243. }
收起
自动换行
深色代码主题
复制
  1. // CustomComponent.ets
  2. // 自定义占位节点,跨容器迁移能力
  3. import { BuilderNode, FrameNode, NodeController } from '@kit.ArkUI';
  4. @Builder
  5. function flowerBuilder() {
  6. // 请将$r('app.media.longevity_flower')替换为实际资源文件
  7. Image($r('app.media.longevity_flower'))
  8. // 避免第一次加载图片时图片闪烁
  9. .syncLoad(true);
  10. }
  11. export class MyNodeController extends NodeController {
  12. private flowerNode: BuilderNode<[]> | null = null;
  13. private wrapBuilder: WrappedBuilder<[]> = wrapBuilder(flowerBuilder);
  14. private needCreate: boolean = false;
  15. private isRemove: boolean = false;
  16. constructor(create: boolean) {
  17. super();
  18. this.needCreate = create;
  19. }
  20. makeNode(uiContext: UIContext): FrameNode | null {
  21. if (this.isRemove === true) {
  22. return null;
  23. }
  24. if (this.needCreate && this.flowerNode === null) {
  25. this.flowerNode = new BuilderNode(uiContext);
  26. this.flowerNode.build(this.wrapBuilder);
  27. }
  28. if (this.flowerNode === null) {
  29. return null;
  30. }
  31. return this.flowerNode!.getFrameNode()!;
  32. }
  33. getNode(): BuilderNode<[]> | null {
  34. return this.flowerNode;
  35. }
  36. setNode(node: BuilderNode<[]> | null) {
  37. this.flowerNode = node;
  38. this.rebuild();
  39. }
  40. onRemove() {
  41. this.isRemove = true;
  42. this.rebuild();
  43. this.isRemove = false;
  44. }
  45. init(uiContext: UIContext) {
  46. this.flowerNode = new BuilderNode(uiContext);
  47. this.flowerNode.build(this.wrapBuilder);
  48. }
  49. }
  50. let myNode: MyNodeController | undefined;
  51. export const createMyNode =
  52. (uiContext: UIContext) => {
  53. myNode = new MyNodeController(false);
  54. myNode.init(uiContext);
  55. }
  56. export const getMyNode = (): MyNodeController | undefined => {
  57. return myNode;
  58. }
收起
自动换行
深色代码主题
复制
  1. // ComponentAttrUtils.ets
  2. // 获取组件相对窗口的位置
  3. import { componentUtils, UIContext } from '@kit.ArkUI';
  4. import { JSON } from '@kit.ArkTS';
  5. export class ComponentAttrUtils {
  6. // 根据组件的id获取组件的位置信息
  7. public static getRectInfoById(context: UIContext, id: string): RectInfoInPx {
  8. if (!context || !id) {
  9. throw Error('object is empty');
  10. }
  11. let componentInfo: componentUtils.ComponentInfo = context.getComponentUtils().getRectangleById(id);
  12. if (!componentInfo) {
  13. throw Error('object is empty');
  14. }
  15. let rstRect: RectInfoInPx = new RectInfoInPx();
  16. const widthScaleGap = componentInfo.size.width * (1 - componentInfo.scale.x) / 2;
  17. const heightScaleGap = componentInfo.size.height * (1 - componentInfo.scale.y) / 2;
  18. rstRect.left = componentInfo.translate.x + componentInfo.windowOffset.x + widthScaleGap;
  19. rstRect.top = componentInfo.translate.y + componentInfo.windowOffset.y + heightScaleGap;
  20. rstRect.right =
  21. componentInfo.translate.x + componentInfo.windowOffset.x + componentInfo.size.width - widthScaleGap;
  22. rstRect.bottom =
  23. componentInfo.translate.y + componentInfo.windowOffset.y + componentInfo.size.height - heightScaleGap;
  24. rstRect.width = rstRect.right - rstRect.left;
  25. rstRect.height = rstRect.bottom - rstRect.top;
  26. return {
  27. left: rstRect.left,
  28. right: rstRect.right,
  29. top: rstRect.top,
  30. bottom: rstRect.bottom,
  31. width: rstRect.width,
  32. height: rstRect.height
  33. }
  34. }
  35. }
  36. export class RectInfoInPx {
  37. public left: number = 0;
  38. public top: number = 0;
  39. public right: number = 0;
  40. public bottom: number = 0;
  41. public width: number = 0;
  42. public height: number = 0;
  43. }
  44. export class RectJson {
  45. public $rect: Array<number> = [];
  46. }
收起
自动换行
深色代码主题
复制
  1. // WindowUtils.ets
  2. // 窗口信息
  3. import { window } from '@kit.ArkUI';
  4. export class WindowUtils {
  5. public static window: window.Window;
  6. public static windowWidthPx: number;
  7. public static windowHeightPx: number;
  8. public static topAvoidAreaHeightPx: number;
  9. public static navigationIndicatorHeightPx: number;
  10. }
收起
自动换行
深色代码主题
复制
  1. // EntryAbility.ets
  2. // 程序入口处的onWindowStageCreate增加对窗口宽高等的抓取
  3. import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit';
  4. import { WindowUtils } from '../utils/WindowUtils';
  5. import { display, window } from '@kit.ArkUI';
  6. import { hilog } from '@kit.PerformanceAnalysisKit';
  7. const DOMAIN = 0x0000;
  8. const TAG: string = 'EntryAbility';
  9. export default class EntryAbility extends UIAbility {
  10. private currentBreakPoint: string = '';
  11. onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
  12. hilog.info(DOMAIN, TAG, '%{public}s', 'Ability onCreate');
  13. }
  14. onDestroy(): void {
  15. hilog.info(DOMAIN, TAG, '%{public}s', 'Ability onDestroy');
  16. }
  17. onWindowStageCreate(windowStage: window.WindowStage): void {
  18. // Main window is created, set main page for this ability
  19. hilog.info(DOMAIN, TAG, '%{public}s', 'Ability onWindowStageCreate');
  20. // ...
  21. // 获取窗口宽高
  22. WindowUtils.window = windowStage.getMainWindowSync();
  23. WindowUtils.windowWidthPx = WindowUtils.window.getWindowProperties().windowRect.width;
  24. WindowUtils.windowHeightPx = WindowUtils.window.getWindowProperties().windowRect.height;
  25. this.updateBreakpoint(WindowUtils.windowWidthPx);
  26. // 获取上方避让区(状态栏等)高度
  27. let avoidArea = WindowUtils.window.getWindowAvoidArea(window.AvoidAreaType.TYPE_SYSTEM);
  28. WindowUtils.topAvoidAreaHeightPx = avoidArea.topRect.height;
  29. // 获取导航条高度
  30. let navigationArea = WindowUtils.window.getWindowAvoidArea(window.AvoidAreaType.TYPE_NAVIGATION_INDICATOR);
  31. WindowUtils.navigationIndicatorHeightPx = navigationArea.bottomRect.height;
  32. hilog.info(DOMAIN, TAG, 'the width is ' + WindowUtils.windowWidthPx + ' ' + WindowUtils.windowHeightPx + ' ' +
  33. WindowUtils.topAvoidAreaHeightPx + ' ' + WindowUtils.navigationIndicatorHeightPx);
  34. // 监听窗口尺寸、状态栏高度及导航条高度的变化并更新
  35. try {
  36. WindowUtils.window.on('windowSizeChange', (data) => {
  37. hilog.info(DOMAIN, TAG, 'on windowSizeChange, the width is ' + data.width + ', the height is ' + data.height);
  38. WindowUtils.windowWidthPx = data.width;
  39. WindowUtils.windowHeightPx = data.height;
  40. this.updateBreakpoint(data.width);
  41. AppStorage.setOrCreate('windowSizeChanged', Date.now());
  42. })
  43. WindowUtils.window.on('avoidAreaChange', (data) => {
  44. if (data.type === window.AvoidAreaType.TYPE_SYSTEM) {
  45. let topRectHeight = data.area.topRect.height;
  46. hilog.info(DOMAIN, TAG, 'on avoidAreaChange, the top avoid area height is ' + topRectHeight);
  47. WindowUtils.topAvoidAreaHeightPx = topRectHeight;
  48. } else if (data.type === window.AvoidAreaType.TYPE_NAVIGATION_INDICATOR) {
  49. let bottomRectHeight = data.area.bottomRect.height;
  50. hilog.info(DOMAIN, TAG, 'on avoidAreaChange, the navigation indicator height is ' + bottomRectHeight);
  51. WindowUtils.navigationIndicatorHeightPx = bottomRectHeight;
  52. }
  53. })
  54. } catch (exception) {
  55. hilog.error(DOMAIN, TAG, `register failed. code: ${exception.code}, message: ${exception.message}`);
  56. }
  57. windowStage.loadContent('pages/Index', (err) => {
  58. if (err.code) {
  59. hilog.error(DOMAIN, TAG, 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
  60. return;
  61. }
  62. hilog.info(DOMAIN, TAG, 'Succeeded in loading the content.');
  63. });
  64. }
  65. updateBreakpoint(width: number) {
  66. let windowWidthVp = width / (display.getDefaultDisplaySync().densityDPI / 160);
  67. let newBreakPoint: string = '';
  68. if (windowWidthVp < 400) {
  69. newBreakPoint = 'xs';
  70. } else if (windowWidthVp < 600) {
  71. newBreakPoint = 'sm';
  72. } else if (windowWidthVp < 800) {
  73. newBreakPoint = 'md';
  74. } else {
  75. newBreakPoint = 'lg';
  76. }
  77. if (this.currentBreakPoint !== newBreakPoint) {
  78. this.currentBreakPoint = newBreakPoint;
  79. // 使用状态变量记录当前断点值
  80. AppStorage.setOrCreate('currentBreakpoint', this.currentBreakPoint);
  81. }
  82. }
  83. onWindowStageDestroy(): void {
  84. // Main window is destroyed, release UI related resources
  85. hilog.info(DOMAIN, TAG, '%{public}s', 'Ability onWindowStageDestroy');
  86. }
  87. onForeground(): void {
  88. // Ability has brought to foreground
  89. hilog.info(DOMAIN, TAG, '%{public}s', 'Ability onForeground');
  90. }
  91. onBackground(): void {
  92. // Ability has back to background
  93. hilog.info(DOMAIN, TAG, '%{public}s', 'Ability onBackground');
  94. }
  95. }

使用geometryTransition共享元素转场

geometryTransition用于组件内隐式共享元素转场,在视图状态切换过程中提供丝滑的上下文继承过渡体验。

geometryTransition的使用方式为对需要添加一镜到底动效的两个组件使用geometryTransition接口绑定同一id,这样在其中一个组件消失同时另一个组件创建出现的时候,系统会对二者添加一镜到底动效。

geometryTransition绑定两个对象的实现方式使得geometryTransition区别于其他方法,最适合用于两个不同对象之间完成一镜到底。

geometryTransition的简单使用

对于同一个页面中的两个元素的一镜到底效果,geometryTransition接口的简单使用示例如下:

收起
自动换行
深色代码主题
复制
  1. import { curves } from '@kit.ArkUI';
  2. @Entry
  3. @Component
  4. struct IfElseGeometryTransition {
  5. @State isShow: boolean = false;
  6. build() {
  7. Stack({ alignContent: Alignment.Center }) {
  8. if (this.isShow) {
  9. // 请将$r('app.media.spring')替换为实际资源文件
  10. Image($r('app.media.spring'))
  11. .autoResize(false)
  12. .clip(true)
  13. .width(200)
  14. .height(200)
  15. .borderRadius(100)
  16. .geometryTransition('picture')
  17. .transition(TransitionEffect.OPACITY)
  18. // 在打断场景下,即动画过程中点击页面触发下一次转场,如果不加id,则会出现重影
  19. // 加了id之后,新建的spring图片会复用之前的spring图片节点,不会重新创建节点,也就不会有重影问题
  20. // 加id的规则为加在if和else下的第一个节点上,有多个并列节点则也需要进行添加
  21. .id('item1')
  22. } else {
  23. // geometryTransition此处绑定的是容器,那么容器内的子组件需设为相对布局跟随父容器变化,
  24. // 套多层容器为了说明相对布局约束传递
  25. Column() {
  26. Column() {
  27. // 请将$r('app.media.sunset_sky')替换为实际资源文件
  28. Image($r('app.media.sunset_sky'))
  29. .size({ width: '100%', height: '100%' })
  30. }
  31. .size({ width: '100%', height: '100%' })
  32. }
  33. .width(100)
  34. .height(100)
  35. // geometryTransition会同步圆角,但仅限于geometryTransition绑定处,此处绑定的是容器
  36. // 则对容器本身有圆角同步而不会操作容器内部子组件的borderRadius
  37. .borderRadius(50)
  38. .clip(true)
  39. .geometryTransition('picture')
  40. // transition保证节点离场不被立即析构,设置通用转场效果
  41. .transition(TransitionEffect.OPACITY)
  42. .position({ x: 40, y: 40 })
  43. .id('item2')
  44. }
  45. }
  46. .onClick(() => {
  47. this.getUIContext()?.animateTo({
  48. curve: curves.springMotion()
  49. }, () => {
  50. this.isShow = !this.isShow;
  51. })
  52. })
  53. .size({ width: '100%', height: '100%' })
  54. }
  55. }

geometryTransition结合模态转场使用

更多的场景中,需要对一个页面的元素与另一个页面的元素添加一镜到底动效。可以通过geometryTransition搭配模态转场接口实现。以点击头像弹出个人信息页的demo为例:

收起
自动换行
深色代码主题
复制
  1. import { common } from '@kit.AbilityKit';
  2. class PostData {
  3. // 请将$r('app.media.flower')替换为实际资源文件
  4. avatar: Resource = $r('app.media.flower');
  5. name: string = '';
  6. message: ResourceStr = '';
  7. images: Resource[] = [];
  8. }
  9. @Entry
  10. @Component
  11. struct Index {
  12. @State isPersonalPageShow: boolean = false;
  13. @State selectedIndex: number = 0;
  14. @State alphaValue: number = 1;
  15. private context = this.getUIContext().getHostContext() as common.UIAbilityContext;
  16. // 数组中图片均使用Resource资源,需用户自定义
  17. private allPostData: PostData[] = [
  18. {
  19. // 请将$r('app.media.flower')替换为实际资源文件
  20. avatar: $r('app.media.flower'),
  21. name: 'Alice',
  22. // 请将$r('app.string.shareTransition_text1')替换为实际资源文件,在本示例中该资源文件的value值为"天气晴朗"
  23. message: $r('app.string.shareTransition_text1'),
  24. // 请将$r('app.media.spring')替换为实际资源文件
  25. // 请将$r('app.media.tall_tree')替换为实际资源文件
  26. images: [$r('app.media.spring'), $r('app.media.tall_tree')]
  27. },
  28. {
  29. // 请将$r('app.media.sunset_sky')替换为实际资源文件
  30. avatar: $r('app.media.sunset_sky'),
  31. name: 'Bob',
  32. // 请将$r('app.string.shareTransition_text2')替换为实际资源文件,在本示例中该资源文件的value值为"你好世界"
  33. message: $r('app.string.shareTransition_text2'),
  34. // 请将$r('app.media.island')替换为实际资源文件
  35. images: [$r('app.media.island')]
  36. },
  37. {
  38. // 请将$r('app.media.tall_tree')替换为实际资源文件
  39. avatar: $r('app.media.tall_tree'),
  40. name: 'Carl',
  41. // 请将$r('app.string.shareTransition_text3')替换为实际资源文件,在本示例中该资源文件的value值为"万物生长"
  42. message: $r('app.string.shareTransition_text3'),
  43. // 请将$r('app.media.flower')替换为实际资源文件
  44. // 请将$r('app.media.sunset_sky')替换为实际资源文件
  45. // 请将$r('app.media.spring')替换为实际资源文件
  46. images: [$r('app.media.flower'), $r('app.media.sunset_sky'), $r('app.media.spring')]
  47. }];
  48. private onAvatarClicked(index: number): void {
  49. this.selectedIndex = index;
  50. this.getUIContext()?.animateTo({
  51. duration: 350,
  52. curve: Curve.Friction
  53. }, () => {
  54. this.isPersonalPageShow = !this.isPersonalPageShow;
  55. this.alphaValue = 0;
  56. });
  57. }
  58. private onPersonalPageBack(index: number): void {
  59. this.getUIContext()?.animateTo({
  60. duration: 350,
  61. curve: Curve.Friction
  62. }, () => {
  63. this.isPersonalPageShow = !this.isPersonalPageShow;
  64. this.alphaValue = 1;
  65. });
  66. }
  67. @Builder
  68. PersonalPageBuilder(index: number) {
  69. Column({ space: 20 }) {
  70. Image(this.allPostData[index].avatar)
  71. .size({ width: 200, height: 200 })
  72. .borderRadius(100)
  73. // 头像配置共享元素效果,与点击的头像的id匹配
  74. .geometryTransition(index.toString())
  75. .clip(true)
  76. .transition(TransitionEffect.opacity(0.99))
  77. Text(this.allPostData[index].name)
  78. .font({ size: 30, weight: 600 })
  79. // 对文本添加出现转场效果
  80. .transition(TransitionEffect.asymmetric(
  81. TransitionEffect.OPACITY
  82. .combine(TransitionEffect.translate({ y: 100 })),
  83. TransitionEffect.OPACITY.animation({ duration: 0 })
  84. ))
  85. // 请在resources\base\element\string.json文件中配置name为'shareTransition_text11',value为非空字符串的资源
  86. Text(this.context.resourceManager.getStringByNameSync('shareTransition_text11') + this.allPostData[index].name)
  87. // 对文本添加出现转场效果
  88. .transition(TransitionEffect.asymmetric(
  89. TransitionEffect.OPACITY
  90. .combine(TransitionEffect.translate({ y: 100 })),
  91. TransitionEffect.OPACITY.animation({ duration: 0 })
  92. ))
  93. }
  94. .padding({ top: 20 })
  95. .size({ width: 360, height: 780 })
  96. .backgroundColor(Color.White)
  97. .onClick(() => {
  98. this.onPersonalPageBack(index);
  99. })
  100. .transition(TransitionEffect.asymmetric(
  101. TransitionEffect.opacity(0.99),
  102. TransitionEffect.OPACITY
  103. ))
  104. }
  105. build() {
  106. Column({ space: 20 }) {
  107. ForEach(this.allPostData, (postData: PostData, index: number) => {
  108. Column() {
  109. Post({
  110. data: postData, index: index, onAvatarClicked: (index: number) => {
  111. this.onAvatarClicked(index);
  112. }
  113. })
  114. }
  115. .width('100%')
  116. }, (postData: PostData, index: number) => index.toString())
  117. }
  118. .size({ width: '100%', height: '100%' })
  119. .backgroundColor('#40808080')
  120. .bindContentCover(this.isPersonalPageShow,
  121. this.PersonalPageBuilder(this.selectedIndex), { modalTransition: ModalTransition.NONE })
  122. .opacity(this.alphaValue)
  123. }
  124. }
  125. @Component
  126. export default struct Post {
  127. @Prop data: PostData;
  128. @Prop index: number;
  129. @State expandImageSize: number = 100;
  130. @State avatarSize: number = 50;
  131. private onAvatarClicked: (index: number) => void = (index: number) => { };
  132. build() {
  133. Column({ space: 20 }) {
  134. Row({ space: 10 }) {
  135. Image(this.data.avatar)
  136. .size({ width: this.avatarSize, height: this.avatarSize })
  137. .borderRadius(this.avatarSize / 2)
  138. .clip(true)
  139. .onClick(() => {
  140. this.onAvatarClicked(this.index);
  141. })
  142. // 对头像绑定共享元素转场的id
  143. .geometryTransition(this.index.toString(), { follow: true })
  144. .transition(TransitionEffect.OPACITY.animation({ duration: 350, curve: Curve.Friction }))
  145. Text(this.data.name)
  146. }
  147. .justifyContent(FlexAlign.Start)
  148. Text(this.data.message)
  149. Row({ space: 15 }) {
  150. ForEach(this.data.images, (imageResource: Resource, index: number) => {
  151. Image(imageResource)
  152. .size({ width: 100, height: 100 })
  153. }, (imageResource: Resource, index: number) => index.toString())
  154. }
  155. }
  156. .backgroundColor(Color.White)
  157. .size({ width: '100%', height: 250 })
  158. .alignItems(HorizontalAlign.Start)
  159. .padding({ left: 10, top: 10 })
  160. }
  161. }

效果为点击主页的头像后,弹出模态页面显示个人信息,并且两个页面之间的头像做一镜到底动效:

元素转场案例

图片展开一镜到底

  • 双指放大转场

    图片使用双指放大转场显示图片详情页。

    通过NodeContainer组件实现跨节点迁移,通过手势捏合来控制节点的上下树,达成一镜到底动效。

    1. 小图模式和大图模式分别为两个页面,通过监听expand值来进行页面切换。

      收起
      自动换行
      深色代码主题
      复制
      1. @StorageProp('expand') @Watch('goToPageTwo') num1: number = 0;
      2. // ...
      3. aboutToAppear(): void {
      4. if (!getMyNode()) {
      5. createMyNode(this.getUIContext(), false);
      6. }
      7. this.imageGalleryNodeController = getMyNode();
      8. }
    2. 创建NodeContainer节点类。

      收起
      自动换行
      深色代码主题
      复制
      1. export class ImageGalleryNodeController extends NodeController {
      2. private rootNode: BuilderNode<[Params]> | null = null;
      3. private wrapBuilder: WrappedBuilder<[Params]> = wrapBuilder(ImageGalleryBuilder);
      4. private isExpand: boolean = false;
      5. constructor(isExpand: boolean) {
      6. super();
      7. this.isExpand = isExpand;
      8. }
      9. makeNode(uiContext: UIContext): FrameNode | null {
      10. if (this.rootNode === null) {
      11. this.rootNode = new BuilderNode(uiContext);
      12. this.rootNode.build(this.wrapBuilder, { isExpand: this.isExpand });
      13. }
      14. return this.rootNode.getFrameNode();
      15. }
      16. init(uiContext: UIContext) {
      17. this.rootNode = new BuilderNode(uiContext);
      18. this.rootNode.build(this.wrapBuilder, { isExpand: this.isExpand });
      19. }
      20. update(isExpand: boolean) {
      21. if (this.rootNode !== null) {
      22. this.rootNode.update({ isExpand });
      23. }
      24. }
      25. }
    3. 在小图界面当对图片进行双指捏合操作时,改变isExpand值。

      收起
      自动换行
      深色代码主题
      复制
      1. PinchGesture()
      2. .onActionStart((event: GestureEvent) => {
      3. this.offsetY = getTranslateToFullScreen(this.getUIContext(), 'swiper')?.offsetY || 0
      4. this.imageHeight = this.getUIContext().vp2px(Number(event.target.area.height))
      5. this.imageWidth = this.getUIContext().vp2px(Number(event.target.area.width))
      6. this.status = Status.PINCHING;
      7. this.updateCenter([this.getUIContext().vp2px(event.pinchCenterX),
      8. this.getUIContext().vp2px(event.pinchCenterY)])
      9. this.updateTranslateAccordingToCenter();
      10. this.startGestureScale = this.imageScale;
      11. this.gestureCount++;
      12. })
      13. .onActionUpdate((event: GestureEvent) => {
      14. this.imageScale = this.startGestureScale * event.scale;
      15. if (!this.isExpand && this.imageScale >= 1) {
      16. this.onExpand();
      17. }
      18. this.updateExtremeOffset();
      19. })
    4. 当expand值更改时,页面进行切换到大图页面,完成一镜到底页面切换。

      收起
      自动换行
      深色代码主题
      复制
      1. NavDestination() {
      2. NodeContainer(this.imageGalleryNodeController)
      3. }
      4. .mode(NavDestinationMode.DIALOG)
      5. .height('100%')
      6. .width('100%')
      7. .hideTitleBar(true)
      8. .onReady((context: NavDestinationContext) => {
      9. this.pageInfo = context.pathStack;
      10. const param = context.pathInfo?.param as Record<string, Object>;
      11. this.onBack = param['onBack'] as () => void;
      12. })
      13. .onBackPressed(() => {
      14. AppStorage.setOrCreate('reset', new Date());
      15. this.getUIContext().animateTo({ duration: 300, curve: Curve.EaseIn }, () => {
      16. this.backToPageOne();
      17. })
      18. return true;
      19. })
  • 查看大图转场

    比如图片在九宫格中显示,点击查看大图,同时还支持手势下拉返回到九宫格。

    设置geometryTransition属性将图片首页和大图页面的图片绑定同一id值,结合属性动画效果实现一镜到底效果。核心代码如下:

    1. 首页通过网格布局实现三行三列图片布局,并给每个图片设置geometryTransition属性,绑定唯一id值,绑定共享的两个图片组件。

      收起
      自动换行
      深色代码主题
      复制
      1. NavDestination() {
      2. Column() {
      3. Grid(this.scroller) {
      4. ForEach(this.data, (item: number) => {
      5. GridItem() {
      6. if (this.clickedIndex !== item || (this.isFirstPageShow)) {
      7. Image($r(`app.media.img_${item % 9}`))
      8. .width('100%')
      9. .height('100%')
      10. .objectFit(ImageFit.Cover)
      11. .id('item2_' + item)
      12. .onClick(() => {
      13. this.onItemClick(item);
      14. })
      15. .geometryTransition(this.clickedIndex === item ? 'app.media.img_' + item.toString() : '')
      16. .transition(TransitionEffect.opacity(0.99))
      17. }
      18. }
      19. .width(this.getUIContext().px2vp(381))
      20. .height(this.getUIContext().px2vp(381))
      21. }, (item: number) => item + '')
      22. }
      23. .rowsTemplate('1fr 1fr 1fr')
      24. .columnsTemplate('1fr 1fr 1fr')
      25. .columnsGap(2)
      26. .rowsGap(2)
      27. .size({
      28. width: this.getUIContext().px2vp(1169),
      29. height: this.getUIContext().px2vp(1169)
      30. })
      31. .margin({ top: 16 })
      32. }
      33. }
      34. .title('View larger picture')
      35. .height('100%')
      36. .width('100%')
      37. .onReady((context: NavDestinationContext) => {
      38. this.pageInfo = context.pathStack;
      39. })
    2. 通过属性动画来进行小图和大图页面的切换,同时为了避免触发Navigation的转场动画,在pushPath()的时候把动画选项设置成了false。

      收起
      自动换行
      深色代码主题
      复制
      1. onItemClick(index: number): void {
      2. let param: Record<string, Object> = {};
      3. this.needFollow = false;
      4. this.clickedIndex = index;
      5. param['selectedIndex'] = this.clickedIndex;
      6. param['onIndexChange'] = (index: number) => {
      7. this.onIndexChange(index);
      8. };
      9. param['onBackToFirstPage'] = () => {
      10. this.onBack();
      11. }
      12. this.getUIContext().animateTo({
      13. duration: 250,
      14. curve: Curve.EaseIn,
      15. }, () => {
      16. this.pageInfo.pushPath({ name: 'ShowLargeImageWithGesturePageTwo', param: param }, false);
      17. this.isFirstPageShow = false;
      18. })
      19. }
  • 半模态转场

    图片从页面向半模态弹窗中转场显示。

    利用NodeContainer组件实现跨节点迁移,将半模态SheetOptions()中的mode设置为SheetMode.EMBEDDED,该模式下新起的页面可以覆盖在半模态弹窗上,页面返回后该半模态依旧存在,半模态面板内容不丢失。通过属性动画,展示组件从初始界面至半模态页面的一镜到底动效,并在动画结束时关闭页面,并将该组件迁移至半模态页面。

    1. 创建NodeContainer节点类。

      收起
      自动换行
      深色代码主题
      复制
      1. export class MyNodeController extends NodeController {
      2. // ...
      3. }
    2. 首页图片绑定半模态弹窗,并通过bindContentCover设置模态转场动画。

      收起
      自动换行
      深色代码主题
      复制
      1. NavDestination() {
      2. Column() {
      3. Image($r('app.media.flower'))
      4. .opacity(this.opacityDegree)
      5. .width('90%')
      6. .id('origin')
      7. .enabled(this.isEnabled)
      8. .onClick(() => {
      9. this.originInfo = this.calculateData('origin');
      10. this.scaleValue = this.originInfo.scale;
      11. this.translateX = this.originInfo.translateX;
      12. this.translateY = this.originInfo.translateY;
      13. this.clipWidth = this.originInfo.clipWidth;
      14. this.clipHeight = this.originInfo.clipHeight;
      15. this.radius = 0;
      16. this.opacityDegree = 0;
      17. this.isShowSheet = true;
      18. this.isShowOverlay = true;
      19. this.isEnabled = false;
      20. })
      21. }
      22. .width('100%')
      23. .height('100%')
      24. .padding({ top: 16 })
      25. .alignItems(HorizontalAlign.Center)
      26. .bindSheet(this.isShowSheet, this.mySheet(), {
      27. mode: SheetMode.EMBEDDED,
      28. height: this.bindSheetHeight,
      29. onDisappear: () => {
      30. this.isShowImage = false;
      31. this.isShowSheet = false;
      32. this.isAnimating = false;
      33. this.isEnabled = true;
      34. }
      35. })
      36. .bindContentCover(this.isShowOverlay, this.overlayNode(), {
      37. transition: TransitionEffect.IDENTITY
      38. })
      39. }
      40. .backgroundColor('#F1F3F5')
      41. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.BOTTOM])
      42. .title('half mode')
    3. 点击首页图片后将图片节点迁移至半模态,当半模态完成布局之后,触发onLayoutComplete()函数,获取到图片初始位置和半模态位置,通过自定义显示动画完成一镜到底的效果。

      收起
      自动换行
      深色代码主题
      复制
      1. aboutToAppear(): void {
      2. let onLayoutComplete: () => void = (): void => {
      3. this.targetInfo = this.calculateData('target');
      4. if (this.targetInfo.scale !== 0 && this.targetInfo.clipWidth !== 0 && this.targetInfo.clipHeight !== 0 &&
      5. !this.isAnimating) {
      6. this.isAnimating = true;
      7. this.getUIContext().animateTo({
      8. duration: 1000,
      9. curve: Curve.Friction,
      10. onFinish: () => {
      11. this.isShowOverlay = false;
      12. this.isShowImage = true;
      13. }
      14. }, () => {
      15. this.scaleValue = AppStorage.get('currentBreakpoint') === 'md' ? 0.382 : this.targetInfo.scale;
      16. this.translateX = AppStorage.get('currentBreakpoint') === 'md' ? 93.5 : this.targetInfo.translateX;
      17. this.clipWidth = AppStorage.get('currentBreakpoint') === 'md' ? 525 : this.targetInfo.clipWidth;
      18. this.clipHeight = AppStorage.get('currentBreakpoint') === 'md' ? 785 : this.targetInfo.clipHeight;
      19. this.translateY = this.targetInfo.translateY +
      20. (this.getUIContext().px2vp(WindowUtils.windowHeight_px) - this.bindSheetHeight -
      21. this.getUIContext().px2vp(WindowUtils.navigationIndicatorHeight_px) -
      22. this.getUIContext().px2vp(WindowUtils.topAvoidAreaHeight_px)) -
      23. (AppStorage.get('currentBreakpoint') === 'md' ? 134.3 : 0);
      24. this.radius = this.sheetRadius / this.scaleValue;
      25. })
      26. this.getUIContext().animateTo({
      27. duration: 2000,
      28. curve: Curve.Friction,
      29. }, () => {
      30. this.opacityDegree = 1;
      31. })
      32. }
      33. };
      34. this.listener.on('layout', onLayoutComplete);
      35. }

图标(搜索框、头像等)展开一镜到底

搜索框点击后,转场到搜索结果页面。

将搜索框首页与搜索框页面的Search组件同时设置geometryTransition属性,并绑定同一id值。设置显式动画和transition属性的转场效果,实现搜索框的一镜到底效果。

  1. 搜索框首页在Search组件添加geometryTransition属性,并绑定id值,禁用掉Navigation本身转场的动画。

    收起
    自动换行
    深色代码主题
    复制
    1. private showSearchPage(): void {
    2. this.transitionEffect = TransitionEffect.OPACITY;
    3. this.getUIContext().animateTo({
    4. curve: curves.interpolatingSpring(0, 1, 342, 38)
    5. }, () => {
    6. this.pageInfos.pushPath({ name: 'SearchLongTakeTransitionPageTwo' }, false);
    7. })
    8. }
  2. 搜索页面中的Search组件添加geometryTransition(),并添加与搜索框首页中的同一id值。

    收起
    自动换行
    深色代码主题
    复制
    1. Search({ placeholder: 'Search' })
    2. .height(40)
    3. .placeholderColor($r('sys.color.mask_secondary'))
    4. .width('100%')
    5. .geometryTransition('SEARCH_ONE_SHOT_DEMO_TRANSITION_ID', { follow: true })
    6. .backgroundColor('#0D000000')
    7. .defaultFocus(false)
    8. .focusOnTouch(false)
    9. .focusable(false)

容器转场案例

卡片、列表展开一镜到底

在瀑布流或列表流布局中,当用户点击其中一个卡片或列表项时,应用将执行平滑的转场动画,引导用户从概览页面切换到详情页面。

使用WaterFlow()和LazyForEach()实现卡片列表瀑布流。利用Navigation的自定义导航转场动画能力,通过customNavContentTransition()配置列表页与详情页的自定义导航转场动画,结合componentSnapshot()将卡片进行截图避免跳转页面白屏。

  1. 卡片列表页使用WaterFlow和LazyForEach实现页面布局。

    收起
    自动换行
    深色代码主题
    复制
    1. private onColumnClicked(indexValue: string): void {
    2. let param: Record<string, Object> = {};
    3. let clickedIndex = parseInt(indexValue);
    4. param['indexValue'] = clickedIndex;
    5. this.clickedIndex = clickedIndex;
    6. this.getUIContext()
    7. .getComponentSnapshot()
    8. .get('FlowItem_' + indexValue, (error: BusinessError, pixelMap: image.PixelMap) => {
    9. if (error) {
    10. hilog.error(0x0000, 'CardLongTakePageOne',
    11. `componentSnapshot.get error, reason: Code is ${error.code}, message is ${error.message}`);
    12. this.pageInfos.pushPath({ name: 'CardLongTakeTransitionPageTwo', param: param });
    13. return;
    14. } else {
    15. hilog.info(0x0000, 'CardLongTakePageOne', 'componentSnapshot.get success!');
    16. param['clickedComponentId'] = CardUtil.getFlowItemIdByIndex(indexValue);
    17. param['doDefaultTransition'] = () => {
    18. this.doFinishTransition();
    19. };
    20. SnapShotImage.pixelMap = pixelMap;
    21. this.pageInfos.pushPath({ name: 'CardLongTakeTransitionPageTwo', param: param });
    22. this.dataSource.getData(this.clickedIndex).isVisible = Visibility.Hidden;
    23. }
    24. })
    25. }
  2. 卡片详情页通过Navigation自定义动画实现一镜到底。这里套了两层Stack(),因为要放截图,以及把原来的详情页内容转移过来。缩放、translate属性设置在Stack()这层上实现边界动画,透明度属性设置在截图上实现内容过渡。在onReady()里面注册自定义动画,通过id对动画属性进行初始化。

    收起
    自动换行
    深色代码主题
    复制
    1. tryRegisterCustomTransition(clickedCardId: string): void {
    2. try {
    3. this.longTakeAnimationProperties.init(clickedCardId, this.prePageDoFinishTransition);
    4. CustomTransition.getInstance().registerNavParam(this.pageId, 2000,
    5. (transitionProxy: NavigationTransitionProxy) => {
    6. this.longTakeAnimationProperties.doAnimation(transitionProxy);
    7. });
    8. hilog.info(0x0000, 'CardLongTakePageTwo', 'register successes');
    9. } catch (error) {
    10. let err = error as BusinessError;
    11. hilog.error(0x0000, 'CardLongTakePageTwo', `this is error:code=${err.code}, message=${err.message}`);
    12. this.longTakeAnimationProperties.setFinalStatus();
    13. }
    14. }
    15. // ...
    16. build() {
    17. NavDestination() {
    18. Stack({ alignContent: Alignment.TopStart }) {
    19. Stack({ alignContent: Alignment.TopStart }) {
    20. Image(this.snapShotImage)
    21. .size(this.longTakeAnimationProperties.snapShotSize)
    22. .objectFit(ImageFit.Auto)
    23. .opacity(this.longTakeAnimationProperties.snapShotOpacity)
    24. .syncLoad(true)
    25. .position({
    26. x: this.longTakeAnimationProperties.snapShotPositionX,
    27. y: this.longTakeAnimationProperties.snapShotPositionY
    28. })
    29. DetailPageContent({
    30. indexValue: this.indexValue,
    31. pageInfos: this.pageInfos,
    32. onBackPressed: () => {
    33. this.onBackPressed()
    34. },
    35. SharedComponentId: CardUtil.getPostPageImageId(this.clickedCardId)
    36. })
    37. .size({
    38. width: '100%',
    39. height: '100%'
    40. })
    41. .opacity(this.longTakeAnimationProperties.postPageOpacity)
    42. }
    43. .width('100%')
    44. .position({
    45. x: this.longTakeAnimationProperties.positionXValue,
    46. y: this.longTakeAnimationProperties.positionYValue
    47. })
    48. }
    49. .scale({
    50. x: this.longTakeAnimationProperties.scaleValue,
    51. y: this.longTakeAnimationProperties.scaleValue
    52. })
    53. .translate({
    54. x: this.longTakeAnimationProperties.translateX,
    55. y: this.longTakeAnimationProperties.translateY
    56. })
    57. .width(this.longTakeAnimationProperties.clipWidth)
    58. .height(this.longTakeAnimationProperties.clipHeight)
    59. .borderRadius(this.longTakeAnimationProperties.radius)
    60. .expandSafeArea([SafeAreaType.SYSTEM])
    61. .backgroundColor($r('app.color.water_flow_background_color'))
    62. .clip(true)
    63. }
    64. .backgroundColor(this.longTakeAnimationProperties.navDestinationBgColor)
    65. .GestureStyles()
    66. .hideTitleBar(true)
    67. .onReady((context: NavDestinationContext) => {
    68. this.pageInfos = context.pathStack;
    69. let param = context.pathInfo?.param as Record<string, Object>;
    70. let clickedCardId = param['clickedComponentId'] as string;
    71. this.indexValue = param['indexValue'] as number;
    72. this.prePageDoFinishTransition = param['doDefaultTransition'] as () => void;
    73. if (context.navDestinationId && clickedCardId) {
    74. this.pageId = context.navDestinationId;
    75. this.clickedCardId = clickedCardId;
    76. this.tryRegisterCustomTransition(clickedCardId);
    77. }
    78. })
    79. .onBackPressed(() => {
    80. return this.onBackPressed();
    81. })
    82. .onDisAppear(() => {
    83. CustomTransition.getInstance().unRegisterNavParam(this.pageId);
    84. })
    85. }
    86. // ...

列表一镜到底效果图。

将列表项与详情页面同时设置geometryTransition属性,并绑定同一id值。每个列表项设置显式动画和transition属性的转场效果,实现列表展开的一镜到底效果。

  1. 列表页面中每一个列表项设置geometryTransition属性,并绑定当前列表的id值。

    收起
    自动换行
    深色代码主题
    复制
    1. @Component
    2. export struct MyButton {
    3. @Prop listContent: ListContent;
    4. @Prop indexValue: string;
    5. @State scaleValue: number = 1;
    6. build() {
    7. Column({ space: 10 }) {
    8. Row({ space: 5 }) {
    9. Line()
    10. .startPoint([0, 0])
    11. .endPoint([0, 20])
    12. .strokeWidth(5)
    13. .stroke(Color.Yellow)
    14. .strokeLineCap(LineCapStyle.Round)
    15. Text(this.listContent.title)
    16. .fontWeight(FontWeight.Medium)
    17. .fontSize(16)
    18. }
    19. Text(this.listContent.content)
    20. .fontColor(Color.Grey)
    21. .maxLines(1)
    22. .textOverflow({ overflow: TextOverflow.Ellipsis })
    23. .fontSize(14)
    24. }
    25. .alignItems(HorizontalAlign.Start)
    26. .padding({
    27. left: 20,
    28. right: 20,
    29. top: 20,
    30. bottom: 20
    31. })
    32. .width('91%')
    33. .backgroundColor(Color.White)
    34. .clip(true)
    35. .borderRadius(20)
    36. .scale({
    37. x: this.scaleValue,
    38. y: this.scaleValue
    39. })
    40. .geometryTransition(this.indexValue, { follow: true })
    41. .onTouch((event?: TouchEvent) => {
    42. this.onTouchProcess(event);
    43. })
    44. .onClick(() => {
    45. this.onButtonClicked?.(this.indexValue);
    46. })
    47. }
    48. onButtonClicked: (index: string) => void = (_index: string) => {
    49. };
    50. private onTouchProcess(event?: TouchEvent): void {
    51. if (!event) {
    52. return;
    53. }
    54. if (event.type === TouchType.Down) {
    55. this.getUIContext().animateTo({ curve: curves.interpolatingSpring(0, 1, 350, 35) }, () => {
    56. this.scaleValue = 0.95;
    57. })
    58. } else if (event.type === TouchType.Up) {
    59. this.getUIContext().animateTo({ curve: curves.interpolatingSpring(0, 1, 350, 35) }, () => {
    60. this.scaleValue = 1;
    61. })
    62. } else if (event.type === TouchType.Cancel) {
    63. this.getUIContext().animateTo({ curve: curves.interpolatingSpring(0, 1, 350, 35) }, () => {
    64. this.scaleValue = 1;
    65. })
    66. }
    67. }
    68. }
  2. 列表详情页中的容器组件Column组件设置geometryTransition属性,并绑定对应列表项的id值,完成一镜到底效果。

    收起
    自动换行
    深色代码主题
    复制
    1. NavDestination() {
    2. Column({ space: 20 }) {
    3. Text(this.param.title)
    4. .fontSize(30)
    5. .fontWeight(FontWeight.Medium)
    6. Text(this.param.content)
    7. .fontColor($r('sys.color.password_icon_focus_color'))
    8. .lineHeight(28)
    9. .fontSize(16)
    10. }
    11. .alignItems(HorizontalAlign.Start)
    12. .clip(true)
    13. .size({
    14. width: '100%',
    15. height: '100%'
    16. })
    17. .geometryTransition(this.param.geometryId)
    18. }
    19. .padding({
    20. top: 46,
    21. left: 16,
    22. right: 16
    23. })
    24. .backgroundColor(Constants.DEFAULT_BG_COLOR)
    25. .transition(TransitionEffect.OPACITY)
    26. .hideTitleBar(true)
    27. .backgroundColor(Color.Transparent)
    28. .onReady((context: NavDestinationContext) => {
    29. this.pageInfos = context.pathStack;
    30. this.param = (context.pathInfo.param as ListDetailPageExtraInfo);
    31. })
    32. .onBackPressed(() => {
    33. this.getUIContext().animateTo({ curve: curves.interpolatingSpring(0, 1, 342, 38) }, () => {
    34. this.pageInfos.pop(false);
    35. })
    36. return true;
    37. })

“图书”翻页展开一镜到底

阅读类应用中,点击一本“图书”的图标后,模拟图书翻页展开的效果,转场到书本内容页面,同时支持手势返回。

利用Navigation的自定义导航转场动画能力,通过customNavContentTransition()配置书籍页与详情页的自定义导航转场动画实现图书翻页一镜到底效果。使用rotate属性实现书籍翻页的旋转效果。

  1. 书架页面通过Grid组件实现书架第一行书籍布局,使用Swiper()组件实现书架第一行书籍布局。

    收起
    自动换行
    深色代码主题
    复制
    1. build() {
    2. NavDestination() {
    3. Scroll() {
    4. Column({ space: 12 }) {
    5. Grid() {
    6. ForEach(this.dataSource, (item: BookItem, index: number) => {
    7. GridItem() {
    8. Image($r(item.coverImageUrl))
    9. .id(item.id)
    10. .width('100%')
    11. .onClick(() => {
    12. this.onColumnClicked(item.id, item.coverImageUrl, this.dataSource[0].id, () => {
    13. this.dataSource.sort((a, b) => b.timestamp - a.timestamp);
    14. })
    15. this.dataSource[index].timestamp = Number(new Date());
    16. })
    17. }
    18. .width(this.columnWidth)
    19. }, (item: BookItem) => JSON.stringify(item))
    20. }
    21. .padding({
    22. left: 12,
    23. right: 12,
    24. top: 12
    25. })
    26. .columnsTemplate(this.columnType)
    27. .columnsGap(10)
    28. .rowsGap(10)
    29. Column({ space: 12 }) {
    30. Text('Recently read')
    31. .fontSize(16)
    32. .fontWeight(FontWeight.Medium)
    33. .fontColor(Color.Gray)
    34. Swiper(this.swiperController) {
    35. ForEach(this.recentData, (item: BookItem) => {
    36. GridItem() {
    37. Image($r(item.coverImageUrl))
    38. .id(item.id)
    39. .onClick(() => {
    40. this.onColumnClicked(item.id, item.coverImageUrl);
    41. })
    42. }
    43. }, (item: BookItem) => JSON.stringify(item))
    44. }
    45. .indicator(false)
    46. .displayCount(3)
    47. .loop(false)
    48. .itemSpace(10)
    49. }
    50. .padding({
    51. left: 12,
    52. right: 12
    53. })
    54. .alignItems(HorizontalAlign.Start)
    55. }
    56. }
    57. }
    58. // ...
    59. }
    60. // ...
    61. private onColumnClicked(bookId: string, bookCoverUrl: string, toBookId?: string, prePageCallback?: () => void): void {
    62. try {
    63. CustomTransition.getInstance().unRegisterNavParam(this.pageId);
    64. const fromCardItemInfo: RectInfoInPx =
    65. ComponentAttrUtils.getRectInfoById(WindowUtils.window.getUIContext(), bookId);
    66. let param: Record<string, Object> = {};
    67. param['fromCardItemInfo'] = fromCardItemInfo;
    68. param['bookCoverUrl'] = bookCoverUrl;
    69. if (toBookId) {
    70. const toCardItemInfo: RectInfoInPx =
    71. ComponentAttrUtils.getRectInfoById(WindowUtils.window.getUIContext(), toBookId);
    72. param['toCardItemInfo'] = toCardItemInfo;
    73. }
    74. if (prePageCallback) {
    75. param['prePageCallback'] = prePageCallback;
    76. }
    77. this.pageInfos.pushPath({ name: 'BookFlipLongTakeTransitionPageTwo', param: param });
    78. } catch (err) {
    79. let error = err as BusinessError;
    80. hilog.error(0x0000, 'BookFlipLongTakeTransitionPageOne',
    81. `onColumnClicked failed. error code=${error.code}, message=${error.message}`);
    82. }
    83. }
  2. 书籍详情页通过Navigation自定义动画实现一镜到底。

    收起
    自动换行
    深色代码主题
    复制
    1. NavDestination() {
    2. Stack() {
    3. Column() {
    4. Text($r('app.string.DetailPage_text'))
    5. .fontColor($r('sys.color.password_icon_focus_color'))
    6. .lineHeight(28)
    7. .fontSize(16)
    8. }
    9. .width(AppStorage.get('currentBreakpoint') === 'md' ? '75%' : '100%')
    10. .height('100%')
    11. .alignItems(HorizontalAlign.Start)
    12. .padding({
    13. left: 16,
    14. right: 16,
    15. top: 46
    16. })
    17. if (!this.doDefaultTransition) {
    18. Image($r(this.bookCoverUrl))
    19. .objectFit(ImageFit.Cover)
    20. .syncLoad(true)
    21. .rotate({
    22. x: 0,
    23. y: 1,
    24. z: 0,
    25. angle: this.bookFlipLongTakeTransitionProperties.coverRotateAngle,
    26. centerX: 0,
    27. centerY: '50%'
    28. })
    29. .scale({
    30. x: this.bookFlipLongTakeTransitionProperties.coverScale,
    31. centerX: 0,
    32. centerY: '50%'
    33. })
    34. }
    35. }
    36. .scale({
    37. x: this.bookFlipLongTakeTransitionProperties.scaleValue,
    38. y: this.bookFlipLongTakeTransitionProperties.scaleValue
    39. })
    40. .translate({
    41. x: this.bookFlipLongTakeTransitionProperties.translateX,
    42. y: this.bookFlipLongTakeTransitionProperties.translateY
    43. })
    44. .width(this.bookFlipLongTakeTransitionProperties.clipWidth)
    45. .height(this.bookFlipLongTakeTransitionProperties.clipHeight)
    46. .backgroundColor('#DEDFDF')
    47. }
    48. .backgroundColor(this.bookFlipLongTakeTransitionProperties.navDestinationBgColor)
    49. .GestureStyles()
    50. .hideTitleBar(true)
    51. .onReady((context: NavDestinationContext) => {
    52. this.pageInfos = context.pathStack;
    53. let param = context.pathInfo?.param as Record<string, Object>;
    54. this.bookCoverUrl = param['bookCoverUrl'] as string;
    55. this.fromCardItemInfo = param['fromCardItemInfo'] as RectInfoInPx;
    56. this.toCardItemInfo = (param['toCardItemInfo'] || param['fromCardItemInfo']) as RectInfoInPx;
    57. this.prePageCallback = param['prePageCallback'] as () => void;
    58. if (context.navDestinationId) {
    59. this.pageId = context.navDestinationId;
    60. }
    61. CustomTransition.getInstance()
    62. .registerNavParam(this.pageId, 500, (transitionProxy: NavigationTransitionProxy) => {
    63. this.bookFlipLongTakeTransitionProperties.doAnimation(transitionProxy, this.fromCardItemInfo,
    64. this.toCardItemInfo);
    65. }, () => {
    66. this.bookFlipLongTakeTransitionProperties.onInteractiveFinish();
    67. }, () => {
    68. this.bookFlipLongTakeTransitionProperties.onInteractive(
    69. this.fromCardItemInfo, this.toCardItemInfo);
    70. });
    71. })
    72. .onBackPressed(() => {
    73. return this.onBackPressed();
    74. })
    75. .onDisAppear(() => {
    76. CustomTransition.getInstance().unRegisterNavParam(this.pageId);
    77. })

视频展开一镜到底

视频组件从一个页面向目标页面的转场,在一镜到底的过程中,视频需要持续播放。

使用WaterFlow()和LazyForEach()实现卡片列表瀑布流。利用NodeController实现组件的跨节点迁移,通过customNavContentTransition配置概览页与视频详情的自定义导航转场动画,给节点的迁移过程赋予一镜到底效果。

  1. 创建NodeController节点类。

    收起
    自动换行
    深色代码主题
    复制
    1. export class MyNodeController extends NodeController {
    2. // ...
    3. }
  2. 视频首页使用WaterFlow()和LazyForEach()实现页面布局,点击视频后将视频节点迁移至视频播放页面,通过Navigation自定义动画完成一镜到底的效果。

    收起
    自动换行
    深色代码主题
    复制
    1. NavDestination() {
    2. WaterFlow() {
    3. LazyForEach(this.dataSource, (_: CardAttr, index: number) => {
    4. FlowItem() {
    5. VideoCardComponent({
    6. isPlaying: false,
    7. index,
    8. onColumnClicked: (prePageCallback) => {
    9. this.onColumnClicked(`xComponent_${index}`, prePageCallback)
    10. }
    11. })
    12. }
    13. .width('100%')
    14. .borderRadius(10)
    15. .clip(true)
    16. .id('FlowItem_' + index.toString())
    17. }, (item: string) => item)
    18. }
    19. .edgeEffect(EdgeEffect.Spring)
    20. .onScrollIndex((first: number) => {
    21. this.scrollFirstIndex = first;
    22. })
    23. .padding(12)
    24. .columnsTemplate(this.columnType)
    25. .columnsGap(12)
    26. .rowsGap(10)
    27. .width('100%')
    28. .height('100%')
    29. }
    30. .backgroundColor(Constants.DEFAULT_BG_COLOR)
    31. .title(getResourceString(this.getUIContext(), $r('app.string.video_title'), this))
    32. .onReady((context: NavDestinationContext) => {
    33. this.pageInfos = context.pathStack;
    34. if (context.navDestinationId) {
    35. this.pageId = context.navDestinationId;
    36. }
    37. })
    38. .onDisAppear(() => {
    39. CustomTransition.getInstance().unRegisterNavParam(this.pageId);
    40. })
在 开发与测试 开放能力API 中进行搜索
请输入您想要搜索的关键词