图片截屏
2016-12-01 本文已影响9人
遇见灬最美的你
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) {
//获取开始的点
self.startP = p;
}else if (pan.state == UIGestureRecognizerStateChanged){
//当前的点
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];
//把当前的图片压入到上下文中
[self.imgView.layer renderInContext:ctx];
//取出图片
UIImage * newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
self.imgView.image = newImage;
[self.imgView removeGestureRecognizer:pan];
//结束的点
[self.coverView removeFromSuperview];
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end