<pre name="code" class="html">
</pre><pre name="code" class="html"><span style="font-size:24px;">截取全屏</span>
//1.开启一个位图上下文
UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, NO, 0);
//2.把UIView内的东西会知道上下文当中
CGContextRef ctx = UIGraphicsGetCurrentContext();
//通过渲染的方式绘制到上下文当中
[self.view.layer renderInContext:ctx];
//获得这个新图片
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
//关闭上下文
UIGraphicsEndImageContext();
//将图片转换为NSData
NSData *data = UIImagePNGRepresentation(image);
//将图片写到屏幕
[data writeToFile:@"/Users/gaocai/Desktop/截屏.png" atomically:YES];
在图片上截取
//
// ViewController.m
// Quartz2D-图片截屏
//
// Created by gaocai on 16/8/1.
// Copyright © 2016年 gaocai. All rights reserved.
//
#import "ViewController.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@property (nonatomic, assign) CGPoint startP;
@property (nonatomic, weak) UIView *coverV;
@end
@implementation ViewController
/**
* 懒加载
*/
- (UIView *)coverV {
if (_coverV == nil) {
//添加一个UIView
UIView *coverV = [[UIView alloc] init];
coverV.backgroundColor = [UIColor blackColor];
coverV.alpha = 0.8;
_coverV = coverV;
[self.view addSubview:coverV];
}
return _coverV;
}
- (void)viewDidLoad {
[super viewDidLoad];
}
//手势
- (IBAction)pan:(UIPanGestureRecognizer *)pan {
//获取图片上的CGPoint
CGPoint curP = [pan locationInView:self.imageView];
if (pan.state == UIGestureRecognizerStateBegan) {
self.startP = curP;
} else if(pan.state == UIGestureRecognizerStateChanged) {
CGFloat x = self.startP.x;
CGFloat y = self.startP.y;
CGFloat w = curP.x - self.startP.x;
CGFloat h = curP.y - self.startP.y;
CGRect rect = CGRectMake(x, y, w, h);
self.coverV.frame = rect;
} else if(pan.state == UIGestureRecognizerStateEnded) {
//把超过coverV的frame以外的内容裁剪掉
//生成一张图片,把原来的图片给替换掉
UIGraphicsBeginImageContextWithOptions(self.imageView.bounds.size, NO, 0);
//绘制之前设置个剪切区域
UIBezierPath *clipPath = [UIBezierPath bezierPathWithRect:self.coverV.frame];
[clipPath addClip];
//把当前的ImageView渲染到上下文中
CGContextRef ctx = UIGraphicsGetCurrentContext();
[self.imageView.layer renderInContext:ctx];
//获得一张新图片
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndPDFContext();
//将coverV移除
[self.coverV removeFromSuperview];
self.imageView.image = newImage;
}
}
@end