- 头文件
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface ZQImageView : UIImageView
@end
NS_ASSUME_NONNULL_END
- 具体文件
#import "ZQImageView.h"
@interface ZQImageView ()
@property (nonatomic, assign) CGPoint beginPoint;
@property (nonatomic, strong) UIView *clipView;
@end
@implementation ZQImageView
- (UIView *)clipView{
if(_clipView==nil){
_clipView = [[UIView alloc]init];
_clipView.backgroundColor = [UIColor grayColor];
_clipView.alpha = 0.7;
[[self superview] addSubview:_clipView];
}
return _clipView;
}
- (instancetype)initWithFrame:(CGRect)frame{
if(self = [super initWithFrame: frame]){
self.userInteractionEnabled = YES;
UIPanGestureRecognizer *gestureRecognizer = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(gestureRecognizer:)];
[self addGestureRecognizer:gestureRecognizer];
}
return self;
}
-(void)gestureRecognizer:(UIPanGestureRecognizer*)pan{
CGPoint cur = [pan locationInView:self];
if(pan.state == UIGestureRecognizerStateBegan){
self.beginPoint = cur;
}
if(pan.state == UIGestureRecognizerStateChanged){
CGFloat x = self.beginPoint.x;
CGFloat y = self.beginPoint.y;
CGFloat w = cur.x - self.beginPoint.x;
CGFloat H = cur.y - self.beginPoint.y;
self.clipView.frame = CGRectMake(x, y, w, H);
}
if(pan.state == UIGestureRecognizerStateEnded){
UIGraphicsBeginImageContextWithOptions(self.bounds.size, NO, 0);
UIBezierPath *path = [UIBezierPath bezierPathWithRect:self.clipView.frame];
[path addClip];
CGContextRef ctx = UIGraphicsGetCurrentContext();
[self.layer renderInContext:ctx];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
self.image = newImage;
[self.clipView removeFromSuperview];
self.clipView = nil;
}
}
@end