功能:任意一张图片,通过触摸屏幕,可以剪切任意大小的子图片。
思路:1.用手势+重绘图片实现;
2.手势控制截图的区域,重绘设置裁剪区域和生成图片。
主要代码如下(这是手势出发的方法实现):
- (void)panGestureAction:(UIPanGestureRecognizer *)pan
{
CGPoint currentPoint = [pan locationInView:self.view];
if (pan.state == UIGestureRecognizerStateBegan)
{
self.startPoint = currentPoint;
}else if (pan.state == UIGestureRecognizerStateChanged)
{
CGPoint point = [pan locationInView:self.view];
CGFloat width = fabs(self.startPoint.x - point.x);
CGFloat height = fabs(self.startPoint.y - point.y);
self.coverView.frame = CGRectMake(self.startPoint.x, self.startPoint.y, width, height);
}else if (pan.state == UIGestureRecognizerStateEnded){
//1.生成一个与原来图片一样大的图片
UIGraphicsBeginImageContextWithOptions(self.baseImageView.bounds.size, NO, 1);
//2.设置剪裁区
UIBezierPath *clipath = [UIBezierPath bezierPathWithRect:self.coverView.frame];
[clipath addClip];
//3.渲染当前图片
CGContextRef ctx = UIGraphicsGetCurrentContext();
[self.baseImageView.layer renderInContext:ctx];
//4.获取新图片
UIImage *currentImage = UIGraphicsGetImageFromCurrentImageContext();
//5.关闭上下文
UIGraphicsEndImageContext();
//6.重新设置图片
self.baseImageView.image = currentImage;
//7.移除浮层
[self.coverView removeFromSuperview];
self.coverView = nil;
}
}