我正在用Objective-C为iOS7开发一个应用程序.我的应用程序里有一个屏幕,上面有几个按钮和漂亮的背景图片.(这是一个简单的XIB,在UIImageView
的基础上再加上UIButtons
.)
我在想,如果这些按钮具有iOS 7主屏幕所具有的视差效果,那就太酷了,所以如果你倾斜手机,你可以看到背景.
我怎样才能在我自己的应用程序中实现这种效果呢?
我正在用Objective-C为iOS7开发一个应用程序.我的应用程序里有一个屏幕,上面有几个按钮和漂亮的背景图片.(这是一个简单的XIB,在UIImageView
的基础上再加上UIButtons
.)
我在想,如果这些按钮具有iOS 7主屏幕所具有的视差效果,那就太酷了,所以如果你倾斜手机,你可以看到背景.
我怎样才能在我自己的应用程序中实现这种效果呢?
在iOS7中,苹果引入了UIMotionEffect
来添加与用户设备方向相关的运动效果.例如,要在主屏幕上模拟视差效果,您可以使用子类UIInterpolatingMotionEffect
,如所解释的here,只需几行代码.
Objective-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];
Swift(感谢@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版本: