如何在Swift中实现动态背景图片

7

我希望能够实现与“真实移动背景”启动页面相同的行为。当您倾斜手机时,背景图像会稍微移动,使其看起来具有3D和“真实”的效果。

这就是我想在我的应用程序启动页面中实现的效果。

我该如何制作呢?

2个回答

10

请查看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轴倾斜时,图像将上下移动。

来自 developer.apple.com/library/ios/documentation/EventHandling/Conceptual/EventHandlingiPhoneOS/motion_event_basics/motion_event_basics.html#//apple_ref/doc/uid/TP40009541-CH6-SW14 (图片来源于iOS事件处理指南


看起来很不错。是否可以将其与用户倾斜iPhone时的传感器结合使用?向右倾斜并将图像向左移动,反之亦然。 - SGoldwin
我不明白你的意思。通过上述代码,当你左右倾斜设备时,图像将分别向右和向左移动。 (它还结合了绕x轴的旋转,导致图像上下移动,从而完成用户在手中移动设备时产生深度错觉的效果。) - Rob
抱歉,是我不好。我确实已经仔细阅读了。我一定会尝试这个方法的。谢谢! - SGoldwin

1

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];

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接