// // GalleryScrollView.m // FirstLink // // Created by Lemon on 14/12/24. // Copyright (c) 2014年 FirstLink. All rights reserved. // #import "GalleryScrollView.h" @interface GalleryScrollView () @property (nonatomic, strong) UIImageView *imageView; @property (nonatomic, assign) CGRect scaleOriginalRect; @property (nonatomic, assign) CGSize imageSize; @property (nonatomic, assign) CGRect initRect; @end @implementation GalleryScrollView - (id)init { self = [super init]; if (self) { _index = 0; } return self; } - (id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { self.backgroundColor = [UIColor blackColor]; self.showsHorizontalScrollIndicator = NO; self.showsVerticalScrollIndicator = NO; // self.pagingEnabled = YES; self.minimumZoomScale = 1.0; self.bouncesZoom = YES; self.delegate = self; self.userInteractionEnabled = YES; [self addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGalleryImage:)]]; _imageView = [[UIImageView alloc] init]; _imageView.clipsToBounds = YES; _imageView.contentMode = UIViewContentModeScaleAspectFill; [self addSubview:_imageView]; } return self; } - (void)setContentWithFrame:(CGRect)rect initRect:(CGRect)initRect { _imageView.frame = rect; _initRect = initRect; } - (void)setAnimationRect { _imageView.frame = _scaleOriginalRect; } - (void)resetFrame { self.zoomScale = 1.0; _imageView.frame = _initRect; } - (void)setImage:(UIImage *)image { if (image) { _imageView.image = image; _imageSize = image.size; // 判断首先缩放的值 float scaleX = self.frame.size.width / _imageSize.width; float scaleY = self.frame.size.height / _imageSize.height; // 倍数小的,先到边缘 if (scaleX > scaleY) { // Y方向先到边缘 float imageViewWidth = _imageSize.width * scaleY; self.maximumZoomScale = self.frame.size.width / imageViewWidth; _scaleOriginalRect = (CGRect){self.frame.size.width/2 - imageViewWidth/2, 0, imageViewWidth, self.frame.size.height}; } else { // X先到边缘 float imageViewHeight = _imageSize.height * scaleX; self.maximumZoomScale = self.frame.size.height / imageViewHeight; _scaleOriginalRect = (CGRect){0, self.frame.size.height/2 - imageViewHeight/2, self.frame.size.width, imageViewHeight}; } } } #pragma mark - #pragma mark - ScrollView Delegate - (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView { return _imageView; } - (void)scrollViewDidZoom:(UIScrollView *)scrollView { CGSize boundsSize = scrollView.bounds.size; CGRect imageFrame = _imageView.frame; CGSize contentSize = scrollView.contentSize; CGPoint centerPoint = CGPointMake(contentSize.width/2, contentSize.height/2); // center horizontally if (imageFrame.size.width <= boundsSize.width) { centerPoint.x = boundsSize.width/2; } // center vertically if (imageFrame.size.height <= boundsSize.height) { centerPoint.y = boundsSize.height/2; } _imageView.center = centerPoint; } #pragma mark - #pragma mark - Gesture - (IBAction)tapGalleryImage:(id)sender { if (self.touchCallBack) { self.touchCallBack(self, self.index); } } @end