Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to achieve parallax effect with pattern image?

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

like image 394
Dinesh Raja Avatar asked Oct 19 '22 08:10

Dinesh Raja


1 Answers

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.

like image 144
Clafou Avatar answered Oct 21 '22 23:10

Clafou