How to achieve parallax effect with pattern image?

951 views Asked by At

I've been trying to achieve parallax effect for an image view. Code for parallax effect is straightforward and it is working only If I add UIImage to UIImageView. I've a pattern image which needs to tile itself on both sides.

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

Here it is a 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];
}

Code can be in Swift or Objective-C. Any help would be appreciated. Thanks

EDIT: As per @Clafou suggestion, I'm getting a weird look when I try to push and pop animations.

enter image description here

1

There are 1 answers

0
Clafou On BEST ANSWER

I guess that your backgroundImageView needs to extend beyond the edges of its container since your effect will shift it.

As a quick test, if you don't use AutoLayout you could add self.backgroundImageView.frame = CGRectInset(self.backgroundImageView.frame, -50, -50); to the end of viewDidLoad.

If you use AutoLayout, change your constraints to make backgroundImageView extend beyond its container's frame.