一、背景
本篇是关于常见的交互实现,即Swiper左右滑动的伸缩效果
二、目标
点击查看
如上图所示,在滑动过程中,移走的缩小,移入的放大,同时展示相邻两项的一部分,这在app中也是一种很常见的交互。
三、实现步骤
在开始之前,我们可以先回顾一下原来Android中的实现;步骤也很简单,我们在ViewPage2外层设置可以突破边界,即:android:clipChildren=“false”, 然后PageTransformer来实现,滑动过程中的的动画;代码如下:
mBinding.vp2SquareChild.setPageTransformer(PetPageTransformer())
使用setPageTransformer给ViewPage2设置PageTransformer对象
class PetPageTransformer : ViewPager2.PageTransformer {
override fun transformPage(page: View, position: Float) {
page.setPadding(
page.context.resources.getDimension(R.dimen.d_6).toInt(),
0,
page.context.resources.getDimension(R.dimen.d_6).toInt(),
0
)
var scale = 0.0f
var alpha = 0.0f
if(position in 0.0f..1.0F) { //1
scale = 1.0f - (position * 0.1f)
alpha = 1.0f - (position * 0.5f)
}else if (-1.0f <= position && position < 0.0f){ //2
scale = (position * 0.1f) + 1.0f
alpha = (position * 0.5f) + 1.0f
}
page.scaleY = scale
page.alpha = alpha
}
}
PageTransformer内部做两件事:
●设置padding
加上前面的android:clipChildren=“false” ,实现相邻项的部分展示
●根据返回的position做动画处理
position为正数或负数表示相邻项的移动比例,根据这个比例换算出动画执行的属性值,且设置给view即可。
关于Android的实现就完成了,那鸿蒙上实现会不会类似呢,我觉得差不多,哈哈:
1、设置相邻项边距
我们需要相邻项展示部分内容的效果,如下图:
在鸿蒙中这个比较简单,只要给Swiper设置下面的属性即可:
.prevMargin(this.swiperMargin) // 漏出前一项的部分
.nextMargin(this.swiperMargin)// 漏出后一项的部分
2、设置相邻项的缩放动画
我们知道Android中是通过transformPage(page: View, position: Float) 函数回调来处理的,Swiper也有类似的函数,这就是:
.onGestureSwipe((index, event)
index我们可以理解,指当前展示的项,event是SwiperAnimationEvent:
declare interface SwiperAnimationEvent {
/**
* Offset of the current page to the start position of the swiper main axis. The unit is vp.
*
* @type { number }
* @default 0.0 vp
* @syscap SystemCapability.ArkUI.ArkUI.Full
* @since 10
*/
/**
* Offset of the current page to the start position of the swiper main axis. The unit is vp.
*
* @type { number }
* @default 0.0 vp
* @syscap SystemCapability.ArkUI.ArkUI.Full
* @crossplatform
* @atomicservice
* @since 11
*/
currentOffset: number;
/**
* Offset of the target page to the start position of the swiper main axis. The unit is vp.
*
* @type { number }
* @default 0.0 vp
* @syscap SystemCapability.ArkUI.ArkUI.Full
* @since 10
*/
/**
* Offset of the target page to the start position of the swiper main axis. The unit is vp.
*
* @type { number }
* @default 0.0 vp
* @syscap SystemCapability.ArkUI.ArkUI.Full
* @crossplatform
* @atomicservice
* @since 11