码迷,mamicode.com
首页 > 其他好文 > 详细

Xcode屏幕图片截取

时间:2016-05-12 13:47:08      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:


#import "ViewController.h"

@interface ViewController ()
//显示图片
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
//pan手指刚开始移动的位置
@property (nonatomic, assign) CGPoint startPoint;
//pan手势结束的位置
@property (nonatomic, assign) CGPoint endPoint;
//剪切的半透明视图
@property (nonatomic, strong) UIView *clipView;
@end

@implementation ViewController

//懒加载clipView,在拖拽的过程中只创建一次,避免视图上创建过多无用的view
- (UIView*)clipView
{
    if (_clipView == nil) {
        _clipView = [[UIView alloc] init];
        _clipView.backgroundColor = [UIColor blackColor];
        _clipView.alpha = 0.5;
        [self.view addSubview:_clipView];
    }
    return _clipView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    //给控制器添加一个pan手势
    UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)];
    [self.view addGestureRecognizer:panGesture];
    
}

- (void)pan:(UIPanGestureRecognizer*)panGesture
{
    
    if (panGesture.state == UIGestureRecognizerStateBegan) { //panBegin
        
        //startPoint保存pan手势的开始位置
        CGPoint startPoint = [panGesture locationInView:self.view];
        self.startPoint = startPoint;
        
    } else if (panGesture.state == UIGestureRecognizerStateChanged) { //PanChanged
        
        CGPoint endPoint = [panGesture locationInView:self.view];
        self.endPoint = endPoint;
        CGFloat clipViewX = self.startPoint.x;
        CGFloat clipViewY = self.startPoint.y;
        CGFloat clipViewW = self.endPoint.x - self.startPoint.x;
        CGFloat clipCiewH = self.endPoint.y - self.startPoint.y;
        self.clipView.frame = CGRectMake(clipViewX, clipViewY, clipViewW, clipCiewH);
        
    } else if (panGesture.state == UIGestureRecognizerStateEnded) { //panEnded
        
        //图片裁剪,生成一张新的图片
        //1.开启上下文
        UIGraphicsBeginImageContextWithOptions(self.imageView.frame.size, NO, 0);
        
        //2.设置裁剪区域
        UIBezierPath *path = [UIBezierPath bezierPathWithRect:self.clipView.frame];
        
        [path addClip];
        
        //3.获取上下文
        CGContextRef ctx = UIGraphicsGetCurrentContext();
        
        //4.把控件上的内容渲染到上下文中
        [self.imageView.layer renderInContext:ctx];
        
        //5.生成一张新的图片
        self.imageView.image = UIGraphicsGetImageFromCurrentImageContext();
        
        //6.关闭就上下文
        UIGraphicsEndImageContext();
        
        //7.移除clipView
        [self.clipView removeFromSuperview];
        
    }
}

@end
屏幕图片剪切效果演示:

技术分享

Xcode屏幕图片截取

标签:

原文地址:http://blog.csdn.net/bao_libra/article/details/51364310

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!