我想实现与“真实运动背景”的起始页面相同的行为。当您倾斜手机时,背景图像会移动一点,使其看起来像3D并且“真实”。
这就是我在申请开始页面中想要的内容。
我该怎么做?
答案 0 :(得分:6)
请参阅UIInterpolatingMotionEffect
。
您可以为每个轴创建一个,创建一个组,然后将动作效果组添加到后台的UIImageView
。
let horizontalMotionEffect = UIInterpolatingMotionEffect(keyPath: "center.x", type: .TiltAlongHorizontalAxis)
horizontalMotionEffect.minimumRelativeValue = -50
horizontalMotionEffect.maximumRelativeValue = 50
let verticalMotionEffect = UIInterpolatingMotionEffect(keyPath: "center.y", type: .TiltAlongVerticalAxis)
verticalMotionEffect.minimumRelativeValue = -50
verticalMotionEffect.maximumRelativeValue = 50
let motionEffectGroup = UIMotionEffectGroup()
motionEffectGroup.motionEffects = [horizontalMotionEffect, verticalMotionEffect]
imageView.addMotionEffect(motionEffectGroup)
因此,当您围绕y轴倾斜时,图像将左右移动。当您围绕x轴倾斜时,图像将上下移动。
(图片取自Event Handling Guide for iOS。)
答案 1 :(得分:0)
Objective-C (如果有人在2020年仍在使用Obj-C的话)
// Vertical effect
UIInterpolatingMotionEffect *verticalMotionEffect =
[[UIInterpolatingMotionEffect alloc]
initWithKeyPath:@"center.y"
type:UIInterpolatingMotionEffectTypeTiltAlongVerticalAxis];
verticalMotionEffect.minimumRelativeValue = @(-50);
verticalMotionEffect.maximumRelativeValue = @(50);
// horizontal effect
UIInterpolatingMotionEffect *horizontalMotionEffect =
[[UIInterpolatingMotionEffect alloc]
initWithKeyPath:@"center.x"
type:UIInterpolatingMotionEffectTypeTiltAlongHorizontalAxis];
horizontalMotionEffect.minimumRelativeValue = @(-50);
horizontalMotionEffect.maximumRelativeValue = @(50);
// Combine both effect
UIMotionEffectGroup *group = [UIMotionEffectGroup new];
group.motionEffects = @[horizontalMotionEffect, verticalMotionEffect];
// Add combine effects to your ImageView OR UIView
[yourImageView addMotionEffect:group];