简单介绍截取图片
完整图片
截取后的图片
首先创建一个UIImageView,导入图片
然后ViewController.m
#import "ViewController.h"
@interface ViewController ()
@property(nonatomic,assign)CGPoint startP;
/**截取的view*/
@property(nonatomic,weak)UIView * clipView;
@property (weak, nonatomic) IBOutlet UIImageView *myImageView;
@end
@implementation ViewController
//懒加载clipView
-(UIView *)clipView
{
if (_clipView == nil) {
UIView * view = [[UIView alloc]init];
_clipView = view;
view.backgroundColor = [UIColor blackColor];
view.alpha = 0.5;
[self.view addSubview:view];
}
return _clipView;
}
- (void)viewDidLoad {
[super viewDidLoad];
//添加pan手势
UIPanGestureRecognizer * pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(pan:)];
[self.view addGestureRecognizer:pan];
}
-(void)pan:(UIPanGestureRecognizer*)pan
{
CGPoint endA = CGPointZero;
if (pan.state == UIGestureRecognizerStateBegan) {
//获取一开始的触摸点
self.startP = [pan locationInView:self.view];
}else if (pan.state == UIGestureRecognizerStateChanged)
{
//获取结束点
endA = [pan locationInView:self.view];
CGFloat w = endA.x - _startP.x;
CGFloat h = endA.y - _startP.y;
//获取截取范围
CGRect clipRect = CGRectMake(_startP.x, _startP.y, w, h);
//生成截屏的view
self.clipView.frame = clipRect;
}else if (pan.state == UIGestureRecognizerStateEnded)
{
//图片剪裁,生成一张新的图片
//开启上下文
UIGraphicsBeginImageContextWithOptions(_myImageView.bounds.size, NO, 0);
//设置裁剪区域
UIBezierPath * path = [UIBezierPath bezierPathWithRect:self.clipView.frame];
[path addClip];
//获取上下文
CGContextRef ctx = UIGraphicsGetCurrentContext();
//把控件上的内容渲染到上下文
[self.myImageView.layer renderInContext:ctx];
//生成一张新的图片
_myImageView.image = UIGraphicsGetImageFromCurrentImageContext();
//关闭上下文
UIGraphicsEndPDFContext();
//先移除
[self.clipView removeFromSuperview];
_clipView = nil;
}
}
@end