//
//  SingleScrollView.m
//  PhotoWallDemo
//
//  Created by LZXuan on 14-8-18.
//  Copyright (c) 2014年 LZXuan. All rights reserved.
//

#import "SingleScrollView.h"
#import "UIImageView+WebCache.h"
#define SW  1

@interface SingleScrollView()<UIScrollViewDelegate>

@end
@implementation SingleScrollView {
    UIImageView *_imageView;
}

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self setUpViews];
    }
    return self;
}

- (SingleScrollView *)initWithFrame:(CGRect)frame image:(NSString *)image{
    if (self = [super initWithFrame:frame]) {
        [self setUpViews];
        [self setImage:image placeHolder:nil];
    }
    return self;
}

- (void)setUpViews {
    self.delegate = self;
    self.showsHorizontalScrollIndicator = NO;
    self.showsVerticalScrollIndicator = NO;
    //设置最大放大倍数
    self.minimumZoomScale = 1.0;
    self.maximumZoomScale = 2.0;
    //粘贴一张图片
    _imageView = [[UIImageView alloc] init];
    _imageView.frame = CGRectMake(0, 0, self.frame.size.width - 10*2, self.frame.size.height);
    _imageView.center = CGPointMake(self.frame.size.width/2, self.frame.size.height/2);
    _imageView.contentMode = UIViewContentModeScaleAspectFit;
    UITapGestureRecognizer *doubleTapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleDoubleTap:)];
    [doubleTapGesture setNumberOfTapsRequired:2];
    [_imageView addGestureRecognizer:doubleTapGesture];
    _imageView.userInteractionEnabled = YES;
    [self addSubview:_imageView];
}

- (void)setImage:(NSString *)image placeHolder:(UIImage *)placeHolder{
    //每次重新设置图片的时候设置缩放比例（场景是在做相册的时候）
    self.zoomScale = 1.0;
    if ([image hasPrefix:@"http://"]) {
        NSURL *url = [NSURL URLWithString:image];
        [_imageView sd_setImageWithURL:url placeholderImage:placeHolder];
    }else{
        _imageView.image=[UIImage imageNamed:image];
    }
}

//双击定点缩放
- (void)handleDoubleTap:(UIGestureRecognizer *)gesture {
    CGFloat zoomScale = self.zoomScale;
    zoomScale = (zoomScale == 1.0) ? 2.0 : 1.0;
    CGRect zoomRect = [self zoomRectForScale:zoomScale withCenter:[gesture locationInView:gesture.view]];
    [self zoomToRect:zoomRect animated:YES];
}

- (CGRect)zoomRectForScale:(float)scale withCenter:(CGPoint)center {
    CGRect zoomRect;
    zoomRect.size.height = self.frame.size.height / scale;
    zoomRect.size.width  = self.frame.size.width  / scale;
    zoomRect.origin.x = center.x - (zoomRect.size.width  /2.0);
    zoomRect.origin.y = center.y - (zoomRect.size.height /2.0);
    return zoomRect;
}

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
    return _imageView;
}



@end
