How to achieve parallax effect with a sample image?

I am trying to achieve a parallax effect for an image. The code for the parallax effect is simple and only works if I add UIImage to UIImageView . I have an image of a pattern that needs to be sewn on both sides.

So I had to use the patternWithImage method of the UIColor . When I do this parallax, but I see the background color of self.view in the edges when I tilt the device.

Here is the code:

 - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. self.backgroundImageView.contentMode = UIViewContentModeCenter; self.backgroundImageView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"connect"]]; [self addParallaxEffectToView:self.backgroundImageView]; } - (void)addParallaxEffectToView:(UIView *)view { // Set vertical effect UIInterpolatingMotionEffect *verticalMotionEffect = [[UIInterpolatingMotionEffect alloc] initWithKeyPath:@"center.y" type:UIInterpolatingMotionEffectTypeTiltAlongVerticalAxis]; verticalMotionEffect.minimumRelativeValue = @(-50); verticalMotionEffect.maximumRelativeValue = @(50); // Set horizontal effect UIInterpolatingMotionEffect *horizontalMotionEffect = [[UIInterpolatingMotionEffect alloc] initWithKeyPath:@"center.x" type:UIInterpolatingMotionEffectTypeTiltAlongHorizontalAxis]; horizontalMotionEffect.minimumRelativeValue = @(-50); horizontalMotionEffect.maximumRelativeValue = @(50); // Create group to combine both UIMotionEffectGroup *group = [UIMotionEffectGroup new]; group.motionEffects = @[horizontalMotionEffect, verticalMotionEffect]; // Add both effects to your view [view addMotionEffect:group]; } 

The code can be in Swift or Objective-C. Any help would be greatly appreciated. Thanks

EDIT: As suggested by @Clafou, I get a weird look when I try to click and pop animations.

enter image description here

+5
source share
1 answer

I assume that your backgroundImageView should go beyond its container, since your effect will shift it.

As a quick test, if you are not using AutoLayout, you can add self.backgroundImageView.frame = CGRectInset(self.backgroundImageView.frame, -50, -50); to the end of viewDidLoad.

If you use AutoLayout, change your restrictions to make backgroundImageView above the container frame.

+3
source

All Articles