Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement dynamic background image in swift

I would like to implement the same behaviour that the start page with "true motion backgrounds". When you tilt the phone the background image move a bit which makes it look 3D and "real".

This what I would like in my application start page.

How do I make this?

like image 356
SGoldwin Avatar asked Oct 17 '14 06:10

SGoldwin


1 Answers

See UIInterpolatingMotionEffect.

You can create one for each axis, create a group, and add the motion effect group to the UIImageView in the background.

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)

Thus, as you tilt it about the y-axis, the image will move left and right. As you tilt about the x-axis, the image will move up and down.

from developer.apple.com/library/ios/documentation/EventHandling/Conceptual/EventHandlingiPhoneOS/motion_event_basics/motion_event_basics.html#//apple_ref/doc/uid/TP40009541-CH6-SW14 (Image taken from the Event Handling Guide for iOS.)

like image 131
Rob Avatar answered Sep 28 '22 18:09

Rob