XKZoomingView.h
#import <UIKit/UIKit.h> @interface XKZoomingView : UIScrollView /** 本地图片 */ @property (nonatomic, strong) UIImage *mainImage; /** 图片显示 */ @property (nonatomic, strong) UIImageView *mainImageView; @end
XKZoomingView.m
#import "XKZoomingView.h" @interface XKZoomingView()<UIScrollViewDelegate> /** 当前图片偏移量 */ @property (nonatomic,assign) CGPoint currPont; @end @implementation XKZoomingView - (instancetype)init{ self = [super init]; if (self) { [self setup]; } return self; } - (instancetype)initWithFrame:(CGRect)frame{ self = [super initWithFrame:frame]; if (self) { [self setup]; } return self; } - (void)setup{ self.backgroundColor = [[UIColor grayColor]colorWithAlphaComponent:0.2]; self.delegate = self; self.showsHorizontalScrollIndicator = NO; self.showsVerticalScrollIndicator = NO; self.decelerationRate = UIScrollViewDecelerationRateFast; self.maximumZoomScale = 3; self.minimumZoomScale = 1; self.alwaysBounceHorizontal = NO; self.alwaysBounceVertical = NO; self.layer.masksToBounds = YES; if (@available(iOS 11.0, *)) { self.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever; } [self addSubview:self.mainImageView]; _currPont = CGPointZero; ///监听屏幕旋转 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarOrientationChange:) name:UIApplicationDidChangeStatusBarOrientationNotification object:nil]; ///单击 UITapGestureRecognizer *tapSingle = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapSingleSponse:)]; //设置手势属性 tapSingle.numberOfTapsRequired = 1; tapSingle.delaysTouchesEnded = NO; [self.mainImageView addGestureRecognizer:tapSingle]; ///双击 UITapGestureRecognizer *tapDouble = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapDoubleSponse:)]; //设置手势属性 tapDouble.numberOfTapsRequired = 2; [self.mainImageView addGestureRecognizer:tapDouble]; ///避免手势冲突 [tapSingle requireGestureRecognizerToFail:tapDouble]; } #pragma mark - layoutSubviews - (void)layoutSubviews{ [super layoutSubviews]; ///放大或缩小中 if (self.zooming || self.zoomScale != 1.0 || self.zoomBouncing) { return; } ///设置图片尺寸 if (_mainImage) { CGRect imgRect = [self getImageViewFrame]; self.mainImageView.frame = imgRect; ///设置content size if (CGRectGetHeight(imgRect) > CGRectGetHeight(self.frame)) { [self setContentSize:CGSizeMake(CGRectGetWidth(self.frame), CGRectGetHeight(imgRect))]; } else{ [self setContentSize:CGSizeMake(CGRectGetWidth(self.frame), CGRectGetHeight(self.frame))]; } } } - (void)setMainImage:(UIImage *)mainImage{ _mainImage = mainImage; self.mainImageView.image = _mainImage; [self setContentOffset:CGPointMake(0, 0)]; [self setNeedsLayout]; } /** 根据图片原始大小,获取图片显示大小 @return CGRect */ - (CGRect)getImageViewFrame{ if (_mainImage) { CGRect imageRect; CGFloat scWidth = self.frame.size.width; CGFloat scHeight = self.frame.size.height; ///width if (_mainImage.size.width > scWidth) { imageRect.size.width = scWidth; CGFloat ratioHW = _mainImage.size.height/_mainImage.size.width; imageRect