温馨提示:本篇博客的详细代码已发布到 git : https://gitcode.com/nutpi/HarmonyosNext 可以下载运行哦!
.gesture(
GestureGroup(
GestureMode.Exclusive, // 手势互斥模式
TapGesture({ count: 2 }), // 双击
TapGesture({ count: 1 }), // 单击
PinchGesture({ fingers: 2 }), // 双指捏合
PanGesture({ fingers: 1 }) // 单指滑动
)
)
TapGesture({ count: 2 })
.onAction(() => {
if (this.imageScaleInfo.scaleValue > 默认值) {
// 缩小逻辑
fn = () => {
this.isEnableSwipe = true; // 启用滑动切换
this.imageScaleInfo.reset(); // 重置缩放
this.matrix = matrix4.identity(); // 重置变换矩阵
};
} else {
// 放大逻辑
fn = () => {
this.isEnableSwipe = false; // 禁用滑动切换
const ratio = this.calcFitScaleRatio(...); // 计算适配比例
this.matrix = matrix4.identity().scale({x: ratio, y: ratio});
};
}
runWithAnimation(fn); // 带动画执行
})
calcFitScaleRatio
:计算填满屏幕所需比例runWithAnimation
:HarmonyOS动画API,实现平滑过渡PinchGesture({ fingers: 2 })
.onActionUpdate((event) => {
// 实时计算缩放比例
this.imageScaleInfo.scaleValue = 上次值 * event.scale;
// 边界限制
const maxScale = 最大缩放值 * 1.3; // 允许超出20%的弹性效果
const minScale = 默认值 * 0.7; // 允许缩小到70%
this.imageScaleInfo.scaleValue = Math.min(maxScale,
Math.max(minScale, this.imageScaleInfo.scaleValue));
// 应用矩阵变换
this.matrix = matrix4.identity().scale({
x: 当前比例,
y: 当前比例
});
})
.onActionEnd(() => {
// 弹性回弹处理
if (当前比例 < 默认值) {
runWithAnimation(() => 重置到默认值);
} else if (当前比例 > 最大缩放值) {
runWithAnimation(() => 调整到最大值);
}
})
event.scale
:捏合手势的实时缩放系数(>1放大,<1缩小)lastValue
:记录上次缩放值,保证连续性PanGesture({ fingers: 1 })
.onActionUpdate((event) => {
if (当前是默认缩放比例) return; // 默认状态禁止滑动
// 计算新偏移量
this.imageOffsetInfo.currentX = 上次X + event.offsetX;
this.imageOffsetInfo.currentY = 上次Y + event.offsetY;
})
.onActionEnd(() => {
// 保存当前偏移量
this.imageOffsetInfo.stash();
})
offsetX/Y
:手势相对于起点的位移量runWithAnimation(() => {
// 状态变更操作
this.imageScaleInfo.scaleValue = 目标值;
this.matrix = 新矩阵;
});
动画原理:
runWithAnimation
中的状态变更会自动应用动画自定义动画:
runWithAnimation(() => {
// 操作
}, {
duration: 300, // 动画时长
curve: Curve.EaseInOut // 缓动曲线
})
matrix4.identity() // 创建单位矩阵
.scale({ x: 2, y: 2 }) // 缩放变换
.translate({ x: 100, y: 50 }) // 位移变换
.copy(); // 创建新实例