圖片截屏

000.gif
//
//  ViewController.m
//  04-圖片截屏(了解)
//
//  Created by 李亮 on 2016/12/1.
//  Copyright ? 2016年 www.thelast.com. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *imgView;
@property (nonatomic, weak)  UIView * coverView;
@property (nonatomic, assign) CGPoint startP;

@end

@implementation ViewController
- (UIView *)coverView{
    if (_coverView == nil) {
        UIView * coverView = [[UIView alloc] init];
        coverView.backgroundColor = [UIColor blackColor];
        coverView.alpha = 0.5;
        [self.view addSubview:coverView];
        _coverView = coverView;
    }
    return _coverView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.imgView.userInteractionEnabled = YES;
    
    UIPanGestureRecognizer * pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)];
    
    [self.imgView addGestureRecognizer:pan];
}

- (void)pan:(UIPanGestureRecognizer *)pan{
    
    CGPoint p = [pan locationInView:self.imgView];
    
    if (pan.state == UIGestureRecognizerStateBegan) {
        //獲取開始的點(diǎn)
        self.startP = p;

    }else if (pan.state == UIGestureRecognizerStateChanged){
        //當(dāng)前的點(diǎn)
        CGFloat x = self.startP.x;
        CGFloat y = self.startP.y;
        CGFloat w = p.x - self.startP.x;
        CGFloat h = p.y - self.startP.y;
        CGRect rect =  CGRectMake(x, y, w, h);
        self.coverView.frame = rect;
        
    }else if (pan.state == UIGestureRecognizerStateEnded){
        
        //開啟圖片上下文
        UIGraphicsBeginImageContextWithOptions(self.imgView.frame.size, NO, 0);
        
        CGContextRef ctx = UIGraphicsGetCurrentContext();
        
        UIBezierPath * path = [UIBezierPath bezierPathWithRect:self.coverView.frame];
        [path addClip];
        
        //把當(dāng)前的圖片壓入到上下文中
        [self.imgView.layer renderInContext:ctx];

        //取出圖片
        UIImage * newImage = UIGraphicsGetImageFromCurrentImageContext();
        
        UIGraphicsEndImageContext();
        
        self.imgView.image = newImage;
        
        [self.imgView removeGestureRecognizer:pan];
        //結(jié)束的點(diǎn)
        [self.coverView removeFromSuperview];
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容