2014-10-17 40 views
4

我想實現與「真正的運動背景」開始頁面相同的行爲。當您傾斜手機時,背景圖片稍稍移動一點,使其看起來像3D和「真實」。如何在swift中實現動態背景圖像

這是我想在我的應用程序的開始頁面。

我該如何做到這一點?

回答

6

請參閱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軸傾斜時,圖像會上下移動。

from developer.apple.com/library/ios/documentation/EventHandling/Conceptual/EventHandlingiPhoneOS/motion_event_basics/motion_event_basics.html#//apple_ref/doc/uid/TP40009541-CH6-SW14 (圖像從Event Handling Guide for iOS獲得。)

+0

看起來不錯。當用戶傾斜iPhone時,是否有可能將此與傳感結合起來?向右傾斜並將圖像向左移動,反之亦然。 – SGoldwin 2014-10-23 18:51:39

+0

我不跟着你。使用上面的代碼,當您將設備左右傾斜y軸時,圖像將分別向左和向右移動。 (它將x軸的旋轉結合起來,導致圖像上下移動,當用戶將設備移動到手中時,完成了一定深度的幻覺。) – Rob 2014-10-23 19:21:01

+0

對不起。我的錯。我確實讀過它。我一定會嘗試這個。謝謝! – SGoldwin 2014-10-24 21:00:35