-
Notifications
You must be signed in to change notification settings - Fork 0
/
NIPhotoScrollView.m
505 lines (379 loc) · 19.1 KB
/
NIPhotoScrollView.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
//
// Copyright 2011 Jeff Verkoeyen
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#import "NIPhotoScrollView.h"
#import "NimbusCore.h"
///////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
@implementation NIPhotoScrollView
@synthesize photoIndex = _photoIndex;
@synthesize photoSize = _photoSize;
@synthesize photoDimensions = _photoDimensions;
@synthesize zoomingIsEnabled = _zoomingIsEnabled;
@synthesize zoomingAboveOriginalSizeIsEnabled = _zoomingAboveOriginalSizeIsEnabled;
@synthesize photoScrollViewDelegate = _photoScrollViewDelegate;
///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)dealloc {
NI_RELEASE_SAFELY(_doubleTapGestureRecognizer);
[super dealloc];
}
///////////////////////////////////////////////////////////////////////////////////////////////////
- (id)initWithFrame:(CGRect)frame {
if ((self = [super initWithFrame:frame])) {
// Disable the scroll indicators.
self.showsVerticalScrollIndicator = NO;
self.showsHorizontalScrollIndicator = NO;
// Photo viewers should feel sticky when you're panning around, not smooth and slippery
// like a UITableView.
self.decelerationRate = UIScrollViewDecelerationRateFast;
// Ensure that empty areas of the scroll view are draggable.
self.backgroundColor = [UIColor blackColor];
// We implement viewForZoomingInScrollView: and return the image view for zooming.
self.delegate = self;
// Default configuration.
self.zoomingIsEnabled = YES;
self.zoomingAboveOriginalSizeIsEnabled = YES;
self.doubleTapToZoomIsEnabled = YES;
// Autorelease so that we don't have to worry about releasing it in dealloc.
_imageView = [[[UIImageView alloc] initWithFrame:CGRectZero] autorelease];
// Increases the retain count to 1. The image view will be released when this view
// is released.
[self addSubview:_imageView];
}
return self;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
- (CGFloat)scaleForSize:(CGSize)size boundsSize:(CGSize)boundsSize useMinimalScale:(BOOL)minimalScale {
CGFloat xScale = boundsSize.width / size.width; // The scale needed to perfectly fit the image width-wise.
CGFloat yScale = boundsSize.height / size.height; // The scale needed to perfectly fit the image height-wise.
CGFloat minScale = minimalScale ? MIN(xScale, yScale) : MAX(xScale, yScale); // Use the minimum of these to allow the image to become fully visible, or the maximum to get fullscreen size
return minScale;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Calculate the min and max scale for the given dimensions and photo size.
*
* minScale will fit the photo to the bounds, unless it is too small in which case it will
* show the image at a 1-to-1 resolution.
*
* maxScale will be whatever value shows the image at a 1-to-1 resolution, UNLESS
* isZoomingAboveOriginalSizeEnabled is enabled, in which case maxScale will be calculated
* such that the image completely fills the bounds.
*
* Exception: If the photo size is unknown (this is a loading image, for example) then
* the minimum scale will be set without considering the screen scale. This allows the
* loading image to draw with its own image scale if it's a high-res @2x image.
*/
- (void)minAndMaxScaleForDimensions: (CGSize)dimensions
boundsSize: (CGSize)boundsSize
photoSize: (NIPhotoScrollViewPhotoSize)photoSize
minScale: (CGFloat *)pMinScale
maxScale: (CGFloat *)pMaxScale {
NIDASSERT(nil != pMinScale);
NIDASSERT(nil != pMaxScale);
if (nil == pMinScale
|| nil == pMaxScale) {
return;
}
CGFloat minScale = [self scaleForSize: dimensions
boundsSize: boundsSize
useMinimalScale: YES];
// On high resolution screens we have double the pixel density, so we will be seeing
// every pixel if we limit the maximum zoom scale to 0.5.
// If the photo size is unknown, it's likely that we're showing the loading image and
// don't want to shrink it down with the zoom because it should be a scaled image.
CGFloat maxScale = ((NIPhotoScrollViewPhotoSizeUnknown == photoSize)
? 1
: (1.0f / NIScreenScale()));
if (NIPhotoScrollViewPhotoSizeThumbnail != photoSize) {
// Don't let minScale exceed maxScale. (If the image is smaller than the screen, we
// don't want to force it to be zoomed.)
minScale = MIN(minScale, maxScale);
}
// At this point if the image is small, then minScale and maxScale will be the same because
// we don't want to allow the photo to be zoomed.
// If zooming above the original size IS enabled, however, expand the max zoom to
// whatever value would make the image fit the view perfectly.
if ([self isZoomingAboveOriginalSizeEnabled]) {
CGFloat idealMaxScale = [self scaleForSize: dimensions
boundsSize: boundsSize
useMinimalScale: NO];
maxScale = MAX(maxScale, idealMaxScale);
}
*pMinScale = minScale;
*pMaxScale = maxScale;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)setMaxMinZoomScalesForCurrentBounds {
CGSize imageSize = _imageView.bounds.size;
// Avoid crashing if the image has no dimensions.
NIDASSERT(imageSize.width > 0 && imageSize.height > 0);
if (imageSize.width <= 0 || imageSize.height <= 0) {
self.maximumZoomScale = 1;
self.minimumZoomScale = 1;
return;
}
// The following code is from Apple's ImageScrollView example application and has been used
// here because it is well-documented and concise.
CGSize boundsSize = self.bounds.size;
CGFloat minScale = 0;
CGFloat maxScale = 0;
// Calculate the min/max scale for the image to be presented.
[self minAndMaxScaleForDimensions: imageSize
boundsSize: boundsSize
photoSize: self.photoSize
minScale: &minScale
maxScale: &maxScale];
// When we show thumbnails for images that are too small for the bounds, we try to use
// the known photo dimensions to scale the minimum scale to match what the final image
// would be. This avoids any "snapping" effects from stretching the thumbnail too large.
if ((NIPhotoScrollViewPhotoSizeThumbnail == self.photoSize)
&& !CGSizeEqualToSize(self.photoDimensions, CGSizeZero)) {
CGFloat scaleToFitOriginal = 0;
CGFloat originalMaxScale = 0;
// Calculate the original-sized image's min/max scale.
[self minAndMaxScaleForDimensions: self.photoDimensions
boundsSize: boundsSize
photoSize: NIPhotoScrollViewPhotoSizeOriginal
minScale: &scaleToFitOriginal
maxScale: &originalMaxScale];
if (scaleToFitOriginal + FLT_EPSILON >= (1.0 / NIScreenScale())) {
// If the final image will be smaller than the view then we want to use that
// scale as the "true" scale and adjust it relatively to the thumbnail's dimensions.
// This ensures that the thumbnail will always be the same visual size as the original
// image, giving us that sexy "crisping" effect when the thumbnail is loaded.
CGFloat relativeSize = self.photoDimensions.width / imageSize.width;
minScale = scaleToFitOriginal * relativeSize;
}
}
// If zooming is disabled then we flatten the range for zooming to only allow the min zoom.
self.maximumZoomScale = [self isZoomingEnabled] ? maxScale : minScale;
self.minimumZoomScale = minScale;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
#pragma mark UIView
///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)layoutSubviews {
[super layoutSubviews];
// Center the image as it becomes smaller than the size of the screen.
CGSize boundsSize = self.bounds.size;
CGRect frameToCenter = _imageView.frame;
// Center horizontally.
if (frameToCenter.size.width < boundsSize.width) {
frameToCenter.origin.x = floorf((boundsSize.width - frameToCenter.size.width) / 2);
} else {
frameToCenter.origin.x = 0;
}
// Center vertically.
if (frameToCenter.size.height < boundsSize.height) {
frameToCenter.origin.y = floorf((boundsSize.height - frameToCenter.size.height) / 2);
} else {
frameToCenter.origin.y = 0;
}
_imageView.frame = frameToCenter;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
#pragma mark UIScrollView
///////////////////////////////////////////////////////////////////////////////////////////////////
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
return _imageView;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
#pragma mark Gesture Recognizers
///////////////////////////////////////////////////////////////////////////////////////////////////
- (CGRect)rectAroundPoint:(CGPoint)point atZoomScale:(CGFloat)zoomScale {
NIDASSERT(zoomScale > 0);
// Define the shape of the zoom rect.
CGSize boundsSize = self.bounds.size;
// Modify the size according to the requested zoom level.
// For example, if we're zooming in to 0.5 zoom, then this will increase the bounds size
// by a factor of two.
CGSize scaledBoundsSize = CGSizeMake(boundsSize.width / zoomScale,
boundsSize.height / zoomScale);
CGRect rect = CGRectMake(point.x - scaledBoundsSize.width / 2,
point.y - scaledBoundsSize.height / 2,
scaledBoundsSize.width,
scaledBoundsSize.height);
// When the image is zoomed out there is a bit of empty space around the image due
// to the fact that it's centered on the screen. When we created the rect around the
// point we need to take this "space" into account.
// 1: get the frame of the image in this view's coordinates.
CGRect imageScaledFrame = [self convertRect:_imageView.frame toView:self];
// 2: Offset the frame by the excess amount. This will ensure that the zoomed location
// is always centered on the tap location. We only allow positive values because a
// negative value implies that there isn't actually any offset.
rect = CGRectOffset(rect, -MAX(0, imageScaledFrame.origin.x), -MAX(0, imageScaledFrame.origin.y));
return rect;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)didDoubleTap:(UITapGestureRecognizer *)tapGesture {
BOOL isCompletelyZoomedIn = (self.maximumZoomScale <= self.zoomScale + FLT_EPSILON);
BOOL didZoomIn;
if (isCompletelyZoomedIn) {
// Zoom the photo back out.
[self setZoomScale:self.minimumZoomScale animated:YES];
didZoomIn = NO;
} else {
// Zoom into the tap point.
CGPoint tapCenter = [tapGesture locationInView:_imageView];
CGRect maxZoomRect = [self rectAroundPoint:tapCenter atZoomScale:self.maximumZoomScale];
[self zoomToRect:maxZoomRect animated:YES];
didZoomIn = YES;
}
if ([self.photoScrollViewDelegate respondsToSelector:
@selector(photoScrollViewDidDoubleTapToZoom:didZoomIn:)]) {
[self.photoScrollViewDelegate photoScrollViewDidDoubleTapToZoom:self didZoomIn:didZoomIn];
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
#pragma mark Public Methods
///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)setImage:(UIImage *)image photoSize:(NIPhotoScrollViewPhotoSize)photoSize {
_imageView.image = image;
[_imageView sizeToFit];
if (nil == image) {
self.photoSize = NIPhotoScrollViewPhotoSizeUnknown;
} else {
self.photoSize = photoSize;
}
// The min/max zoom values assume that the content size is the image size. The max zoom will
// be a value that allows the image to be seen at a 1-to-1 pixel resolution, while the min
// zoom will be small enough to fit the image on the screen perfectly.
if (nil != image) {
self.contentSize = image.size;
}
[self setMaxMinZoomScalesForCurrentBounds];
// Start off with the image fully-visible on the screen.
self.zoomScale = self.minimumZoomScale;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
- (UIImage *)image {
return _imageView.image;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)prepareForReuse {
_imageView.image = nil;
self.photoSize = NIPhotoScrollViewPhotoSizeUnknown;
self.zoomScale = 1;
self.contentSize = self.bounds.size;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)setZoomingIsEnabled:(BOOL)enabled {
_zoomingIsEnabled = enabled;
if (nil != _imageView.image) {
[self setMaxMinZoomScalesForCurrentBounds];
// Fit the image on screen.
self.zoomScale = self.minimumZoomScale;
// Disable zoom bouncing if zooming is disabled, otherwise the view will allow pinching.
self.bouncesZoom = enabled;
} else {
// Reset to the defaults if there is no set image yet.
self.zoomScale = 1;
self.minimumZoomScale = 1;
self.maximumZoomScale = 1;
self.bouncesZoom = NO;
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)setDoubleTapToZoomIsEnabled:(BOOL)enabled {
// Only enable double-tap to zoom if the SDK supports it. This feature only works on
// iOS 3.2 and above.
if (enabled && nil == _doubleTapGestureRecognizer
&& (nil != NIUITapGestureRecognizerClass()
&& [self respondsToSelector:@selector(addGestureRecognizer:)])) {
_doubleTapGestureRecognizer =
[[NIUITapGestureRecognizerClass() alloc] initWithTarget: self
action: @selector(didDoubleTap:)];
// I freaking love gesture recognizers.
[_doubleTapGestureRecognizer setNumberOfTapsRequired:2];
[self addGestureRecognizer:_doubleTapGestureRecognizer];
}
// If the recognizer hasn't been initialized then this will fire on nil and do nothing.
[_doubleTapGestureRecognizer setEnabled:enabled];
}
///////////////////////////////////////////////////////////////////////////////////////////////////
- (BOOL)isDoubleTapToZoomIsEnabled {
// If the gesture recognizer hasn't been created, then _doubleTapGestureRecognizer will be
// nil and so calling isEnabled will return 0.
return [_doubleTapGestureRecognizer isEnabled];
}
///////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Saving/Restoring Offset and Scale
// The following code is from Apple's ImageScrollView example application and has been used
// here because it is well-documented and concise.
///////////////////////////////////////////////////////////////////////////////////////////////////
// Fetch the visual center point of this view in the image view's coordinate space.
- (CGPoint)pointToCenterAfterRotation {
CGPoint boundsCenter = CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds));
return [self convertPoint:boundsCenter toView:_imageView];
}
///////////////////////////////////////////////////////////////////////////////////////////////////
- (CGFloat)scaleToRestoreAfterRotation {
CGFloat contentScale = self.zoomScale;
// If we're at the minimum zoom scale, preserve that by returning 0, which
// will be converted to the minimum allowable scale when the scale is restored.
if (contentScale <= self.minimumZoomScale + FLT_EPSILON) {
contentScale = 0;
}
return contentScale;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
- (CGPoint)maximumContentOffset {
CGSize contentSize = self.contentSize;
CGSize boundsSize = self.bounds.size;
return CGPointMake(contentSize.width - boundsSize.width,
contentSize.height - boundsSize.height);
}
///////////////////////////////////////////////////////////////////////////////////////////////////
- (CGPoint)minimumContentOffset {
return CGPointZero;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)restoreCenterPoint:(CGPoint)oldCenter scale:(CGFloat)oldScale {
// Step 1: restore zoom scale, making sure it is within the allowable range.
self.zoomScale = boundf(oldScale, self.minimumZoomScale, self.maximumZoomScale);
// Step 2: restore center point, making sure it is within the allowable range.
// 2a: convert our desired center point back to the scroll view's coordinate space from the
// image's coordinate space.
CGPoint boundsCenter = [self convertPoint:oldCenter fromView:_imageView];
// 2b: calculate the content offset that would yield that center point
CGPoint offset = CGPointMake(boundsCenter.x - self.bounds.size.width / 2.0f,
boundsCenter.y - self.bounds.size.height / 2.0f);
// 2c: restore offset, adjusted to be within the allowable range
CGPoint maxOffset = [self maximumContentOffset];
CGPoint minOffset = [self minimumContentOffset];
offset.x = boundf(offset.x, minOffset.x, maxOffset.x);
offset.y = boundf(offset.y, minOffset.y, maxOffset.y);
self.contentOffset = offset;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)setFrameAndMaintainZoomAndCenter:(CGRect)frame {
CGPoint restorePoint = [self pointToCenterAfterRotation];
CGFloat restoreScale = [self scaleToRestoreAfterRotation];
self.frame = frame;
[self setMaxMinZoomScalesForCurrentBounds];
[self restoreCenterPoint:restorePoint scale:restoreScale];
}
@end