支持手势改变裁剪区域
接下来就是动态裁剪图片的核心内容了,其实原理也很简单,只要在上面的移动手势处理函数中,进行一些判断,决定是移动图片位置还是改变裁剪区域,也就是自定义的 CAShapeLayer 的绘制方框的尺寸就可以了。
首先我们定义一个枚举,用来表示当前应当操作的是图片还是裁剪区域的边线
typedef NS_ENUM(NSInteger, ACTIVEGESTUREVIEW) {
CROPVIEWLEFT,
CROPVIEWRIGHT,
CROPVIEWTOP,
CROPVIEWBOTTOM,
BIGIMAGEVIEW
};
它们分别表示触发对象为裁剪区域左边线、右边线、上边线、下边线以及 UIImageView
然后我们定义一个枚举属性
@property(assign, nonatomic) ACTIVEGESTUREVIEW activeGestureView;
判断操作对象的标准是当前的手势所触发的位置是在边线上还是在非边线上,因此我们需要知道手势触发时的坐标,要知道这一点就需要我们继承一个 UIPanGestureRecognizer 并覆写一些方法
@interface YasicPanGestureRecognizer : UIPanGestureRecognizer
@property(assign, nonatomic) CGPoint beginPoint;
@property(assign, nonatomic) CGPoint movePoint;
-(instancetype)initWithTarget:(id)target action:(SEL)action inview:(UIView*)view;
@end
@interface YasicPanGestureRecognizer()
@property(strong, nonatomic) UIView *targetView;
@end
@implementation YasicPanGestureRecognizer
-(instancetype)initWithTarget:(id)target action:(SEL)action inview:(UIView*)view{
self = [super initWithTarget:target action:action];
if(self) {
self.targetView = view;
}
return self;
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent*)event{
[super touchesBegan:touches withEvent:event];
UITouch *touch = [touches anyObject];
self.beginPoint = [touch locationInView:self.targetView];
}
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
[super touchesMoved:touches withEvent:event];
UITouch *touch = [touches anyObject];
self.movePoint = [touch locationInView:self.targetView];
}
@end
可以看到,我们首先传入了一个 view,用于将手势触发的位置转换为 view 中的坐标值。在 - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent*)event{ 方法中我们得到了手势开始时的触发点 beginPoint,在 - (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event 方法中我们获得了手势进行时的触发点 movePoint。
自定义完 UIPanGestureRecognizer 后我们将其加到 cropview 上并把 cropview 作为参数传给 UIPanGestureRecognizer
// 拖动手势
YasicPanGestureRecognizer *panGesture = [[YasicPanGestureRecognizer alloc] initWithTarget:self action:@selector(handleDynamicPanGesture:) inview:self.cropView];
[self.cropView addGestureRecognizer:panGesture];
接下来就是处理手势的函数,这里我们可以将整个过程分为三个步骤,开始时 -> 进行时 -> 结束时。










