您的位置:首页 > 产品设计 > UI/UE

UIView添加背景视差效果(MotionEffect)

2016-07-27 17:09 337 查看
#pragma mark - 给UIView添加一个category

#pragma mark - UIView+MotionEffect.h

//

//  UIView+MotionEffect.h

//  背景视差效果

//

//  Created by HarrySun on 16/7/27.

//  Copyright © 2016年 Mobby. All rights reserved.

//

#import <UIKit/UIKit.h>

@interface UIView (MotionEffect)

@property (nonatomic,strong)
UIMotionEffectGroup *effectGroup;

- (void)addXAxisWithValue:(CGFloat)xValue YAxisWithValue:(CGFloat)yValue;

- (void)removeSelfMotionEffect;

@end

#pragma mark - UIView+MotionEffect.m

//

//  UIView+MotionEffect.m

//  背景视差效果

//

//  Created by HarrySun on 16/7/27.

//  Copyright © 2016年 Mobby. All rights reserved.

//

#import "UIView+MotionEffect.h"

#import <objc/runtime.h>

static char motionEffectFlag;

@implementation UIView (MotionEffect)

- (void)setEffectGroup:(UIMotionEffectGroup *)effectGroup {

    // 清除关联

    objc_setAssociatedObject(self, &motionEffectFlag,nil,
OBJC_ASSOCIATION_RETAIN_NONATOMIC);

    

    // 建立关联

    objc_setAssociatedObject(self, &motionEffectFlag,
effectGroup, OBJC_ASSOCIATION_RETAIN_NONATOMIC);

}

- (UIMotionEffectGroup *)effectGroup {

    // 返回关联

    returnobjc_getAssociatedObject(self,
&motionEffectFlag);

}

- (void)addXAxisWithValue:(CGFloat)xValue YAxisWithValue:(CGFloat)yValue
{

    if ((xValue >=0) && (yValue >=
0)) {

        UIInterpolatingMotionEffect *xAxis = [[UIInterpolatingMotionEffectalloc]
initWithKeyPath:@"center.x"type:UIInterpolatingMotionEffectTypeTiltAlongHorizontalAxis];

        xAxis.minimumRelativeValue =@(-xValue);

        xAxis.maximumRelativeValue =@(xValue);

        

        UIInterpolatingMotionEffect *yAxis = [[UIInterpolatingMotionEffectalloc]
initWithKeyPath:@"center.y"type:UIInterpolatingMotionEffectTypeTiltAlongVerticalAxis];

        yAxis.minimumRelativeValue =@(-yValue);

        yAxis.maximumRelativeValue =@(yValue);

        

        // 先移除效果再添加效果

        self.effectGroup.motionEffects =nil;

        [selfremoveMotionEffect:self.effectGroup];

        self.effectGroup.motionEffects =@[xAxis,
yAxis];

        

        // 给view添加效果

        [selfaddMotionEffect:self.effectGroup];

    }

}

- (void)removeSelfMotionEffect {

    [selfremoveMotionEffect:self.effectGroup];

}

@end

#pragma mark - 调用

在viewDidLoad中

    UIImageView *imageView = [[UIImageViewalloc]
initWithImage:[UIImageimageNamed:@"1.jpg"]];

    imageView.frame =self.view.bounds;

    imageView.center =self.view.center;

    [self.viewaddSubview:imageView];

    

    imageView.effectGroup = [UIMotionEffectGroupnew];

    

    [imageView addXAxisWithValue:15.fYAxisWithValue:15.f];

这样就能实现背景视差效果,这个效果在模拟器上无法呈现,有苹果设备的小伙伴可以将工程打包到设备上查看或者在锁屏状态下看home背景 也有背景视差效果。

demo网址:UIMotionEffect下载
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息