[iOS][Swift] パララックス(視差効果)を入れるサンプル

2016.07.01

この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。

パララックスとは、スクロールやデバイスを傾けたときに背景がずれるなどして、画面内に奥行きを表現する視差効果です。 今回はそんな視差効果をアプリ内に入れるサンプルです。

イメージ図

サンプル1

環境

今回の開発環境は下記で実施しています。

Xcode 7.3.1
Swift 2.2

ターゲットはiOS9.0、デバイスはiPhone、画面回転無しでProjectを作成しました。

準備

今回の例では通信は行わないので、画像をAssets.xcassetsに入れておきます。

実装

視差効果を出すにはUIInterpolatingMotionEffectを使います。
アプリの背景がデバイスを傾けると何か動く的な感じを目指します。

1. Storyboard上に配置する

まずはStoryboard上に部品を配置します。

Storyboard配置

背景にする場合はModeをAspect Fill にすると良いと思います。

画像をAspect Fillに

2. 動かす幅の分だけマイナスにする

動かしたい幅の分だけマイナス値にするのがポイントです。

動かす分だけ。。。

3. 対象のImageViewをOutlet接続する

imageViewに対してのエフェクトになるのでOutlet接続しましょう。

class ViewController: UIViewController {

    @IBOutlet weak var imageView: UIImageView!
	
    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

4. UIInterpolatingMotionEffectをつける

imageViewに対してエフェクトを適用します。

class ViewController: UIViewController {

    @IBOutlet weak var imageView: UIImageView!
	
    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        
        backGroundMotion()
    }

    private func backGroundMotion() {
        let min = -30.0
        let max = 30.0

        let xAxis = UIInterpolatingMotionEffect(keyPath: "center.x", type: .TiltAlongHorizontalAxis)
        xAxis.minimumRelativeValue = min
        xAxis.maximumRelativeValue = max

        let yAxis = UIInterpolatingMotionEffect(keyPath: "center.y", type: .TiltAlongVerticalAxis)
        yAxis.minimumRelativeValue = min
        yAxis.maximumRelativeValue = max

        let group = UIMotionEffectGroup()
        group.motionEffects = [xAxis, yAxis]

        imageView.addMotionEffect(group)
    }
}

let xAxis = UIInterpolatingMotionEffect(keyPath: "center.x", type: .TiltAlongHorizontalAxis) let yAxis = UIInterpolatingMotionEffect(keyPath: "center.y", type: .TiltAlongVerticalAxis) でそれぞれ縦横方向にエフェクトを定義します。

minimumRelativeValue maximumRelativeValue で動かす幅を定義します。
minimumRelativeValueの方は2. 動かす幅の分だけマイナスにするで設定した値を同じにしましょう。

UIMotionEffectGroupのgroup.motionEffects = [xAxis, yAxis]でそれぞれ縦横方向のエフェクトをグループ化し、
imageView.addMotionEffect(group) でimageViewに適用します。

動作イメージ

実機で試して見ると、端末の傾きで背景画像が動きます。
下記画像(右側)は傾けた状態でキャプチャを撮って重ねたものになります。背景画像のキリンの位置が動いているのがわかります。

結果イメージ

参考