放大& amp;使用UIScrollView查看视图

时间:2014-03-24 02:58:09

标签: objective-c uiscrollview zoom

我尝试使用UIScrollView制作一些放大&缩小视图。 它就像第一次点击一样使视图放大3,再一次点击使其再次放大3,然后再点击将其缩小回原始大小。 但我的代码不能正常工作。 这有什么不对? 谢谢,

#import "ViewController.h"

@interface ViewController ()

@property (strong, nonatomic) IBOutlet UIScrollView *myScrollView;
@property (strong, nonatomic) IBOutlet UIImageView *myImageView;


@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    self.myScrollView.delegate = self;

    self.myScrollView.minimumZoomScale = 1;
    self.myScrollView.maximumZoomScale = 8;

    self.myScrollView.scrollEnabled = YES;
    self.myScrollView.showsHorizontalScrollIndicator = YES;
    self.myScrollView.showsHorizontalScrollIndicator = YES;



    UITapGestureRecognizer  *doubleTapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doubleTap:)];

    doubleTapGesture.numberOfTapsRequired = 2;
    self.myImageView.userInteractionEnabled = YES;
    [self.myImageView addGestureRecognizer:doubleTapGesture];




}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



- (void)doubleTap:(UITapGestureRecognizer *)gesture
{

    if (self.myScrollView.zoomScale < self.myScrollView.maximumZoomScale){

        float newScale = self.myScrollView.zoomScale * 3;
        CGRect zoomRect = [self zoomRectForScale:newScale withCenter:[gesture locationInView:gesture.view]];

        [self.myScrollView zoomToRect:zoomRect animated:YES];

    }else{

        [self.myScrollView setZoomScale:1.0 animated:YES];
    }

}

- (CGRect)zoomRectForScale:(float)scale withCenter:(CGPoint)center
{
    CGRect zoomRect;
    zoomRect.size.height = [self.myScrollView frame].size.height * scale;
    zoomRect.size.width =  [self.myScrollView frame].size.width  * scale;

    zoomRect.origin.x = center.x - (zoomRect.size.width / 2.0);
    zoomRect.origin.y = center.y - (zoomRect.size.width / 2.0);

    return zoomRect;


}





#pragma mark - delegate

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    return self.myImageView;
}



@end

1 个答案:

答案 0 :(得分:0)

- (CGRect)zoomRectForScale:(float)scale withCenter:(CGPoint)center
{
    CGRect zoomRect;
    zoomRect.size.height = [self.myScrollView frame].size.height / scale;
    zoomRect.size.width =  [self.myScrollView frame].size.width  / scale;

    zoomRect.origin.x = center.x - (zoomRect.size.width / 2.0);
    zoomRect.origin.y = center.y - (zoomRect.size.width / 2.0);

    return zoomRect;


}