-
Notifications
You must be signed in to change notification settings - Fork 61
/
SWSnapshotStackView.m
558 lines (455 loc) · 22 KB
/
SWSnapshotStackView.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
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
////////////////////////////////////////////////////////////////////////////
/*!
** \file SWSnapshotStackView.m
** \brief Snapshot Stack Image View class implementation file
** \author Scott White (support@scottwhite.id.au, http://github.com/snwau)
**
** Snapshot Stack View provides an easy means of decorating your UIImage's
** of any aspect ratio with a rendered matte frame and associated drop
** shadow. It also may render your image to look as though it is the top
** photograph (or snapshot) within a stack of shots.
**
** Copyright (c) 2012 Scott White. All rights reserved.
**
** Permission is hereby granted, free of charge, to any person obtaining a
** copy of this software and associated documentation files (the "Software"),
** to deal in the Software without restriction, including without limitation
** the rights to use, copy, modify, merge, publish, distribute, sublicense,
** and/or sell copies of the Software, and to permit persons to whom the
** Software is furnished to do so, subject to the following conditions:
**
** The above copyright notice and this permission notice shall be included
** in all copies or substantial portions of the Software.
**
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
** OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
** SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
**
** MIT License, see <http://www.opensource.org/licenses/MIT/>.
**
** \see SWSnapshotStackView.h
*/
// Documentation of the code is formatted for use with the documentation
// package Doxygen (see http://www.doxygen.org/).
//
// Project : iOS Common Components
// Component : GUI/Views
// Platform : iOS SDK 3.1+
//
////////////////////////////////////////////////////////////////////////////
#import "SWSnapshotStackView.h"
// ********************************************************************** //
// SNAPSHOT STACK VIEW CLASS (PRIVATE METHODS)
// ********************************************************************** //
#pragma mark Snapshot Stack View class (Private Interface)
@interface SWSnapshotStackView (Private)
//! Perform common initialisation activities
- (void)commonInitialisation;
//! Calculate the scaling required to fit the rotated snapshots in views frame
- (void)calculateScalingToFitStack;
@end
// ********************************************************************** //
// SNAPSHOT STACK VIEW CLASS
// ********************************************************************** //
#pragma mark - Snapshot Stack View class
@implementation SWSnapshotStackView
// ********************************************************************** //
// CONSTANTS
#pragma mark Constants
//! Defines the width of the matte border around a snapshot (each side)
#define SWSnapshotStackViewMatteWidth 7.0
// SINGLE DISPLAY MODE CONSTANTS
//! Defines X offset for either edge to indent shadow effect (single mode)
#define SWSnapshotStackViewSingleShadowXOffset 5.0
//! Defines Y offset to drop shadow below snapshot matte frame
#define SWSnapshotStackViewSingleShadowYOffset 5.0
//! Defines radius of the shadow (results in magnitude and softness of shadow)
#define SWSnapshotStackViewSingleShadowRadius 5.0
#define SWSnapshotStackViewSingleShadowTotalHeight (SWSnapshotStackViewSingleShadowYOffset + SWSnapshotStackViewSingleShadowRadius)
// STACK DISPLAY MODE CONSTANTS
//! Defines Y offset to drop shadow below snapshot matte frame
#define SWSnapshotStackViewStackShadowYOffset 2.0
//! Defines radius of the shadow (results in magnitude and softness of shadow)
#define SWSnapshotStackViewStackShadowRadius 6.0
#define SWSnapshotStackViewStackShadowTotalHeight ((2 * SWSnapshotStackViewStackShadowRadius) - SWSnapshotStackViewStackShadowYOffset)
// ********************************************************************** //
// PROPERTIES
#pragma mark Properties
@dynamic image;
@dynamic displayAsStack;
// ********************************************************************** //
// DYNAMIC PROPERTY METHODS
#pragma mark Dynamic Property Methods
- (UIImage *)image
{
return (m_image);
}
- (void)setImage:(UIImage *)image
{
// Release previous image, assign and retain new image
[m_image release];
m_image = [image retain];
// If an image is provided, perform some pre-calculations to assist
// drawing that remain constant for a given image
if (nil != m_image)
{
// Calculate the image aspect ratio, used to determine aspect of
// image (landscape, square, portrait) which determines the larger
// dimension required for calculating required scaling
m_imageAspect = m_image.size.width / m_image.size.height;
// When display mode is Stack, rotation of snapshot/image rectangles
// changes dimensions of bounding rectangle, perform calculations to
// discover largest bounding rectangle requiring most scaling
if (YES == m_displayStack)
{
[self calculateScalingToFitStack];
}
}
// Image has change, redraw the view
[self setNeedsDisplay];
}
// ********************************************************************** //
- (BOOL)displayAsStack
{
return (m_displayStack);
}
- (void)setDisplayAsStack:(BOOL)displayAsStack
{
// Take action only if the requested display mode is differs from current
if (displayAsStack != m_displayStack)
{
m_displayStack = displayAsStack;
// Rotation of snapshot/image rectangles changes dimensions of bounding
// rectangle, perform calculations to discover largest bounding rectangle
// requiring most scaling
if ((YES == m_displayStack) && (nil != m_image))
{
[self calculateScalingToFitStack];
}
// Display mode has changed, redraw the view
[self setNeedsDisplay];
}
}
// ********************************************************************** //
// INSTANCE METHODS
#pragma mark Instance Methods
- (id)initWithFrame:(CGRect)frame
{
if (nil != (self = [super initWithFrame:frame]))
{
[self commonInitialisation];
}
return (self);
}
// ********************************************************************** //
- (void)awakeFromNib
{
[super awakeFromNib];
[self commonInitialisation];
}
// ********************************************************************** //
// METHOD: commonInitialisation
/*!
Perform initialisation activities common to all forms of instantiation;
programatically via initWithFrame: or from XIB instantiation via
awakeFromNib: method.
*/
- (void)commonInitialisation
{
// Initialise the positions of all snapshots in a stack
// Offsetting centre of snapshots about the view frame centre is
// reserved for future functionality and currently the rotations are
// static, may be optionally randomised in future updates.
/*
for (NSInteger idx = 0; idx < SWSnapshotStackViewSnapshotsPerStack; idx++)
{
m_snapshotPositions[idx].centre = CGPointMake (x,y);
}
*/
m_snapshotPositions[0].angleRotation = 2.5; // 2.0 // 3.0
m_snapshotPositions[1].angleRotation = -3.0; // 4.0 // -5.0
// Top most shot must always have zero rotation
m_snapshotPositions[2].angleRotation = 0.0;
// View's background is transparent underneath the rendered snapshot(s)
self.backgroundColor = [UIColor clearColor];
// Check system (iOS) version, invert sign of shadow direction when
// running on iOS <3.2
m_shadowDirSign = 1.0;
if (NSOrderedAscending == [[[UIDevice currentDevice] systemVersion] compare:@"3.2" options:NSNumericSearch])
{
m_shadowDirSign = -1.0;
}
}
// ********************************************************************** //
- (void)dealloc
{
[m_image release], m_image = nil;
[super dealloc];
}
// ********************************************************************** //
- (void)drawRect:(CGRect)rect
{
// Do nothing if no image is available to display
if (nil == m_image)
{
return;
}
CGContextRef context = UIGraphicsGetCurrentContext ();
CGPoint viewCenter =
CGPointMake (CGRectGetMidX (self.bounds), CGRectGetMidY (self.bounds));
// Initialise to shut static analyser up, gets confused by stacked display
// mode processing 'for' loop and conditional 'if (0 == angle of rotation)'
// where this is initialised for stacked display mode (last snapshot ALWAYS
// zero rotation)
CGRect matteFrameRect = rect;
// Set fill & stroke colour and stroke line width for rendering of the
// matte frame around snapshots
UIColor *colour = [UIColor whiteColor];
[colour setFill];
colour = [UIColor grayColor];
[colour setStroke];
CGContextSetLineWidth (context, 1.0);
CGFloat MatteWidthTotal = 2.0 * SWSnapshotStackViewMatteWidth;
if (NO == m_displayStack)
{
// SINGLE SNAPSHOT DISPLAY MODE
CGSize scaledImageSize;
// Calculate required scaling of image to fit within the views frame,
// leaving room for matte frame and shadow. As the views frame may
// have differing aspect ratio to image, scaling factors must be
// calculated for each dimension and the dimension requiring the
// most scaling is used to determine the resulting scaled image size
CGFloat targetWidth = self.frame.size.width - MatteWidthTotal;
CGFloat requiredWidthScaling = targetWidth / self.image.size.width;
CGFloat targetHeight = self.frame.size.height - MatteWidthTotal - SWSnapshotStackViewSingleShadowTotalHeight;
CGFloat requiredHeightScaling = targetHeight / self.image.size.height;
if (requiredWidthScaling <= requiredHeightScaling)
{
scaledImageSize = CGSizeMake (targetWidth, targetWidth / m_imageAspect);
}
else
{
scaledImageSize = CGSizeMake (targetHeight * m_imageAspect, targetHeight);
}
// Create the matte frame rectangle
matteFrameRect = CGRectMake (floorf (viewCenter.x - ((scaledImageSize.width / 2.0) + SWSnapshotStackViewMatteWidth)) + 0.5,
floorf (viewCenter.y - ((scaledImageSize.height / 2.0) + SWSnapshotStackViewMatteWidth + (SWSnapshotStackViewSingleShadowTotalHeight / 2.0))) + 0.5,
floorf (scaledImageSize.width + MatteWidthTotal) - 1.0,
floorf (scaledImageSize.height + MatteWidthTotal) - 1.0);
CGContextSaveGState (context);
// Render the curved drop shadow, path is defined from top left hand
// corner in a clockwise direction
CGMutablePathRef shadowPath = CGPathCreateMutable ();
CGPathMoveToPoint (shadowPath, NULL,
matteFrameRect.origin.x + SWSnapshotStackViewSingleShadowXOffset,
matteFrameRect.origin.y + matteFrameRect.size.height - SWSnapshotStackViewSingleShadowTotalHeight);
CGPathAddLineToPoint (shadowPath, NULL,
matteFrameRect.origin.x + matteFrameRect.size.width - SWSnapshotStackViewSingleShadowXOffset,
matteFrameRect.origin.y + matteFrameRect.size.height - SWSnapshotStackViewSingleShadowTotalHeight);
CGPathAddLineToPoint (shadowPath, NULL,
matteFrameRect.origin.x + matteFrameRect.size.width - SWSnapshotStackViewSingleShadowXOffset,
matteFrameRect.origin.y + matteFrameRect.size.height);
CGPathAddQuadCurveToPoint (shadowPath, NULL,
(matteFrameRect.origin.x + matteFrameRect.size.width) / 2.0,
matteFrameRect.origin.y + matteFrameRect.size.height - SWSnapshotStackViewSingleShadowTotalHeight,
matteFrameRect.origin.x + SWSnapshotStackViewSingleShadowXOffset,
matteFrameRect.origin.y + matteFrameRect.size.height);
CGPathCloseSubpath (shadowPath);
// Draw the shadow using it's calculated path
colour = [UIColor colorWithRed:0 green:0 blue:0.0 alpha:0.6];
CGContextSetShadowWithColor (context, CGSizeMake (0, (SWSnapshotStackViewSingleShadowYOffset * m_shadowDirSign)),
SWSnapshotStackViewSingleShadowRadius, colour.CGColor);
CGContextAddPath (context, shadowPath);
CGContextFillPath (context);
CGPathRelease (shadowPath);
CGContextRestoreGState (context);
// Draw the matte frame
CGPathRef matteFramePath = CGPathCreateWithRect (matteFrameRect, NULL);
CGContextAddPath (context, matteFramePath);
CGContextDrawPath (context, kCGPathFillStroke);
CGPathRelease (matteFramePath);
}
else
{
// STACK DISPLAY MODE
// Using the snapshot within the stack of rotated snapshots which
// has the largest bounding rectangle (calculated via
// calculateScalingToFitStack:) determine the required scaling to
// fit the snapshot within the views frame, leaving room for shadows
CGFloat requiredScaling;
if (YES == m_scaledUsingWidth)
{
requiredScaling = (self.frame.size.width - 1 - SWSnapshotStackViewStackShadowTotalHeight) /
m_snapshotPositions[m_minScaleShotIdx].boundingRectSize.width;
}
else
{
requiredScaling = (self.frame.size.height - 1 - SWSnapshotStackViewStackShadowTotalHeight) /
m_snapshotPositions[m_minScaleShotIdx].boundingRectSize.height;
}
CGSize matteSize = CGSizeMake (m_image.size.width * requiredScaling,
m_image.size.height * requiredScaling);
// Draw each snapshot in the stack
for (NSInteger shotIdx = 0; shotIdx < SWSnapshotStackViewSnapshotsPerStack; shotIdx++)
{
CGContextSaveGState (context);
CGMutablePathRef matteFramePath = CGPathCreateMutable ();
CGFloat angleRotation = (m_snapshotPositions[shotIdx].angleRotation) * (M_PI / 180.0);
// snapshots containing no rotation don't require the complex
// drawing of rotated rectangles
if (0.0 == angleRotation)
{
matteFrameRect =
CGRectMake (floorf (viewCenter.x - (matteSize.width / 2.0)) + 0.5,
floorf (viewCenter.y - (matteSize.height / 2.0)) + 0.5,
floorf (matteSize.width), floorf (matteSize.height));
CGPathAddRect (matteFramePath, NULL, matteFrameRect);
}
else
{
// Points define rectangle from top-left corner in clockwise direction
CGPoint P1;
CGPoint P2;
CGPoint P3;
CGPoint P4;
// Scale the bounding rectangle that contains the rotated snapshot
// rectangle by the calculated required scaling factor
CGSize scaledBoudingRectSize = CGSizeMake ((m_snapshotPositions[shotIdx].boundingRectSize.width * requiredScaling),
(m_snapshotPositions[shotIdx].boundingRectSize.height * requiredScaling));
CGFloat halfScaledBoundingRectWidth = (scaledBoudingRectSize.width / 2.0);
CGFloat halfScaledBoundingRectHeight = (scaledBoudingRectSize.height / 2.0);
CGFloat adjacentOnXAxis = scaledBoudingRectSize.height * sin (angleRotation);
CGFloat adjacentOnYAxis = scaledBoudingRectSize.width * sin (angleRotation);
// Calculate position of rotated rectangle points P1 to P4,
// using trigonometry and the triangles made by the points against
// the sides of the bounding rectangle
if (angleRotation < 0.0)
{
// Counter-clockwise rotation
P1 = CGPointMake (viewCenter.x - halfScaledBoundingRectWidth,
viewCenter.y - halfScaledBoundingRectHeight - adjacentOnYAxis);
P2 = CGPointMake (viewCenter.x + halfScaledBoundingRectWidth + adjacentOnXAxis,
viewCenter.y - halfScaledBoundingRectHeight);
P3 = CGPointMake (viewCenter.x + halfScaledBoundingRectWidth,
viewCenter.y + halfScaledBoundingRectHeight + adjacentOnYAxis);
P4 = CGPointMake (viewCenter.x - halfScaledBoundingRectWidth - adjacentOnXAxis,
viewCenter.y + halfScaledBoundingRectHeight);
}
else
{
// Clockwise rotation
P1 = CGPointMake (viewCenter.x - halfScaledBoundingRectWidth + adjacentOnXAxis,
viewCenter.y - halfScaledBoundingRectHeight);
P2 = CGPointMake (viewCenter.x + halfScaledBoundingRectWidth,
viewCenter.y - halfScaledBoundingRectHeight + adjacentOnYAxis);
P3 = CGPointMake (viewCenter.x + halfScaledBoundingRectWidth - adjacentOnXAxis,
viewCenter.y + halfScaledBoundingRectHeight);
P4 = CGPointMake (viewCenter.x - halfScaledBoundingRectWidth,
viewCenter.y + halfScaledBoundingRectHeight - adjacentOnYAxis);
}
// Create path to define the matte frame of the rotated snapshot
CGPathMoveToPoint (matteFramePath, NULL, P1.x, P1.y);
CGPathAddLineToPoint (matteFramePath, NULL, P2.x, P2.y);
CGPathAddLineToPoint (matteFramePath, NULL, P3.x, P3.y);
CGPathAddLineToPoint (matteFramePath, NULL, P4.x, P4.y);
CGPathCloseSubpath (matteFramePath);
}
CGContextSaveGState (context);
// Draw the snapshot shadow using the matte frames path, offset
// slightly. Still not 100% happy with the shadow drawing, plan
// to tweak eventually to get better end effect
colour = [UIColor colorWithRed:0 green:0 blue:0.0 alpha:0.4];
CGContextSetShadowWithColor (context, CGSizeMake (0.0, (SWSnapshotStackViewStackShadowYOffset * m_shadowDirSign)),
SWSnapshotStackViewStackShadowRadius, colour.CGColor);
CGContextAddPath (context, matteFramePath);
CGContextFillPath (context);
CGContextRestoreGState (context);
// Draw the matte frame
CGContextAddPath (context, matteFramePath);
CGContextDrawPath (context, kCGPathFillStroke);
CGPathRelease (matteFramePath);
CGContextRestoreGState (context);
}
}
// Calculate frame for the actual image within the top snapshot, centered
// within the already drawn matte frame. Unlike the stroked matte
// frame outline the image must reside on integer point values,
// to avoid aliasing across points/pixels.
// Hence conversion of the matte frame rectangle (calculated to perform
// innser stroke at 0.5 offset) requires subtraction of the offsets and
// increasing size in both dimension by 1 point to compensate.
CGRect imageFrame = matteFrameRect;
imageFrame.origin.x += SWSnapshotStackViewMatteWidth - 0.5;
imageFrame.origin.y += SWSnapshotStackViewMatteWidth - 0.5;
imageFrame.size.width -= MatteWidthTotal - 1;
imageFrame.size.height -= MatteWidthTotal - 1;
// Draw the image without manipulation other than correct scaling,
// could have used CGContextDrawImage() if further drawing required
[m_image drawInRect:imageFrame];
}
// ********************************************************************** //
// METHOD: calculateScalingToFitStack
/*!
Calculates the snapshot within the stack which requires the most
scaling, due to the rotation of the rectangle the points protrude
outside of their original dimensions. Hence a bounding rectangle
must be calculated that contains entirely the rotated rectangle.
The dimensions of the bounding rectangle can then be used to calculate
the required scaling to fit the bounding rectangle within the views
frame.
As the size of the views frame may change at anytime, the outcome
of this method is to store the snapshot in the stack which requires
the most scaling (minimum scaling factor) via it's index
(m_minScaleShotIdx) into the snapshot position array
(m_snapshotPositions) and the dimension (width or height) that
should be used to calculate scaling (m_scaledUsingWidth).
The output of this method remains constant as long as the image
remains constant, re-calculation is required when the image
is changed. Hence avoiding the need to perform these calculations
each time the view is drawn.
*/
- (void)calculateScalingToFitStack
{
CGFloat requiredScaling = 1.0;
for (NSInteger idx = 0; idx < SWSnapshotStackViewSnapshotsPerStack; idx++)
{
// Calculate bounding rectangle of rotated snapshot/image rectangle
// Direction of rotation is not important given symmetry, only aiming
// to calculate size, not location after rotation
CGSize imageSize = m_image.size;
CGFloat angleRotation =
(fabs(m_snapshotPositions[idx].angleRotation) * (M_PI / 180.0));
CGSize boundingRect = CGSizeMake ((imageSize.width * cos (angleRotation)) +
(imageSize.height * sin (angleRotation)),
(imageSize.width * sin (angleRotation)) +
(imageSize.height * cos (angleRotation)));
m_snapshotPositions[idx].boundingRectSize = boundingRect;
// Calculated required scaling for each dimension to fit the bounding
// rectangle within the views frame
CGFloat requiredWidthScaling = self.frame.size.width / boundingRect.width;
CGFloat requiredHeightScaling = self.frame.size.height / boundingRect.height;
// Determine if the scaling required for either dimension is the
// largest (smallest scaling factor) required for any of the snapshots
// processed thus far
if (requiredWidthScaling < requiredScaling)
{
requiredScaling = requiredWidthScaling;
m_minScaleShotIdx = idx;
m_scaledUsingWidth = YES;
}
if (requiredHeightScaling < requiredScaling)
{
requiredScaling = requiredHeightScaling;
m_minScaleShotIdx = idx;
m_scaledUsingWidth = NO;
}
}
}
// ********************************************************************** //
@end // @SWSnapshotStackView
// ********************************************************************** //
// End of File