效果如下
效果图
图片截屏实现思路.
- 1、手指在屏幕上移动的时,添加一个半透明的UIView(作为遮盖)
- 2、然后开启一个上下文把UIView的frame设置成裁剪区域.把图片显示的图片绘制到上下文当中,生成一张新的图片
- 3、再把生成的图片再赋值给原来的UImageView.
代码实现如下:
#import "ViewController.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
/** 开始点*/
@property (assign, nonatomic) CGPoint startP;
/** 当前点*/
@property (assign, nonatomic) CGPoint currP;
/** 遮盖view*/
@property (weak, nonatomic) UIView *coverView;
@end
@implementation ViewController
- (UIView *)coverView {
if (_coverView == nil) {
UIView *cV = [[UIView alloc] init];
_coverView = cV;
_coverView.backgroundColor = [UIColor grayColor];
_coverView.alpha = 0.7;
[self.view addSubview:_coverView];
}
return _coverView;
}
- (void)viewDidLoad {
[super viewDidLoad];
self.imageView.userInteractionEnabled = YES;
// 给imageview添加手势
UIPanGestureRecognizer *panGest = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panHandle:)];
[self.imageView addGestureRecognizer:panGest];
}
- (void)panHandle:(UIPanGestureRecognizer *)panGest {
// NSLog(@"%s", __func__);
CGFloat coverX = 0;
CGFloat coverY = 0;
CGFloat coverW = 0;
CGFloat coverH = 0;
if (panGest.state == UIGestureRecognizerStateBegan) {
// 获取起点
self.startP = [panGest locationInView:self.view];
} else if(panGest.state == UIGestureRecognizerStateChanged) {
// 获取当前点
self.currP = [panGest locationInView:self.view];
coverX = self.startP.x;
coverY = self.startP.y;
coverW = self.currP.x - coverX;
coverH = self.currP.y - coverY;
// 显示遮盖层
self.coverView.frame = CGRectMake(coverX, coverY, coverW, coverH);
NSLog(@"%@", NSStringFromCGRect(CGRectMake(coverX, coverY, coverW, coverH)));
} else if(panGest.state == UIGestureRecognizerStateEnded) {
// 开起一个位图上下文
UIGraphicsBeginImageContextWithOptions(self.imageView.bounds.size,NO,0.0);
CGContextRef ctx = UIGraphicsGetCurrentContext();
// 设置一个截取path
UIBezierPath *path = [UIBezierPath bezierPathWithRect:self.coverView.frame];
[path addClip];
// 把imageview的内容渲染到当前上下文
[self.imageView.layer renderInContext:ctx];
// 生成新图片
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndPDFContext();
self.imageView.image = newImage;
[self.coverView removeFromSuperview];
}
}
@end
网友评论