Skip to content

Instantly share code, notes, and snippets.

@carlj
Last active December 21, 2015 03:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save carlj/6240213 to your computer and use it in GitHub Desktop.
Save carlj/6240213 to your computer and use it in GitHub Desktop.
ScroolView Zoom
//
// ZoomView.m
// ZoomView
//
// Created by Carl Jahn on 15.08.13.
// Copyright (c) 2013 Carl Jahn. All rights reserved.
//
#import "ZoomView.h"
@interface ZoomView ()<UIScrollViewDelegate>
@property (nonatomic, strong) UIImageView *imageView;
@property (nonatomic, strong) UIScrollView *scrollView;
@end
@implementation ZoomView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
[self generateGUI];
}
return self;
}
- (void)generateGUI {
self.scrollView = [[UIScrollView alloc] initWithFrame: self.bounds];
self.scrollView.delegate = self;
self.scrollView.showsHorizontalScrollIndicator = NO;
self.scrollView.showsVerticalScrollIndicator = NO;
self.scrollView.maximumZoomScale = 4.0;
[self addSubview: self.scrollView];
self.imageView = [[UIImageView alloc] initWithFrame: self.bounds];
[self.scrollView addSubview: self.imageView];
}
- (void)goForIt {
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
dispatch_async(queue, ^{
NSURL *url = [NSURL URLWithString:@"http://lorempixel.com/1000/500/"];
NSData *data = [NSData dataWithContentsOfURL: url];
UIImage *image = [UIImage imageWithData: data scale:2.0f];
dispatch_sync(dispatch_get_main_queue(), ^{
self.imageView.image = image;
self.imageView.bounds = CGRectMake(0, 0, image.size.width, image.size.height);
CGFloat minimumZoomScale = self.scrollView.frame.size.width / image.size.width;
CGFloat tmpZoomScale = self.scrollView.frame.size.height / image.size.height;
if (tmpZoomScale < minimumZoomScale) {
minimumZoomScale = tmpZoomScale;
}
self.scrollView.contentSize = self.imageView.image.size;
self.scrollView.minimumZoomScale = minimumZoomScale;
self.scrollView.zoomScale = minimumZoomScale;
});
});
}
- (CGRect)centeredFrameForScrollView:(UIScrollView *)scroll andUIView:(UIView *)rView {
CGSize boundsSize = scroll.bounds.size;
CGRect frameToCenter = rView.frame;
frameToCenter.origin = CGPointZero;
// center horizontally
if (frameToCenter.size.width < boundsSize.width) {
frameToCenter.origin.x = (boundsSize.width - frameToCenter.size.width) / 2;
}
// center vertically
if (frameToCenter.size.height < boundsSize.height) {
frameToCenter.origin.y = (boundsSize.height - frameToCenter.size.height) / 2;
}
return frameToCenter;
}
- (void)scrollViewDidZoom:(UIScrollView *)scrollView {
self.imageView.frame = [self centeredFrameForScrollView:scrollView andUIView:self.imageView];
}
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
return self.imageView;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment