iOS实现图片内容扭曲效果


//
//  ZKRBaiWeiAdManager.m
//  VAPictureBoomAnimationDemo
//
//  Created by ZAKER on 2019/6/4.
//  Copyright © 2019 ZAKER. All rights reserved.
//

#import "ZKRBaiWeiAdManager.h"

static ZKRBaiWeiAdManager *shareManager = nil;

@interface ZKRBaiWeiAdManager ()

@property (nonatomic, strong) UIView *animationView;

@property (nonatomic, strong) AVPlayer *player;

@property (nonatomic, strong) AVPlayerLayer *palyLayer;

@property (nonatomic, assign) ZKRBaiWeiAVPlayerStatus status;

@property (nonatomic, weak) UIButton *maskBtn;

@property (nonatomic, strong) id listenObj;

@property (nonatomic, weak) id <ZKRBaiWeiAdManagerPlayerDelegate>delegate;

@property (nonatomic, assign) BOOL isAlreadlyStartPlaying;

@property (nonatomic, assign) BOOL isAlreadlyStartAnimating;


@end

@implementation ZKRBaiWeiAdManager

+ (instancetype)shareManager{
    
    shareManager = [[ZKRBaiWeiAdManager alloc] init];
    return shareManager;
}

+ (instancetype)allocWithZone:(struct _NSZone *)zone{
    
    if (shareManager) {
        return shareManager;
    }
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
       shareManager = [super allocWithZone:zone];
    });
    return shareManager;
}
- (UIImage *)clipTofullScreen{
    
    UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
    
    CGSize imageSize = CGSizeZero;
    if (UIInterfaceOrientationIsPortrait(orientation))
        imageSize = [UIScreen mainScreen].bounds.size;
    else
        imageSize = CGSizeMake([UIScreen mainScreen].bounds.size.height, [UIScreen mainScreen].bounds.size.width);
    
    UIGraphicsBeginImageContextWithOptions(imageSize, NO, [UIScreen mainScreen].scale);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    for (UIWindow *window in [[UIApplication sharedApplication] windows])
    {
        CGContextSaveGState(context);
        CGContextTranslateCTM(context, window.center.x, window.center.y);
        CGContextConcatCTM(context, window.transform);
        CGContextTranslateCTM(context, -window.bounds.size.width * window.layer.anchorPoint.x, -window.bounds.size.height * window.layer.anchorPoint.y);
       
            if(orientation == UIInterfaceOrientationLandscapeLeft){
                CGContextRotateCTM(context, (CGFloat)M_PI_2);
                CGContextTranslateCTM(context, 0, -imageSize.width);
            }
            else if(orientation == UIInterfaceOrientationLandscapeRight){
                CGContextRotateCTM(context, (CGFloat)-M_PI_2);
                CGContextTranslateCTM(context, -imageSize.height, 0);
            }
            else if(orientation == UIInterfaceOrientationPortraitUpsideDown)
            {
                CGContextRotateCTM(context, (CGFloat)M_PI);
                CGContextTranslateCTM(context, -imageSize.width, -imageSize.height);
            }
        
            if([window respondsToSelector:@selector(drawViewHierarchyInRect:afterScreenUpdates:)]){
                [window drawViewHierarchyInRect:window.bounds afterScreenUpdates:NO];
            }
        
        else{
            [window.layer renderInContext:UIGraphicsGetCurrentContext()];
        }
        
        CGContextRestoreGState(context);
    }
    
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return newImage;
}


- (UIView *)animationView{
    if (!_animationView) {
        UIView *animationView = [[UIView alloc] init];
        _animationView = animationView;
    }
    
    return _animationView;
}

- (UIView *)lancinateAnimationView:(UIView *)view size:(CGSize)size{
    
    self.animationView.frame = view.bounds;
    [view.superview addSubview:self.animationView];
    
    UIGraphicsBeginImageContext(view.bounds.size);
    [[UIColor clearColor] setFill];
    [[UIBezierPath bezierPathWithRect:view.bounds] fill];
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    [view.layer renderInContext:ctx];
    
    UIImage *screenshotImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    NSInteger maxX = floor(screenshotImage.size.width / size.width);
    NSInteger maxY = floor(screenshotImage.size.height / size.height);
    
    for (int i=0; i<maxX; i++) {
        for (int j = 0; j<maxY; j++) {
            
            @autoreleasepool {
                
                CALayer* layer = [[CALayer alloc] init];
                layer.frame = CGRectMake(i*size.width, (maxY-j-1)*size.height, size.width, size.height);
                CGContextRef offscreenContext = CGBitmapContextCreate(NULL,
                                                                      size.width,
                                                                      size.height,
                                                                      8,
                                                                      0,
                                                                      CGImageGetColorSpace(screenshotImage.CGImage),
                                                                      kCGBitmapByteOrderDefault | kCGImageAlphaPremultipliedFirst);
                CGContextTranslateCTM(offscreenContext, -i*size.width, -j*size.height);
                CGContextDrawImage(offscreenContext, CGRectMake(0, 0, screenshotImage.size.width, screenshotImage.size.height), screenshotImage.CGImage);
                CGImageRef imageRef = CGBitmapContextCreateImage(offscreenContext);
                
                layer.contents = CFBridgingRelease(imageRef);
                CGContextRelease(offscreenContext);
                [self.animationView.layer addSublayer:layer];
                
            }
        }
    }

    return self.animationView;
    
}
- (void)lancinateAnimationView:(UIView *)view horizontalscale:(CGFloat)sublayerH animationScaleRatio:(CGFloat)scaleRatio animationDuration:(CGFloat)duration repeatCount:(NSInteger)conut isRemoveMask:(BOOL)isRemove completeBlock:(completeBlock)completeBlock{
    
    [self lancinateAnimationView:view size:CGSizeMake(view.bounds.size.width, sublayerH)];
     CGFloat ratio = scaleRatio * 2.0 /(self.animationView.layer.sublayers.count *0.01);
     CGFloat baseValue = [self getRandRangeFloutValue:scaleRatio];
    [self doLancinateAnimationKeyPath:@"transform.scale.x" ratio:ratio scaleRatio:(CGFloat)scaleRatio baseValue:baseValue duration:duration repeatCount:conut isRemoveMask:isRemove completeBlock:completeBlock];
}
- (void)lancinateAnimationView:(UIView *)view verticalScale:(CGFloat)sublayerW animationScaleRatio:(CGFloat)scaleRatio animationDuration:(CGFloat)duration repeatCount:(NSInteger)conut isRemoveMask:(BOOL)isRemove completeBlock:(completeBlock)completeBlock{
    
    [self lancinateAnimationView:view size:CGSizeMake(sublayerW, view.bounds.size.height)];
    CGFloat baseValue = [self getRandRangeFloutValue:scaleRatio];
    CGFloat ratio = scaleRatio * 2.0 /(self.animationView.layer.sublayers.count *0.03);
    [self doLancinateAnimationKeyPath:@"transform.scale.y" ratio:ratio scaleRatio:(CGFloat)scaleRatio baseValue:baseValue duration:duration repeatCount:conut isRemoveMask:isRemove completeBlock:completeBlock];
}

- (void)doLancinateAnimationKeyPath:(NSString *)key ratio:(CGFloat)ratio scaleRatio:(CGFloat)scaleRatio baseValue:(CGFloat)baseValue duration:(CGFloat)duration repeatCount:(NSInteger)conut isRemoveMask:(BOOL)isRemove completeBlock:(completeBlock)completeBlock{
    
    for (CALayer *shape in self.animationView.layer.sublayers) {
        @autoreleasepool {
            CABasicAnimation *scaleAnimation = [CABasicAnimation animationWithKeyPath:key];
            scaleAnimation.fromValue = @(1.0);
            CGFloat resultValue = [self getRandFloutRadioValue:ratio baseValue:baseValue limitValue:scaleRatio];
            baseValue = resultValue;
            scaleAnimation.toValue = @(resultValue + 1.0);
            scaleAnimation.duration = duration;
            scaleAnimation.repeatCount  = conut;
            [shape addAnimation:scaleAnimation forKey:@"lancinateAnimationX"];
        }
    }
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(duration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        if (isRemove) {
            [self.animationView removeFromSuperview];
            self.animationView = nil;
        }
       
        if (completeBlock) {
            completeBlock();
        }
    });
}

- (CGFloat)getRandRangeFloutValue:(CGFloat)rangeValue{
    return (float)random()/(float)RAND_MAX *rangeValue *2.0 - rangeValue;;
}

- (CGFloat)getRandFloutRadioValue:(CGFloat)radioValue baseValue:(CGFloat)baseValue limitValue:(CGFloat)limitValue{
    
    CGFloat randGradualValue = [self getRandRangeFloutValue:radioValue];
    CGFloat result = baseValue + randGradualValue;
     while (fabs(result) >= limitValue) {
         randGradualValue = [self getRandRangeFloutValue:radioValue];
         result = baseValue + randGradualValue;
    }
    return result;
}

- (void)lancinateAnimateDefaultModeView:(UIView *)view completeBlock:(completeBlock)completeBlock{
    
    if (self.isAlreadlyStartAnimating) {
        return;
    }
    
    self.isAlreadlyStartAnimating = YES;
    
    CGFloat horizonScale = 2.0;
    CGFloat verticalScale = 2.0;
    CGFloat animationTime = 0.4;
    CGFloat horizonScaleRatio = 0.048;
    CGFloat verticalScaleRatio = 0.039;
    
    [self lancinateAnimationView:view horizontalscale:horizonScale animationScaleRatio:horizonScaleRatio animationDuration:animationTime repeatCount:1 isRemoveMask:YES completeBlock:^{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self lancinateAnimationView:view verticalScale:verticalScale animationScaleRatio:verticalScaleRatio animationDuration:animationTime repeatCount:1 isRemoveMask:YES completeBlock:^{
                
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self lancinateAnimationView:view horizontalscale:horizonScale animationScaleRatio:horizonScaleRatio animationDuration:animationTime  repeatCount:1 isRemoveMask:YES completeBlock:^{
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                            [self lancinateAnimationView:view verticalScale:verticalScale animationScaleRatio:verticalScaleRatio animationDuration:animationTime repeatCount:1 isRemoveMask:NO completeBlock:^{
                                
                                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.15 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                                    self.isAlreadlyStartAnimating = NO;
                                    if (completeBlock) {
                                        completeBlock();
                                    }
                                });
                            }];
                        });
                    }];
                });
            }];
        });
    }];
}

- (void)removeMaskView{
    
    if (self.animationView) {
        [self.animationView removeFromSuperview];
        self.animationView = nil;
    }
}

/// 视频相关
- (void)playToFullScreen:(NSURL *)videoURL delegate:(id<ZKRBaiWeiAdManagerPlayerDelegate>)delegate{

    [self playWithPlayer:videoURL playToView:[UIApplication sharedApplication].keyWindow delegate:delegate];
}

- (void)playWithPlayer:(NSURL *)videoURL playToView:(UIView *)view delegate:(id<ZKRBaiWeiAdManagerPlayerDelegate>)delegate{
    
    if (self.isAlreadlyStartPlaying) {
        return;
    }
    
    if (!videoURL) {
        NSLog(@"videoURL不能为空");
        return;
    }
    
    if (!view) {
        NSLog(@"view不能为空");
        return;
    }
    
    if (delegate) {
        _delegate = delegate;
    }
    
    AVPlayer *player = [AVPlayer playerWithURL:videoURL];
    self.player = player;
    self.palyLayer = [AVPlayerLayer playerLayerWithPlayer:player];
    self.palyLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    self.palyLayer.frame = view.bounds;
    
    UIButton *maskBtn = [UIButton new];
    _maskBtn = maskBtn;
    [maskBtn addTarget:self action:@selector(touchedVideo) forControlEvents:UIControlEventTouchUpInside];
    maskBtn.backgroundColor = [UIColor clearColor];
    maskBtn.frame = view.bounds;
    [view addSubview:maskBtn];
    
    [view.layer addSublayer:self.palyLayer];
    [player play];
    self.isAlreadlyStartPlaying = YES;
    if (@available(iOS 10.0, *)) {
        [player addObserver:self forKeyPath:@"timeControlStatus" options:NSKeyValueObservingOptionNew context:nil];
    }

   __weak typeof(self)weakSelf = self;
   self.listenObj = [player addPeriodicTimeObserverForInterval:CMTimeMakeWithSeconds(1, NSEC_PER_SEC) queue:NULL usingBlock:^(CMTime time) {

        CGFloat progress = CMTimeGetSeconds(player.currentItem.currentTime) / CMTimeGetSeconds(player.currentItem.duration);
       
       if (weakSelf.delegate && [weakSelf.delegate respondsToSelector:@selector(player:playProgress:)]) {
           [weakSelf.delegate player:weakSelf.player playProgress:progress];
       }
       
        if (progress == 1.0f) {
            if (weakSelf.delegate && [weakSelf.delegate respondsToSelector:@selector(playfinish:)]) {
                [weakSelf.delegate playfinish:weakSelf.player];
            }
        }
    }];
}
- (void)touchedVideo{
   
    if (_delegate && [_delegate respondsToSelector:@selector(touchInsideVideoLayer:)]) {
         [_delegate touchInsideVideoLayer:_player];
    }
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    
    if (object == _player && [keyPath isEqualToString:@"timeControlStatus"]) {
        
            AVPlayerTimeControlStatus status = [[change objectForKey:NSKeyValueChangeNewKey] integerValue];
            if (status ==  AVPlayerTimeControlStatusPaused) {
                _status = ZKRBaiWeiAVPlayerStatusPause;
            }
            
            if (status == AVPlayerTimeControlStatusWaitingToPlayAtSpecifiedRate) {
                _status = ZKRBaiWeiAVPlayerStatusReadyToPlay;
            }
            
            if (status ==  AVPlayerTimeControlStatusPlaying) {
                _status = ZKRBaiWeiAVPlayerStatusPlaying;
            }
            if (_delegate && [_delegate respondsToSelector:@selector(player:playStatusChanged:)]) {
                [_delegate player:_player playStatusChanged:_status];
            }
        }
}

- (void)playPause{
    if (_player) {
        [_player pause];
    }
}

- (void)removePlayLayer{
    
    [self playPause];
    
    [_palyLayer removeFromSuperlayer];
    [_player removeTimeObserver:_listenObj];
    _listenObj = nil;
    _player = nil;
    _palyLayer = nil;
    [_maskBtn removeFromSuperview];
    _maskBtn = nil;
    self.isAlreadlyStartPlaying = NO;
}
@end

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,386评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,142评论 3 394
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,704评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,702评论 1 294
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,716评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,573评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,314评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,230评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,680评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,873评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,991评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,706评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,329评论 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,910评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,038评论 1 270
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,158评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,941评论 2 355

推荐阅读更多精彩内容