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

来源:互联网 发布:opencv车流量统计算法 编辑:程序博客网 时间:2024/04/29 04:14

#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下载


0 0
原创粉丝点击