iOS圖片瀏覽工具,支持雙擊放大痘括,縮小长窄,拉伸和縮放

圖片瀏覽工具

STImageVIew.h
//
//  STImageVIew.h
//  STPhotoBroeser
//
//  Created by StriEver on 16/3/15.
//  Copyright ? 2016年 StriEver. All rights reserved.
//

#import <UIKit/UIKit.h>
@protocol STImageViewDelegate;
@interface STImageVIew : UIImageView
@property (nonatomic, weak)id<STImageViewDelegate>delegate;
- (void)resetView;
@end
@protocol STImageViewDelegate <NSObject>

- (void)stImageVIewSingleClick:(STImageVIew *)imageView;

@end

STImageVIew.m

//
//  STImageVIew.m
//  STPhotoBroeser
//
//  Created by StriEver on 16/3/15.
//  Copyright ? 2016年 StriEver. All rights reserved.
//

#import "STImageVIew.h"
#import "UIView+Extension.h"
@interface STImageVIew()<UIGestureRecognizerDelegate>{
    CGFloat _lastScale;//記錄最后一次的圖片放大倍數(shù)
}
/**手機屏幕高度不夠用的時候 用于顯示完整圖片*/
@property (nonatomic, strong) UIScrollView * scrollView;
/**完整圖片*/
@property (nonatomic, strong) UIImageView * scrollImgV;
/**用于放大 縮小 圖片的scrollview*/
@property (nonatomic, strong) UIScrollView * scaleScrollView;
/**用于顯示 放大縮小的 圖片*/
@property (nonatomic, strong) UIImageView * scaleImgV;
@property (nonatomic, assign) BOOL doubleAction;
@end
@implementation STImageVIew
- (instancetype)initWithFrame:(CGRect)frame{
    if (self == [super initWithFrame:frame]) {
        self.userInteractionEnabled = YES;
        UIPinchGestureRecognizer * ges = [[UIPinchGestureRecognizer alloc]initWithTarget:self action:@selector(scaleImageViewAction:)];
        ges.delegate = self;
        _lastScale = 1.f;
        [self addGestureRecognizer:ges];
        UITapGestureRecognizer * singleTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(singleClick:)];
        [self addGestureRecognizer:singleTap];
        
        UITapGestureRecognizer * doubleTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(doubleClick:)];
        doubleTap.numberOfTapsRequired = 2;
        [self addGestureRecognizer:doubleTap];
        [singleTap requireGestureRecognizerToFail:doubleTap];
    }
    return self;
}
//getter
- (UIScrollView *)scrollView{
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc]initWithFrame:self.bounds];
        [self addSubview:_scrollView];
    }
    return _scrollView;
}
- (UIImageView *)scrollImgV{
    if (!_scrollImgV) {
        _scrollImgV = [[UIImageView alloc]init];
        _scrollImgV.image = self.image;
        [self.scrollView addSubview:_scrollImgV];
    }
    return _scrollImgV;
}
- (UIScrollView *)scaleScrollView{
    if (!_scaleScrollView) {
        _scaleScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, self.width, self.height)];
        _scaleScrollView.bounces = NO;
        _scaleScrollView.backgroundColor = [UIColor blackColor];
        _scaleScrollView.contentSize =  self.bounds.size;
        [self addSubview:_scaleScrollView];
    }
    return _scaleScrollView;
}
- (UIImageView *)scaleImgV{
    if (!_scaleImgV) {
        _scaleImgV = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.width, self.height)];
        _scaleImgV.image = self.image;
        [self.scaleScrollView addSubview:_scaleImgV];
    }
    return _scaleImgV;
}
- (void)layoutSubviews{
    [super layoutSubviews];
    CGSize imageSize = self.image.size;
    //圖片高度大于屏幕高度
    if (self.width * (imageSize.height / imageSize.width) > self.height) {
        [self scrollView];
        self.scrollView.contentSize = CGSizeMake(self.bounds.size.width, self.width * (imageSize.height / imageSize.width));
        self.scrollImgV.center = self.scrollView.center;
        self.scrollImgV.bounds = CGRectMake(0, 0, imageSize.width, self.width * (imageSize.height / imageSize.width));
    }else{
        if (_scrollView)[_scrollView removeFromSuperview];
    }
    
}
#pragma mark ---action
-(void)scaleImageViewAction:(UIPinchGestureRecognizer*)sender {
    
    CGFloat scale = sender.scale;//得到的是當前手勢放大倍數(shù)
    NSLog(@"--------%f",scale);
    CGFloat shouldScale = _lastScale + (scale - 1);//我們需要知道的是當前手勢相收縮率對于剛才手勢的相對收縮 scale - 1颜启,然后加上最后一次收縮率忠聚,為當前要展示的收縮率
    [self setScaleImageWithScale:shouldScale];
    sender.scale = 1.0;//圖片大小改變后設置手勢scale為1
}
- (void)setScaleImageWithScale:(CGFloat)scale{
    //最大2倍最小.5
    if (scale >=2) {
        scale = 2;
    }else if(scale <=.5){
        scale = .5;
    }
    _lastScale = scale;
    self.scaleImgV.transform = CGAffineTransformMakeScale(scale, scale);
    if (scale > 1) {
        CGFloat imageWidth = self.scaleImgV.width;
        CGFloat imageHeight =  MAX(self.scaleImgV.height, self.frame.size.height);
        [self bringSubviewToFront:self.scaleScrollView];
        self.scaleImgV.center = CGPointMake(imageWidth * 0.5, imageHeight * 0.5);
        self.scaleScrollView.contentSize = CGSizeMake(imageWidth, imageHeight);
        CGPoint offset = self.scaleScrollView.contentOffset;
        offset.x = (imageWidth - self.width)/2.0;
        offset.y = (imageHeight - self.height)/2.0;
        self.scaleScrollView.contentOffset = offset;
    }else{
        self.scaleImgV.center = self.scaleScrollView.center;
        self.scaleScrollView.contentSize = CGSizeZero;
        
    }
}
- (void)singleClick:(UITapGestureRecognizer *)tap{
    if (_delegate &&[_delegate respondsToSelector:@selector(stImageVIewSingleClick:)]) {
        [_delegate stImageVIewSingleClick:self];
    }
}

- (void)doubleClick:(UITapGestureRecognizer *)tap{
    if (_lastScale > 1) {
        _lastScale = 1;
        
    }else{
        _lastScale = 2;
    }
    [UIView animateWithDuration:.5 animations:^{
         [self setScaleImageWithScale:_lastScale];
        
    }completion:^(BOOL finished) {
        if (_lastScale == 1) {
            [self resetView];
        }
    }];
   
}
//當達到原圖大小 清除 放大的圖片 和scrollview
- (void)resetView{
    if (!self.scaleScrollView) {
        return;
    }
    self.scaleScrollView.hidden = YES;
    [self.scaleScrollView removeFromSuperview];
    self.scaleScrollView = nil;
    self.scaleImgV = nil;
}
@end
STPhotoBroswer.h
//
//  STPhotoBroswer.h
//  STPhotoBroeser
//
//  Created by StriEver on 16/3/16.
//  Copyright ? 2016年 StriEver. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface STPhotoBroswer : UIView
/**
 * @brief 初始化方法  圖片以數(shù)組的形式傳入, 需要顯示的當前圖片的索引
 *
 * @param  imageArray需要顯示的圖片以數(shù)組的形式傳入.
 * @param  index 需要顯示的當前圖片的索引
 */
- (instancetype)initWithImageArray:(NSArray *)imageArray currentIndex:(NSInteger)index;
- (void)show;
@end
STPhotoBroswer.m
//
//  ;
//  STPhotoBroeser
//
//  Created by StriEver on 16/3/16.
//  Copyright ? 2016年 StriEver. All rights reserved.
//

#import "STPhotoBroswer.h"
#import "STImageVIew.h"
#define MAIN_BOUNDS   [UIScreen mainScreen].bounds
#define Screen_Width  [UIScreen mainScreen].bounds.size.width
#define Screen_Height [UIScreen mainScreen].bounds.size.height
//圖片距離左右 間距
#define SpaceWidth    10
@interface STPhotoBroswer ()<STImageViewDelegate,UIScrollViewDelegate>
@property (nonatomic, strong) NSArray * imageArray;
@property (nonatomic, assign) NSInteger index;
@property (nonatomic, strong) UIScrollView * scrollView;
@property (nonatomic, strong) UILabel * numberLabel;
@end
@implementation STPhotoBroswer
- (instancetype)initWithImageArray:(NSArray *)imageArray currentIndex:(NSInteger)index{
    if (self == [super init]) {
        self.imageArray = imageArray;
        self.index = index;
        [self setUpView];
    }
    return self;
}
//--getter
- (UIScrollView *)scrollView{
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc]initWithFrame:[UIScreen mainScreen].bounds];
        _scrollView.backgroundColor = [UIColor blackColor];
        _scrollView.delegate = self;
        //這里
        _scrollView.contentSize = CGSizeMake((Screen_Width + 2*SpaceWidth) * self.imageArray.count, Screen_Height);
        _scrollView.contentOffset = CGPointMake(Screen_Width * self.index, 0);
        _scrollView.scrollEnabled = YES;
        _scrollView.pagingEnabled = YES;
        [self addSubview:_scrollView];
        [self numberLabel];
    }
    return _scrollView;
}
- (UILabel *)numberLabel{
    if (!_numberLabel) {
        _numberLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 20, Screen_Width, 40)];
        _numberLabel.textAlignment = NSTextAlignmentCenter;
        _numberLabel.textColor = [UIColor greenColor];
        _numberLabel.text = [NSString stringWithFormat:@"%d/%d",self.index +1,self.imageArray.count];
        [self addSubview:_numberLabel];
    }
    return _numberLabel;
}
- (void)setUpView{
    int index = 0;
    for (UIImage * image in self.imageArray) {
        STImageVIew * imageView = [[STImageVIew alloc]init];
        imageView.delegate = self;
        imageView.image = image;
        imageView.tag = index;
        [self.scrollView addSubview:imageView];
        index ++;
    }
}
#pragma mark ---UIScrollViewDelegate
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    NSInteger index = scrollView.contentOffset.x/Screen_Width;
    self.index = index;
    [self.scrollView.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([NSStringFromClass(obj.class) isEqualToString:@"STImageVIew"]) {
            STImageVIew * imageView = (STImageVIew *) obj;
            [imageView resetView];
        }
                }];
    self.numberLabel.text = [NSString stringWithFormat:@"%d/%d",self.index+1,self.imageArray.count];
}
- (void)layoutSubviews{
    [super layoutSubviews];
    //主要為了設置每個圖片的間距弧关,并且使 圖片鋪滿整個屏幕翰舌,實際上就是scrollview每一頁的寬度是 屏幕寬度+2*Space  居中嚣潜。圖片左邊從每一頁的 Space開始,達到間距且居中效果椅贱。
    _scrollView.bounds = CGRectMake(0, 0, Screen_Width + 2 * SpaceWidth,Screen_Height);
    _scrollView.center = self.center;
    [self.scrollView.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        obj.frame = CGRectMake(SpaceWidth + (Screen_Width+20) * idx, 0,Screen_Width,Screen_Height);
    }];
}
- (void)show{
     UIWindow *window = [UIApplication sharedApplication].keyWindow;
    self.frame = CGRectMake(0, 0, Screen_Width, Screen_Height);
    [window addSubview:self];
    self.transform = CGAffineTransformMakeScale(0, 0);
    [UIView animateWithDuration:.5 animations:^{
        self.transform = CGAffineTransformIdentity;
    }];
}
- (void)dismiss{
     self.transform = CGAffineTransformIdentity;
    [UIView animateWithDuration:.5 animations:^{
        self.transform = CGAffineTransformMakeScale(0.0000000001, 0.00000001);
    }completion:^(BOOL finished) {
         [self removeFromSuperview];
    }];
   
}
#pragma mark ---STImageViewDelegate
- (void)stImageVIewSingleClick:(STImageVIew *)imageView{
    [self dismiss];
}
@end

使用方法

STPhotoBroswer * broser = [[STPhotoBroswer alloc]initWithImageArray:@[[UIImage imageNamed:@"1.jpg"],[UIImage imageNamed:@"2.jpg"],[UIImage imageNamed:@"3.jpg"],[UIImage imageNamed:@"4.jpg"],[UIImage imageNamed:@"5.jpg"],[UIImage imageNamed:@"6.jpg"],[UIImage imageNamed:@"7.jpg"]] currentIndex:0];
    [broser show];
```  最近項目中需要用到這個功能懂算,就抽時間自己動手實現(xiàn)了一下吧。希望和大家共同進步夜涕。
[我的github](https://github.com/strivever/STPhotoBroswer)可以下載一下哦
![4.7.gif](http://upload-images.jianshu.io/upload_images/1663049-71d26cb658505472.gif?imageMogr2/auto-orient/strip)
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末犯犁,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子女器,更是在濱河造成了極大的恐慌,老刑警劉巖住诸,帶你破解...
    沈念sama閱讀 206,482評論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件驾胆,死亡現(xiàn)場離奇詭異,居然都是意外死亡贱呐,警方通過查閱死者的電腦和手機丧诺,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,377評論 2 382
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來奄薇,“玉大人驳阎,你說我怎么就攤上這事。” “怎么了呵晚?”我有些...
    開封第一講書人閱讀 152,762評論 0 342
  • 文/不壞的土叔 我叫張陵蜘腌,是天一觀的道長。 經(jīng)常有香客問我饵隙,道長撮珠,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 55,273評論 1 279
  • 正文 為了忘掉前任金矛,我火速辦了婚禮芯急,結果婚禮上,老公的妹妹穿的比我還像新娘驶俊。我一直安慰自己娶耍,他們只是感情好,可當我...
    茶點故事閱讀 64,289評論 5 373
  • 文/花漫 我一把揭開白布饼酿。 她就那樣靜靜地躺著伺绽,像睡著了一般。 火紅的嫁衣襯著肌膚如雪嗜湃。 梳的紋絲不亂的頭發(fā)上奈应,一...
    開封第一講書人閱讀 49,046評論 1 285
  • 那天,我揣著相機與錄音购披,去河邊找鬼杖挣。 笑死,一個胖子當著我的面吹牛刚陡,可吹牛的內容都是我干的惩妇。 我是一名探鬼主播,決...
    沈念sama閱讀 38,351評論 3 400
  • 文/蒼蘭香墨 我猛地睜開眼筐乳,長吁一口氣:“原來是場噩夢啊……” “哼歌殃!你這毒婦竟也來了?” 一聲冷哼從身側響起蝙云,我...
    開封第一講書人閱讀 36,988評論 0 259
  • 序言:老撾萬榮一對情侶失蹤氓皱,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后勃刨,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體波材,經(jīng)...
    沈念sama閱讀 43,476評論 1 300
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 35,948評論 2 324
  • 正文 我和宋清朗相戀三年身隐,在試婚紗的時候發(fā)現(xiàn)自己被綠了廷区。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 38,064評論 1 333
  • 序言:一個原本活蹦亂跳的男人離奇死亡贾铝,死狀恐怖隙轻,靈堂內的尸體忽然破棺而出埠帕,到底是詐尸還是另有隱情,我是刑警寧澤玖绿,帶...
    沈念sama閱讀 33,712評論 4 323
  • 正文 年R本政府宣布敛瓷,位于F島的核電站,受9級特大地震影響镰矿,放射性物質發(fā)生泄漏琐驴。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 39,261評論 3 307
  • 文/蒙蒙 一秤标、第九天 我趴在偏房一處隱蔽的房頂上張望绝淡。 院中可真熱鬧,春花似錦苍姜、人聲如沸牢酵。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,264評論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽馍乙。三九已至,卻和暖如春垫释,著一層夾襖步出監(jiān)牢的瞬間丝格,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 31,486評論 1 262
  • 我被黑心中介騙來泰國打工棵譬, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留显蝌,地道東北人。 一個月前我還...
    沈念sama閱讀 45,511評論 2 354
  • 正文 我出身青樓订咸,卻偏偏與公主長得像曼尊,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子脏嚷,可洞房花燭夜當晚...
    茶點故事閱讀 42,802評論 2 345

推薦閱讀更多精彩內容