如何用图案图像实现视差效果?

Din*_*aja 5 objective-c uiimageview uicolor ios swift

我一直在尝试为图像视图实现视差效果.视差效果的代码很简单,它只在我添加时才UIImage有效UIImageView.我有一个模式图像,需要在两侧平铺自己.

所以我不得不使用patternWithImage方法UIColor.当我进行视差工作时,但是self.view当我倾斜设备时,我可以看到边缘的背景颜色.

这是一个代码:

- (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];
}
Run Code Online (Sandbox Code Playgroud)

代码可以是Swift或Objective-C.任何帮助,将不胜感激.谢谢

编辑: 根据@Clafou的建议,当我尝试推送和弹出动画时,我会有一种奇怪的表情.

在此输入图像描述

Cla*_*fou 3

我猜你backgroundImageView需要延伸到容器的边缘之外,因为你的效果会改变它。

作为一个快速测试,如果您不使用 AutoLayout,您可以添加self.backgroundImageView.frame = CGRectInset(self.backgroundImageView.frame, -50, -50);到 viewDidLoad 的末尾。

如果您使用自动布局,请更改约束以使其backgroundImageView超出其容器的框架。