2013年10月31日 星期四

視差效果 (Parallax effect)

注意:以下教學只支援 iOS7 以上的 SDK!!

iOS 7 的特點除了毛玻璃效果之外還有另一個,就是視差效果 (Parallax effect),
這個功能比起毛玻璃效果效果使用起來簡單許多了,因為官方供提供這個 Class 給你使用,
所以可以自由的加在你想要套用這個效果的 View 上面了,以下就是這個效果的教學。

首先在你的 UIViewController 裡面建立一個 UIView,這個 UIView 的大小可以隨你喜歡,只要將它 addsubView: 上去就好了,
假設這個 UIView 叫做 viewA 好了,以下教學就用它做範例:
- (void)viewDidLoad
{
	[super viewDidLoad];
	
	// 首先先建立一個 X 軸的可偏移範圍,本教學就用 +30 到 -30 之間
	UIInterpolatingMotionEffect *xAxis = [[UIInterpolatingMotionEffect alloc] initWithKeyPath:@"center.x" type:UIInterpolatingMotionEffectTypeTiltAlongHorizontalAxis];
	[xAxis setMinimumRelativeValue:@(-30.0f)];
	[xAxis setMaximumRelativeValue:@(30.0f)];
	
	// 同樣,也建立一個 Y 軸的可偏移範圍,也是用 +30 到 -30 之間
	UIInterpolatingMotionEffect *yAxis = [[UIInterpolatingMotionEffect alloc] initWithKeyPath:@"center.y" type:UIInterpolatingMotionEffectTypeTiltAlongVerticalAxis];
	[yAxis setMinimumRelativeValue:@(-30.0f)];
	[yAxis setMaximumRelativeValue:@(30.0f)];
	
	// 建立一個群組將 X 軸與 Y 軸的可偏移範圍包起來
	UIMotionEffectGroup *motionEffect = [UIMotionEffectGroup new];
	[motionEffect setMotionEffects:@[xAxis, yAxis]];
	
	// 把 viewA 建立起來,並且加到 viewController 中
	UIView *viewA = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 200.0f, 200.0f)];
	[viewA setBackgroundColor:[UIColor whiteColor]];
	[viewA setCenter:self.view.center];
	
	[self.view addSubview:viewA];
	
	// 之後將這個視差效果加入到 viewA 中
	[viewA setMotionEffects:@[motionEffect]];
	
	// 用完後將它們釋放掉
	[xAxis release];
	[yAxis release];
	
	[motionEffect release];
	[viewA release];
}

這樣子執行就可以用了,只不過這在模擬器視沒有效果的,所以只能在實機上面使用,
所以這次就沒有畫面了。

本次的教學就到這邊,大家下次再見了。