#import "ViewController.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *myImage;
@property (nonatomic, weak) UIView *blackView;
@property (nonatomic, assign) CGPoint startP;
@property (nonatomic, assign) CGRect rect;
@end
@implementation ViewController
- (UIView *)blackView
{
if (_blackView == nil) {
UIView *blackView = [[UIView alloc] init];
blackView.backgroundColor = [UIColor blackColor];
blackView.alpha = 0.5;
_blackView = blackView;
[self.view addSubview:blackView];
}
return _blackView;
}
- (void)viewDidLoad {
[super viewDidLoad];
[self pictureSigal];
}
// 截屏
- (void)clipScreen
{
// 创建一个拖动手势
UIPanGestureRecognizer *panGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)];
// 添加手势
[self.myImage addGestureRecognizer:panGestureRecognizer];
}
// 截屏业务逻辑
- (void)pan:(UIPanGestureRecognizer *)pan
{
// 获取当前点
if (pan.state == UIGestureRecognizerStateBegan) {
CGPoint panP = [pan locationInView:pan.view];
self.startP = panP;
}else if(pan.state == UIGestureRecognizerStateChanged){
// 计算截取区域
CGPoint curP = [pan locationInView:pan.view];
CGFloat rectX = self.startP.x;
CGFloat rectY = self.startP.y;
CGFloat rectW = curP.x - self.startP.x;
CGFloat rectH = curP.y - self.startP.y;
CGRect rect = CGRectMake(rectX, rectY, rectW, rectH);
self.blackView.frame = rect;
self.rect = rect;
}else if(pan.state == UIGestureRecognizerStateEnded){
// 开启位图上下文
UIGraphicsBeginImageContext(self.view.bounds.size);
UIBezierPath *path = [UIBezierPath bezierPathWithRect:self.rect];
[path addClip];
// 获取图形上下文
CGContextRef ctx = UIGraphicsGetCurrentContext();
// 把图片渲染到上下文中
[self.myImage.layer renderInContext:ctx];
// 获取新图片
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
NSData *data = UIImagePNGRepresentation(newImage);
// [data writeToFile:@"/Users/luomei/Desktop/newImage.png" atomically:YES];
// 展示新图片
self.myImage.image = newImage;
// 关闭位图上下文
UIGraphicsEndImageContext();
// 移除遮盖
[self.blackView removeFromSuperview];
}
}
- (void)pictureSigal
{
// 开启位图上下文
UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, NO, 0);
// 加载图片
UIImage *image = [UIImage imageNamed:@"newImage"];
self.myImage.image = image;
self.myImage.contentMode = UIViewContentModeScaleAspectFit;
// 加载文字
NSString *str = @"这个美女到底是在吃烧烤还是在作秀";
// 把图片写入到位图上下文中
[image drawAtPoint:CGPointZero];
// 把文字写入到位图上下文中
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
dict[NSFontAttributeName] = [UIFont systemFontOfSize:20];
dict[NSForegroundColorAttributeName] = [UIColor greenColor];
[str drawInRect:CGRectMake(20, 500, 335, 60) withAttributes:dict];
// 获取一张新的图片
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
NSData *data = UIImagePNGRepresentation(newImage);
[data writeToFile:@"/Users/luomei/Desktop/newImage.png" atomically:YES];
// 将新图片展示
self.myImage.image = newImage;
// 关闭位图上下文
UIGraphicsEndImageContext();
}
@end