运动效果Motion Effects:当设备上下左右倾斜会产生视差效果。在iOS7之后,UIInterpolatingMotionEffect提供了这样的功能
先看效果:
请忽略右下角的水印、渣图像、黑边、以及小灰球按钮
开始敲代码
-
新建工程,设置方向
-
在SB中添加两个ImageView,分别为背景和仙女儿
- 代码
#import "ViewController.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *back;
@property (weak, nonatomic) IBOutlet UIImageView *fairy;
@end
@implementation ViewController
-(void)viewDidLoad {
[super viewDidLoad];
[[UIApplication sharedApplication] setStatusBarHidden:YES];
// 设置仙女的运动效果 ===== BEGIN =====
// 设置在x轴的偏移范围
UIInterpolatingMotionEffect * fairyEffX = [[UIInterpolatingMotionEffect alloc] initWithKeyPath:@"center.x" type:UIInterpolatingMotionEffectTypeTiltAlongHorizontalAxis];// type表示沿水平方向运行效果
fairyEffX.maximumRelativeValue = @(50);
fairyEffX.minimumRelativeValue = @(-50);
// 为view添加运动效果
[self.fairy addMotionEffect:fairyEffX];
UIInterpolatingMotionEffect * fairyEffY = [[UIInterpolatingMotionEffect alloc] initWithKeyPath:@"center.y" type:UIInterpolatingMotionEffectTypeTiltAlongVerticalAxis];
fairyEffY.maximumRelativeValue = @(50);
fairyEffY.minimumRelativeValue = @(-50);
[self.fairy addMotionEffect:fairyEffY];
// 设置背景的运动效果 ===== BEGIN =====
UIInterpolatingMotionEffect * backEffX = [[UIInterpolatingMotionEffect alloc] initWithKeyPath:@"center.x" type:UIInterpolatingMotionEffectTypeTiltAlongHorizontalAxis];// type表示沿水平方向运行效果
backEffX.maximumRelativeValue = @(-100);
backEffX.minimumRelativeValue = @(100);
[self.back addMotionEffect:backEffX];
UIInterpolatingMotionEffect * backEffY = [[UIInterpolatingMotionEffect alloc] initWithKeyPath:@"center.y" type:UIInterpolatingMotionEffectTypeTiltAlongVerticalAxis];
backEffY.maximumRelativeValue = @(-100);
backEffY.minimumRelativeValue = @(100);
[self.back addMotionEffect:backEffY];
}
@end
- 真机测试
打开设置->通用->辅助功能->减弱动态效果->关闭
酱婶儿才可以看到效果
Demo在这里