我正在使用Objective-C开发适用于iOS 7的应用程序。我的应用程序中有一个带有几个按钮和漂亮背景图像的屏幕。(这是一个简单的xib,UIButtons位于顶部UIImageView。)
UIButtons
UIImageView
我在想,如果这些按钮具有iOS 7主屏幕具有的视差效果,那就太酷了,因此,如果倾斜手机,您会看到背景。
如何在自己的应用中实现这种效果?
在iOS 7中,Apple引入UIMotionEffect了添加与用户设备方向相关的Motion效果。例如,要在主屏幕上模拟视差效果,可以使用子类UIInterpolationMotionEffect(如此处和此处所述),只需几行代码。
UIMotionEffect
UIInterpolationMotionEffect
目标-C :
// Set vertical effect UIInterpolatingMotionEffect *verticalMotionEffect = [[UIInterpolatingMotionEffect alloc] initWithKeyPath:@"center.y" type:UIInterpolatingMotionEffectTypeTiltAlongVerticalAxis]; verticalMotionEffect.minimumRelativeValue = @(-10); verticalMotionEffect.maximumRelativeValue = @(10); // Set horizontal effect UIInterpolatingMotionEffect *horizontalMotionEffect = [[UIInterpolatingMotionEffect alloc] initWithKeyPath:@"center.x" type:UIInterpolatingMotionEffectTypeTiltAlongHorizontalAxis]; horizontalMotionEffect.minimumRelativeValue = @(-10); horizontalMotionEffect.maximumRelativeValue = @(10); // Create group to combine both UIMotionEffectGroup *group = [UIMotionEffectGroup new]; group.motionEffects = @[horizontalMotionEffect, verticalMotionEffect]; // Add both effects to your view [myBackgroundView addMotionEffect:group];
斯威夫特 (感谢@Lucas):
// Set vertical effect let verticalMotionEffect = UIInterpolatingMotionEffect(keyPath: "center.y", type: .TiltAlongVerticalAxis) verticalMotionEffect.minimumRelativeValue = -10 verticalMotionEffect.maximumRelativeValue = 10 // Set horizontal effect let horizontalMotionEffect = UIInterpolatingMotionEffect(keyPath: "center.x", type: .TiltAlongHorizontalAxis) horizontalMotionEffect.minimumRelativeValue = -10 horizontalMotionEffect.maximumRelativeValue = 10 // Create group to combine both let group = UIMotionEffectGroup() group.motionEffects = [horizontalMotionEffect, verticalMotionEffect] // Add both effects to your view myBackgroundView.addMotionEffect(group)
此外,您可以找到一堆库来简化此操作或将此功能添加到较旧的iOS版本: