PhotoView.m 14.4 KB
//
//  PhotoView.m
//  aoyouHH
//
//  Created by jinzelu on 15/4/30.
//  Copyright (c) 2015年 jinzelu. All rights reserved.
//

#import "PhotoView.h"
//#import "UIImageView+WebCache.h"
#import "MBProgressHUD.h"
//#import "UIView+Toast.h"
//#import "UIAlertView+NTESBlock.h"
//#import "SVProgressHUD.h"

@interface PhotoView ()<UIScrollViewDelegate>
{
    UIScrollView *_scrollView;
    MBProgressHUD *hud;
    NSString *path;
}

@end

@implementation PhotoView

@synthesize moviePlayer = _moviePlayer;
@synthesize avPlayer = _avPlayer;

-(id)initWithFrame:(CGRect)frame withPhotoUrl:(NSString *)photoUrl{
    self = [super initWithFrame:frame];
    if (self) {
        //添加scrollView
        _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height)];
        _scrollView.delegate = self;
        _scrollView.minimumZoomScale = 1;
        _scrollView.maximumZoomScale = 3;
        
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.showsVerticalScrollIndicator = NO;
        [self addSubview:_scrollView];
        //添加图片
        self.imageView = [[UIImageView alloc] initWithFrame:_scrollView.bounds];
        self.imageView.contentMode = UIViewContentModeScaleAspectFit;
        
        SDWebImageManager *manager = [SDWebImageManager sharedManager];
    
        [manager.imageCache containsImageForKey:photoUrl cacheType:SDImageCacheTypeAll completion:^(SDImageCacheType containsCacheType) {
            BOOL isInCache = (containsCacheType == SDImageCacheTypeNone)?NO:YES;
            if (!isInCache) {//没有缓存
                self->hud = [MBProgressHUD showHUDAddedTo:self animated:YES];
                self->hud.mode = MBProgressHUDModeDeterminate;
            }
            [self.imageView sd_setImageWithURL:[NSURL URLWithString:photoUrl] placeholderImage:[UIImage imageNamed:@"comment_empty_img"] options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
                self->hud.progress = ((float)receivedSize)/expectedSize;
            } completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
                NSLog(@"图片加载完成");
                if (!isInCache) {
                    [self->hud hide:YES];
                }
            }];
        }];
        
//        [manager cachedImageExistsForURL:[NSURL URLWithString:photoUrl] completion:^(BOOL isInCache) {
//            if (!isInCache) {//没有缓存
//                hud = [MBProgressHUD showHUDAddedTo:self animated:YES];
//                hud.mode = MBProgressHUDModeDeterminate;
//            }
//            [self.imageView sd_setImageWithURL:[NSURL URLWithString:photoUrl] placeholderImage:[UIImage imageNamed:@"comment_empty_img"] options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
//                hud.progress = ((float)receivedSize)/expectedSize;
//            } completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
//                NSLog(@"图片加载完成");
//                if (!isInCache) {
//                    [hud hide:YES];
//                }
//            }];
//
//        }];
        
        [self.imageView setUserInteractionEnabled:YES];
        [_scrollView addSubview:self.imageView];
        
        //添加手势
        UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
        UITapGestureRecognizer *doubleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleDoubleTap:)];
        UITapGestureRecognizer *twoFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTwoFingerTap:)];
        UILongPressGestureRecognizer *longPressGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressGesture:)];
        
        singleTap.numberOfTapsRequired = 1;
        singleTap.numberOfTouchesRequired = 1;
        doubleTap.numberOfTapsRequired = 2;//需要点两下
        twoFingerTap.numberOfTouchesRequired = 2;//需要两个手指touch
        longPressGesture.minimumPressDuration = 0.5; //(2秒)
        
        [self.imageView addGestureRecognizer:singleTap];
        [self.imageView addGestureRecognizer:doubleTap];
        [self.imageView addGestureRecognizer:twoFingerTap];
        [self.imageView addGestureRecognizer:longPressGesture];
        [singleTap requireGestureRecognizerToFail:doubleTap];//如果双击了,则不响应单击事件
        
        [_scrollView setZoomScale:1];
    }
    return self;
}

-(id)initWithFrame:(CGRect)frame withPhotoImage:(UIImage *)image{
    self = [super initWithFrame:frame];
    if (self) {
        //添加scrollView
        _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height)];
        _scrollView.delegate = self;
        _scrollView.minimumZoomScale = 1;
        _scrollView.maximumZoomScale = 3;
        
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.showsVerticalScrollIndicator = NO;
        [self addSubview:_scrollView];
        //添加图片
        self.imageView = [[UIImageView alloc] initWithFrame:_scrollView.bounds];
        self.imageView.contentMode = UIViewContentModeScaleAspectFit;
        [self.imageView setImage:image];
        
        [self.imageView setUserInteractionEnabled:YES];
        [_scrollView addSubview:self.imageView];
        
        //添加手势
        UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
        UITapGestureRecognizer *doubleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleDoubleTap:)];
        UITapGestureRecognizer *twoFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTwoFingerTap:)];
        UILongPressGestureRecognizer *longPressGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressGesture:)];

        singleTap.numberOfTapsRequired = 1;
        singleTap.numberOfTouchesRequired = 1;
        doubleTap.numberOfTapsRequired = 2;//需要点两下
        twoFingerTap.numberOfTouchesRequired = 2;//需要两个手指touch
        longPressGesture.minimumPressDuration = 0.5; //(2秒)
        
        [self.imageView addGestureRecognizer:singleTap];
        [self.imageView addGestureRecognizer:doubleTap];
        [self.imageView addGestureRecognizer:longPressGesture];
        [self.imageView addGestureRecognizer:twoFingerTap];
        [singleTap requireGestureRecognizerToFail:doubleTap];//如果双击了,则不响应单击事件
        
        
        [_scrollView setZoomScale:1];
    }
    return self;
}

#pragma mark - UIScrollViewDelegate
//scroll view处理缩放和平移手势,必须需要实现委托下面两个方法,另外 maximumZoomScale和minimumZoomScale两个属性要不一样
//1.返回要缩放的图片
-(UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{
    return self.imageView;
}
//2.重新确定缩放完后的缩放倍数
-(void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale{
    [scrollView setZoomScale:scale+0.01 animated:NO];
    [scrollView setZoomScale:scale animated:NO];
}


#pragma mark - 图片的点击,touch事件
-(void)handleSingleTap:(UITapGestureRecognizer *)gestureRecognizer{
    NSLog(@"单击");
    if (gestureRecognizer.numberOfTapsRequired == 1) {
        [self.delegate TapHiddenPhotoView];
    }
}

-(void)handleDoubleTap:(UITapGestureRecognizer *)gestureRecognizer{
    NSLog(@"双击");
    if (gestureRecognizer.numberOfTapsRequired == 2) {
        if(_scrollView.zoomScale == 1){
            float newScale = [_scrollView zoomScale] *2;
            CGRect zoomRect = [self zoomRectForScale:newScale withCenter:[gestureRecognizer locationInView:gestureRecognizer.view]];
            [_scrollView zoomToRect:zoomRect animated:YES];
        }else{
            float newScale = [_scrollView zoomScale]/2;
            CGRect zoomRect = [self zoomRectForScale:newScale withCenter:[gestureRecognizer locationInView:gestureRecognizer.view]];
            [_scrollView zoomToRect:zoomRect animated:YES];
        }
    }
}

-(void)handleTwoFingerTap:(UITapGestureRecognizer *)gestureRecongnizer{
    NSLog(@"2手指操作");
    float newScale = [_scrollView zoomScale]/2;
    CGRect zoomRect = [self zoomRectForScale:newScale withCenter:[gestureRecongnizer locationInView:gestureRecongnizer.view]];
    [_scrollView zoomToRect:zoomRect animated:YES];
}

//常摁手势触发方法
-(void)longPressGesture:(id)sender
{
    UILongPressGestureRecognizer *longPress = sender;
    if (longPress.state == UIGestureRecognizerStateBegan)
    {
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        
        UIAlertAction *Photo = [UIAlertAction actionWithTitle:@"保存到手机" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            
            UIImageWriteToSavedPhotosAlbum([self.imageView image], nil, nil,nil);
            
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"存储照片成功"
                                                            message:@"您已将照片存储于手机中,打开照片即可查看。"
                                                           delegate:self
                                                  cancelButtonTitle:@"OK"
                                                  otherButtonTitles:nil];
            [alert show];
            
            
        }];
        UIAlertAction *Cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        
        
        [alertVC addAction:Photo];
        [alertVC addAction:Cancel];
        
        [self.delegate longPressGesturePhotoView:alertVC];
    }
}


#pragma mark - 缩放大小获取方法
-(CGRect)zoomRectForScale:(CGFloat)scale withCenter:(CGPoint)center{
    CGRect zoomRect;
    //大小
    zoomRect.size.height = [_scrollView frame].size.height/scale;
    zoomRect.size.width = [_scrollView frame].size.width/scale;
    //原点
    zoomRect.origin.x = center.x - zoomRect.size.width/2;
    zoomRect.origin.y = center.y - zoomRect.size.height/2;
    return zoomRect;
}

- (MPMoviePlayerController*)moviePlayer{
    if (!_moviePlayer) {
        _moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:[NSURL fileURLWithPath:path]];
        _moviePlayer.controlStyle = MPMovieControlStyleEmbedded;
        _moviePlayer.scalingMode = MPMovieScalingModeAspectFill;
        _moviePlayer.fullscreen = YES;
    }
    return _moviePlayer;
}

- (AVPlayerViewController*)avPlayer{
    if (!_avPlayer) {
        _avPlayer = [[AVPlayerViewController alloc]init];
        _avPlayer.player = [AVPlayer playerWithURL:[NSURL fileURLWithPath:path]];
    }
    return _avPlayer;
}

- (void)startPlay{
    self.avPlayer.view.frame = CGRectMake(0, 0, ScreenWidth, self.bounds.size.height);
    [self addSubview:self.avPlayer.view];
    
    UIImageView *img_back = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"xn talk-ios-37"]];
    [self addSubview:img_back];
    [img_back mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.avPlayer.view.mas_top).offset(40);
        make.left.equalTo(self.mas_left).offset(20);
    }];
    
    UIButton *btn_back = [[UIButton alloc]init];
    [btn_back addTarget:self action:@selector(removeReader) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:btn_back];
    [btn_back mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(img_back.mas_centerY);
        make.left.equalTo(self.mas_left).offset(20);
        make.width.equalTo(@50);
        make.height.equalTo(@50);
    }];

}

- (void)removeReader{
    [self.delegate TapHiddenPhotoView];
}

- (void)onTap: (UIGestureRecognizer *)recognizer
{
    switch (self.moviePlayer.playbackState)
    {
        case MPMoviePlaybackStatePlaying:
            [self.moviePlayer pause];
            break;
        case MPMoviePlaybackStatePaused:
        case MPMoviePlaybackStateStopped:
        case MPMoviePlaybackStateInterrupted:
            [self.moviePlayer play];
            break;
        default:
            break;
    }
}

- (void)moviePlaybackComplete: (NSNotification *)aNotification
{
    if (self.moviePlayer == aNotification.object)
    {
        
        NSDictionary *notificationUserInfo = [aNotification userInfo];
        NSNumber *resultValue = [notificationUserInfo objectForKey:MPMoviePlayerPlaybackDidFinishReasonUserInfoKey];
        MPMovieFinishReason reason = [resultValue intValue];
        if (reason == MPMovieFinishReasonPlaybackError)
        {
            NSError *mediaPlayerError = [notificationUserInfo objectForKey:@"error"];
            NSString *errorTip = [NSString stringWithFormat:@"%@: %@",@"播放失败", [mediaPlayerError localizedDescription]];
            [self makeToast:errorTip
                        duration:2
                        position:CSToastPositionCenter];
        }
    }
    
}

- (void)moviePlayStateChanged: (NSNotification *)aNotification
{
    if (self.moviePlayer == aNotification.object)
    {
        switch (self.moviePlayer.playbackState)
        {
            case MPMoviePlaybackStatePlaying:
                break;
            case MPMoviePlaybackStatePaused:
            case MPMoviePlaybackStateStopped:
            case MPMoviePlaybackStateInterrupted:
            case MPMoviePlaybackStateSeekingBackward:
            case MPMoviePlaybackStateSeekingForward:
                break;
        }
        
    }
}


//- (void)downLoadVideo:(void(^)(NSError *error))handler{
//    [SVProgressHUD show];
//    __weak typeof(self) wself = self;
//    [[NIMSDK sharedSDK].resourceManager download:_video.url filepath:_video.path progress:^(float progress) {
//        [SVProgressHUD showProgress:progress];
//    } completion:^(NSError *error) {
//        if (wself) {
//            [SVProgressHUD dismiss];
//            if (handler) {
//                handler(error);
//            }
//        }
//    }];
//}


/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end