ScrollView图片的放大缩小

新建一个ZoomScrollView类,将.h和.m代码复制后,直接在新类中可以直接引用

1
#import <UIKit/UIKit.h> 2 3 @interface ZoomScrollView : UIScrollView<UIScrollViewDelegate> 4 @property (nonatomic,strong) UIImageView* imageView; 5 @property (nonatomic,assign) BOOL isZoom; 6 @end

.m中

#import "ZoomScrollView.h"
#define ScreenWidth      CGRectGetWidth([UIScreen mainScreen].applicationFrame)
#define ScreenHeight     CGRectGetHeight([UIScreen mainScreen].applicationFrame)

@implementation ZoomScrollView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.delegate=self;
        self.frame=CGRectMake(0, 0, ScreenWidth, ScreenHeight);
        [self initImageView];
        self.isZoom=NO;
        
    }
    return self;
}


-(void)initImageView
{
    self.imageView=[[UIImageView alloc]init];
    self.imageView.frame = CGRectMake(0, 0, ScreenWidth , ScreenHeight );
    //是否能触发手势
    self.imageView.userInteractionEnabled = YES;
    [self addSubview:self.imageView];
    
//设置放大倍数
    self.maximumZoomScale=17;
    //设置是否显示滚动条
    self.showsHorizontalScrollIndicator=NO;
    self.showsVerticalScrollIndicator=NO;
    
    //添加双击手势
    UITapGestureRecognizer* doubleTap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(didDoubleTap:)];
    doubleTap.numberOfTapsRequired=2;
    [self.imageView addGestureRecognizer:doubleTap];
    
}

-(void)didDoubleTap:(UIGestureRecognizer*)gesture
{
    
    if (self.isZoom)
    {
        [self setZoomScale:1 animated:YES];
        self.isZoom = NO;
    }
    else
    {
        [self setZoomScale:3 animated:YES];
        self.isZoom = YES;
    }
    
}
                                       
#pragma mark - UIScrollViewDelegate
-(UIView*)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    return self.imageView;
}

-(void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(float)scale
{
    [self setZoomScale:scale animated:YES];
    
}

@end

在一个新建的ViewController类中引用

- (void)viewDidLoad
{
    [super viewDidLoad];

    ZoomScrollView* abc=[[ZoomScrollView alloc]initWithFrame:CGRectMake(0, 0, 320, 480)];
    abc.imageView.image=[UIImage imageNamed:@"1.png"];    
    [self.view addSubview:abc];
}
原文地址:https://www.cnblogs.com/shaonian/p/3016977.html