-
Notifications
You must be signed in to change notification settings - Fork 588
/
PARImage+ASCIIInput.m
executable file
·687 lines (571 loc) · 24.9 KB
/
PARImage+ASCIIInput.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
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
// ASCIImage
// Created by Charles Parnot on 5/29/13.
// Copyright (c) 2013 Charles Parnot. All rights reserved.
#import "PARImage+ASCIIInput.h"
NSString * const ASCIIContextShapeIndex = @"ASCIIContextShapeIndex";
NSString * const ASCIIContextFillColor = @"ASCIIContextFillColor";
NSString * const ASCIIContextStrokeColor = @"ASCIIContextStrokeColor";
NSString * const ASCIIContextLineWidth = @"ASCIIContextLineWidth";
NSString * const ASCIIContextShouldClose = @"ASCIIContextShouldClose";
NSString * const ASCIIContextShouldAntialias = @"ASCIIContextShouldAntialias";
#pragma mark - PARImage Cross-Platform Image Class
#if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR
#define PARImage UIImage
#define PARColor UIColor
#define PARBezierPath UIBezierPath
#define NSStringFromPoint(point) (NSStringFromCGPoint(point))
#define PARValueFromPoint(point) ([NSValue valueWithCGPoint:(point)])
#define PARPointFromValue(value) ([value CGPointValue])
#define lineToPoint addLineToPoint
#define NSMiterLineJoinStyle kCGLineJoinMiter
#define NSSquareLineCapStyle kCGLineCapSquare
#elif TARGET_OS_MAC
#define PARImage NSImage
#define PARColor NSColor
#define PARBezierPath NSBezierPath
#define PARValueFromPoint(point) ([NSValue valueWithPoint:(point)])
#define PARPointFromValue(value) ([value pointValue])
#endif
#pragma mark - PARShape
// shape = polygon or ellipse
// a polygon represents an array of pixels, that would eventually be drawn by joining the points in order
@interface PARShape : NSObject
+ (PARShape *)polygonWithPointValues:(NSArray *)pointValues;
+ (PARShape *)ellipseWithPointValues:(NSArray *)pointValues;
@property (readonly) PARBezierPath *bezierPath;
@property (readonly) PARBezierPath *closedBezierPath;
@property (readonly, copy) NSArray *pointValues;
@property (readonly) BOOL ellipse;
@end
#pragma mark - Cross-Platform Methods
@implementation PARImage (ASCIIInput)
#pragma mark - ASCII --> Strict ASCII
+ (NSArray *)strictASCIIRepresentationFromLenientASCIIRepresentation:(NSArray *)lenientRep
{
// empty input
if ([lenientRep count] == 0)
{
NSLog(@"ERROR: empty ASCII shape:\n%@", [lenientRep componentsJoinedByString:@"\n"]);
return nil;
}
// consistent data?
NSSet *counts = [NSSet setWithArray:[lenientRep valueForKey:@"length"]];
if (counts.count != 1)
{
NSLog(@"ERROR: inconsistent line sizes '%@' in ASCII shape:\n%@", [[counts allObjects] componentsJoinedByString:@","], [lenientRep componentsJoinedByString:@"\n"]);
return nil;
}
// empty lines
NSUInteger columnCount = [counts.anyObject unsignedIntegerValue];
if (columnCount == 0)
{
NSLog(@"ERROR: empty lines in ASCII shape:\n%@", [lenientRep componentsJoinedByString:@"\n"]);
return nil;
}
// merge all the strings for easier processing
NSString *concatenatedStrings = [lenientRep componentsJoinedByString:@""];
NSUInteger total = concatenatedStrings.length;
// detect "pixels" = non-space characters
NSMutableIndexSet *pixelColumns = [NSMutableIndexSet indexSet];
NSCharacterSet *nonSpace = [self nonWhitespaceCharacters];
NSRange searchRange = [concatenatedStrings rangeOfCharacterFromSet:nonSpace options:NSLiteralSearch range:NSMakeRange(0, total)];
while (searchRange.location != NSNotFound)
{
[pixelColumns addIndex:(searchRange.location % columnCount)];
NSUInteger newLocation = searchRange.location + 1;
if (newLocation < total)
searchRange = [concatenatedStrings rangeOfCharacterFromSet:nonSpace options:NSLiteralSearch range:NSMakeRange(newLocation, total - newLocation)];
else
break;
}
// gaps between pixels
NSMutableIndexSet *gaps = [NSMutableIndexSet indexSet];
NSUInteger firstColumn = pixelColumns.firstIndex;
NSUInteger currentColumn = firstColumn;
while (currentColumn != NSNotFound)
{
NSUInteger nextColumn = [pixelColumns indexGreaterThanIndex:currentColumn];
if (nextColumn == NSNotFound)
break;
[gaps addIndex:nextColumn -currentColumn];
currentColumn = nextColumn;
}
// pixels should be regularly spaced: the actual gap is the greater common divisor
// no need to make that a fancy algorithm, let's just enumarate all possible values going down, and including, the smallest gap
NSUInteger smallestGap = gaps.firstIndex;
if (smallestGap == NSNotFound)
smallestGap = 1;
NSUInteger pixelGap = 1;
for (NSUInteger i = smallestGap; i > 1; i --)
{
NSUInteger gap = gaps.firstIndex;
while (gap != NSNotFound && gap % i == 0)
{
gap = [gaps indexGreaterThanIndex:gap];
}
if (gap != NSNotFound)
continue;
// yes, the value 'i' divides all the gaps we collected: it is the greater common divisor!
// if we never get there, the common divisor will be 1, which is always correct
pixelGap = i;
break;
}
// now, we know all about the layout of the pixels in the input, we can remove all the spaces and have exactly one character per pixel
NSUInteger lastColumn = pixelColumns.lastIndex;
NSUInteger countCols = 1 + (lastColumn - firstColumn) / pixelGap;
NSUInteger countRows = lenientRep.count;
NSAssert(((lastColumn - firstColumn) % pixelGap) == 0, @"the first and last pixel column should be spearated by an integer multiple of `pixelGap`");
if (concatenatedStrings.length == countCols * countRows)
return lenientRep;
NSMutableString *strictString = [NSMutableString stringWithCapacity:countCols * countRows];
for (NSUInteger i = 0; i < countRows; i ++)
{
for (NSUInteger j = 0; j < countCols; j ++)
[strictString appendString:[concatenatedStrings substringWithRange:NSMakeRange(i * columnCount + firstColumn + j * pixelGap, 1)]];
}
NSAssert(strictString.length == countCols * countRows, @"String derived from lenient ascii shape should have %@ characters but is: %@", @(countCols * countRows), strictString);
// final array
NSMutableArray *strictRep = [NSMutableArray arrayWithCapacity:countRows];
for (NSUInteger i = 0; i < countRows; i ++)
[strictRep addObject:[strictString substringWithRange:NSMakeRange(countCols * i, countCols)]];
return [NSArray arrayWithArray:strictRep];
}
#pragma mark - ASCII --> Ellipses + Polygons
+ (NSArray *)orderedMarksForASCIIShape
{
static dispatch_once_t onceToken;
static NSArray *orderedMarksForASCIIShape = nil;
dispatch_once(&onceToken, ^
{
NSString *numbers = @"1 2 3 4 5 6 7 8 9 A B C D E F G H I J K L M N O P Q R S T U V W X Y Z a b c d e f g h i j k l m n p q r s t u v w x y z";
orderedMarksForASCIIShape = [numbers componentsSeparatedByString:@" "];
});
return orderedMarksForASCIIShape;
}
+ (NSCharacterSet *)markCharactersForASCIIShape
{
static dispatch_once_t onceToken;
static NSCharacterSet *markCharactersForASCIIShape = nil;
dispatch_once(&onceToken, ^
{
NSString *allMarks = [[self orderedMarksForASCIIShape] componentsJoinedByString:@""];
markCharactersForASCIIShape = [NSCharacterSet characterSetWithCharactersInString:allMarks];
});
return markCharactersForASCIIShape;
}
+ (NSCharacterSet *)nonWhitespaceCharacters
{
static dispatch_once_t onceToken;
static NSCharacterSet *nonWhitespaceCharacters = nil;
dispatch_once(&onceToken, ^
{
nonWhitespaceCharacters = [[NSCharacterSet whitespaceCharacterSet] invertedSet];
});
return nonWhitespaceCharacters;
}
+ (NSArray *)shapesFromNumbersInStrictASCIIRepresentation:(NSArray *)representation
{
// canvas size
NSUInteger countRows = representation.count;
if (countRows == 0)
return @[];
NSUInteger countCols = [representation[0] length];
NSUInteger countPixels = countRows * countCols;
NSString *asciiString = [representation componentsJoinedByString:@""];
// collect positions of the different marks in the shape
NSCharacterSet *markCharacters = [self markCharactersForASCIIShape];
NSRange markRange = [asciiString rangeOfCharacterFromSet:markCharacters options:NSLiteralSearch range:NSMakeRange(0, countPixels)];
NSMutableDictionary *markPositions = [NSMutableDictionary dictionary];
while (markRange.location != NSNotFound)
{
NSString *mark = [asciiString substringWithRange:markRange];
NSMutableArray *positions = markPositions[mark];
if (!positions)
{
positions = [NSMutableArray array];
markPositions[mark] = positions;
}
// new position: note that the Y need to be inverted to get the coordinate rights
CGFloat x = markRange.location % countCols;
CGFloat y = countRows - 1 - markRange.location / countCols;
[positions addObject:PARValueFromPoint(CGPointMake(x,y))];
// next mark
NSUInteger newLocation = markRange.location + 1;
if (newLocation < countPixels)
markRange = [asciiString rangeOfCharacterFromSet:markCharacters options:NSLiteralSearch range:NSMakeRange(newLocation, countPixels - newLocation)];
else
break;
}
// iterate over the possible marks (1, 2, 3, ...), building shapes as we go
NSMutableArray *shapes = [NSMutableArray array];
NSArray *marks = [self orderedMarksForASCIIShape];
NSMutableArray *currentPoints = nil;
for (NSString *mark in marks)
{
NSArray *points = markPositions[mark];
NSUInteger numberOfPoints = points.count;
// continue current shape of start a new one
if (numberOfPoints == 1)
{
CGPoint vertex = PARPointFromValue(points.lastObject);
if (!currentPoints)
currentPoints = [NSMutableArray array];
[currentPoints addObject:PARValueFromPoint(vertex)];
}
else
{
// close current shape
if (currentPoints)
[shapes addObject:[PARShape polygonWithPointValues:currentPoints]];
currentPoints = nil;
// single pixel
if (numberOfPoints == 1)
[shapes addObject:[PARShape polygonWithPointValues:points]];
// line
else if (numberOfPoints == 2)
[shapes addObject:[PARShape polygonWithPointValues:points]];
// ellipse
else if (numberOfPoints > 2)
[shapes addObject:[PARShape ellipseWithPointValues:points]];
}
}
if (currentPoints)
[shapes addObject:[PARShape polygonWithPointValues:currentPoints]];
return [NSArray arrayWithArray:shapes];
}
// method used for testing
+ (NSArray *)numberedASCIIRepresentationFromASCIIRepresentation:(NSArray *)rep
{
// ASCII --> shapes
NSArray *strictRep = [self strictASCIIRepresentationFromLenientASCIIRepresentation:rep];
NSArray *shapes = [self shapesFromNumbersInStrictASCIIRepresentation:strictRep];
// prepare output
NSUInteger countRows = strictRep.count;
NSUInteger countCols = [strictRep[0] length];
NSMutableArray *output = [NSMutableArray arrayWithCapacity:countRows];
for (NSUInteger row = 0; row < countRows; row ++)
{
NSMutableString *line = [NSMutableString stringWithCapacity:countCols * 2];
for (NSUInteger col = 0; col < countCols; col ++)
[line appendString:@"· "];
[output addObject:line];
}
// shapes --> ASCII
NSArray *marks = [self orderedMarksForASCIIShape];
NSUInteger currentMark = 0;
for (PARShape *shape in shapes)
{
for (NSValue *value in shape.pointValues)
{
CGPoint point = PARPointFromValue(value);
NSInteger x = point.x;
NSInteger y = countCols - point.y;
NSMutableString *line = output[y];
[line replaceCharactersInRange:NSMakeRange(x * 2, 1) withString:marks[currentMark]];
currentMark ++;
}
currentMark ++;
}
return output;
}
#pragma mark - ASCII --> NSImage
+ (void(^)(NSMutableDictionary *context))contextHandlerForImageWithColor:(PARColor *)color shouldAntialias:(BOOL)shouldAntialias
{
return ^(NSMutableDictionary *context)
{
context[ASCIIContextShouldAntialias] = @(shouldAntialias);
context[ASCIIContextFillColor] = color;
context[ASCIIContextShouldClose] = @(YES);
};
}
+ (PARImage *)imageWithASCIIRepresentation:(NSArray *)rep color:(PARColor *)color shouldAntialias:(BOOL)shouldAntialias
{
return [self imageWithASCIIRepresentation:rep contextHandler:[self contextHandlerForImageWithColor:color shouldAntialias:shouldAntialias]];
}
+ (PARImage *)imageWithASCIIRepresentation:(NSArray *)rep contextHandler:(void(^)(NSMutableDictionary *context))contextHandler
{
#if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR
CGFloat scaleFactor = [UIScreen mainScreen].scale;
return [self ios_imageWithASCIIRepresentation:rep scaleFactor:scaleFactor contextHandler:contextHandler];
#elif TARGET_OS_MAC
return [self mac_imageWithASCIIRepresentation:rep contextHandler:contextHandler];
#endif
}
#pragma mark - Predefined images
+ (PARImage *)arrowImageWithColor:(PARColor *)color
{
NSArray *asciiRep = @
[
@"· · · · · · · · · · · ·",
@"· · · · · · · · · · · ·",
@"· · · · · · · · · · · ·",
@"· · · · · · 1 · · · · ·",
@"· · · · · · o o · · · ·",
@"· · · 7 o o 8 o 2 · · ·",
@"· · · 6 o o 5 o 3 · · ·",
@"· · · · · · o o · · · ·",
@"· · · · · · 4 · · · · ·",
@"· · · · · · · · · · · ·",
@"· · · · · · · · · · · ·",
@"· · · · · · · · · · · ·",
];
return [self imageWithASCIIRepresentation:asciiRep color:color shouldAntialias:NO];
}
+ (PARImage *)chevronImageWithColor:(PARColor *)color
{
NSArray *asciiRep = @
[
@"· · · · · · · · · · · ·",
@"· · · 1 2 · · · · · · ·",
@"· · · A o o · · · · · ·",
@"· · · · o o o · · · · ·",
@"· · · · · o o o · · · ·",
@"· · · · · · 9 o 3 · · ·",
@"· · · · · · 8 o 4 · · ·",
@"· · · · · o o o · · · ·",
@"· · · · o o o · · · · ·",
@"· · · 7 o o · · · · · ·",
@"· · · 6 5 · · · · · · ·",
@"· · · · · · · · · · · ·",
];
return [self imageWithASCIIRepresentation:asciiRep color:color shouldAntialias:NO];
}
#pragma mark - Platform Specific Methods
#if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR
+ (PARImage *)imageWithASCIIRepresentation:(NSArray *)rep scaleFactor:(CGFloat)scaleFactor color:(PARColor *)color shouldAntialias:(BOOL)shouldAntialias
{
return [self ios_imageWithASCIIRepresentation:rep scaleFactor:scaleFactor contextHandler:[self contextHandlerForImageWithColor:color shouldAntialias:shouldAntialias]];
}
+ (PARImage *)imageWithASCIIRepresentation:(NSArray *)rep scaleFactor:(CGFloat)scaleFactor contextHandler:(void(^)(NSMutableDictionary *context))contextHandler
{
return [self ios_imageWithASCIIRepresentation:rep scaleFactor:scaleFactor contextHandler:contextHandler];
}
+ (PARImage *)ios_imageWithASCIIRepresentation:(NSArray *)rep scaleFactor:(CGFloat)scale contextHandler:(void(^)(NSMutableDictionary *context))contextHandler
{
// ASCII --> shapes
NSArray *strictRep = [self strictASCIIRepresentationFromLenientASCIIRepresentation:rep];
NSArray *shapes = [self shapesFromNumbersInStrictASCIIRepresentation:strictRep];
// image size in points
NSUInteger countRows = strictRep.count;
NSUInteger countCols = [strictRep[0] length];
CGSize imageSizeInPoints = CGSizeMake(countCols, countRows);
// image size in pixels
CGSize imageSizeInPixels;
imageSizeInPixels.width = imageSizeInPoints.width * scale;
imageSizeInPixels.height = imageSizeInPoints.height * scale;
// iOS documentation: https://developer.apple.com/library/ios/documentation/2DDrawing/Conceptual/DrawingPrintingiOS/HandlingImages/Images.html
// iOS example: http://kalyanchakravarthy.net/blog/ios-drawing-using-coregraphics.html
// Create context for drawing to image
UIGraphicsBeginImageContext(imageSizeInPixels);
CGContextRef contextRef = UIGraphicsGetCurrentContext();
// on iOS the Y axis is upside down
CGAffineTransform flipVertical = CGAffineTransformMake(1, 0, 0, -1, 0, imageSizeInPixels.height);
CGContextConcatCTM(contextRef, flipVertical);
// scaling factor: the bezier paths are set in points, but we are drawing directly at the pixel size
CGAffineTransform scalingTransform = CGAffineTransformMakeScale(scale, scale);
CGContextConcatCTM(contextRef, scalingTransform);
// drawing each shape
NSUInteger shapeIndex = 0;
for (PARShape *shape in shapes)
{
// get ASCII context from handler (that's different from the graphics context!)
// ... but don't let the handler mess up the graphics context
NSMutableDictionary *contextASCII = [NSMutableDictionary dictionaryWithDictionary:@{ASCIIContextShapeIndex: @(shapeIndex)}];
CGContextSaveGState(contextRef);
{
contextHandler(contextASCII);
}
CGContextRestoreGState(contextRef);
// get information from ASCII context
PARColor *fillColor = contextASCII[ASCIIContextFillColor];
PARColor *strokeColor = contextASCII[ASCIIContextStrokeColor];
CGFloat lineWidth = [contextASCII[ASCIIContextLineWidth] floatValue];
BOOL shouldClose = [contextASCII[ASCIIContextShouldClose] boolValue];
BOOL shouldAntialias = [contextASCII[ASCIIContextShouldAntialias] boolValue];
// bezier path from shape
PARBezierPath *path = shouldClose ? [shape closedBezierPath] : [shape bezierPath];
// antialias
CGContextSetShouldAntialias(contextRef, shouldAntialias);
// fill
if (fillColor)
{
[fillColor setFill];
[path fill];
if (strokeColor == nil)
{
path.lineWidth = shouldAntialias ? 1.0 : sqrtf(2.0)/2.0;
[fillColor setStroke];
[path stroke];
}
}
// stroke
if (strokeColor)
{
path.lineWidth = lineWidth > 0.0 ? lineWidth : 1.0;
[strokeColor setStroke];
[path stroke];
}
shapeIndex ++;
}
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
#elif TARGET_OS_MAC
+ (PARImage *)mac_imageWithASCIIRepresentation:(NSArray *)rep contextHandler:(void(^)(NSMutableDictionary *context))contextHandler
{
// ASCII --> shapes
NSArray *strictRep = [self strictASCIIRepresentationFromLenientASCIIRepresentation:rep];
NSArray *shapes = [self shapesFromNumbersInStrictASCIIRepresentation:strictRep];
// image size
NSUInteger countRows = strictRep.count;
NSUInteger countCols = [strictRep[0] length];
NSSize imageSize = NSMakeSize(countCols, countRows);
// image is drawn using the block API, so we can handle @2x drawing in HiDPI
NSImage *image = [NSImage imageWithSize:imageSize flipped:NO drawingHandler:^BOOL(NSRect dstRect)
{
NSUInteger shapeIndex = 0;
for (PARShape *shape in shapes)
{
// get ASCII context from handler (that's different from the graphics context!)
// ... but don't let the handler mess up the graphics context
NSMutableDictionary *contextASCII = [NSMutableDictionary dictionaryWithDictionary:@{ASCIIContextShapeIndex: @(shapeIndex)}];
[[NSGraphicsContext currentContext] saveGraphicsState];
{
contextHandler(contextASCII);
}
[[NSGraphicsContext currentContext] restoreGraphicsState];
// get information from ASCII context
PARColor *fillColor = contextASCII[ASCIIContextFillColor];
PARColor *strokeColor = contextASCII[ASCIIContextStrokeColor];
CGFloat lineWidth = [contextASCII[ASCIIContextLineWidth] floatValue];
BOOL shouldClose = [contextASCII[ASCIIContextShouldClose] boolValue];
BOOL shouldAntialias = [contextASCII[ASCIIContextShouldAntialias] boolValue];
// bezier path from shape
PARBezierPath *path = shouldClose ? [shape closedBezierPath] : [shape bezierPath];
// draw!
[[NSGraphicsContext currentContext] saveGraphicsState];
{
// antialias
[[NSGraphicsContext currentContext] setShouldAntialias:shouldAntialias];
// fill
if (fillColor)
{
[fillColor setFill];
[path fill];
if (strokeColor == nil)
{
path.lineWidth = shouldAntialias ? 1.0 : sqrtf(2.0)/2.0;
[fillColor setStroke];
[path stroke];
}
}
// stroke
if (strokeColor)
{
path.lineWidth = lineWidth > 0.0 ? lineWidth : 1.0;
[strokeColor setStroke];
[path stroke];
}
}
[[NSGraphicsContext currentContext] restoreGraphicsState];
shapeIndex ++;
}
return YES;
}];
return image;
}
#endif
@end
#pragma mark - PARShape Private Implementation
@interface PARShape ()
@property (readwrite, copy) NSArray *pointValues;
@property (readwrite) BOOL ellipse;
@property (readwrite) BOOL shouldClose;
@end
@implementation PARShape
- (NSString *)description
{
NSMutableString *description = [NSMutableString stringWithFormat:@"<%@:%p> (%@)", self.class, self, self.ellipse ? @"ellipse":@"polygon"];
for (NSValue *value in self.pointValues)
{
[description appendString:@"\n"];
[description appendString:NSStringFromPoint(PARPointFromValue(value))];
}
return [NSString stringWithString:description];
}
+ (PARShape *)polygonWithPointValues:(NSArray *)pointValues
{
PARShape *polygon = [[PARShape alloc] init];
polygon.pointValues = pointValues;
return polygon;
}
+ (PARShape *)ellipseWithPointValues:(NSArray *)pointValues
{
PARShape *polygon = [[PARShape alloc] init];
polygon.pointValues = pointValues;
polygon.ellipse = YES;
return polygon;
}
- (PARBezierPath *)bezierPathClosed:(BOOL)shouldClose
{
// ellipse
if (self.ellipse)
{
NSArray *points = self.pointValues;
CGPoint point1 = PARPointFromValue(points[0]);
CGRect enclosingRect = CGRectMake(point1.x, point1.y, 0.0, 0.0);
for (NSValue *pointValue in points)
{
CGPoint point = PARPointFromValue(pointValue);
CGFloat minX = fminf(point.x, CGRectGetMinX(enclosingRect));
CGFloat maxX = fmaxf(point.x, CGRectGetMaxX(enclosingRect));
CGFloat minY = fminf(point.y, CGRectGetMinY(enclosingRect));
CGFloat maxY = fmaxf(point.y, CGRectGetMaxY(enclosingRect));
enclosingRect = CGRectMake(minX, minY, maxX - minX, maxY - minY);
}
enclosingRect.size.width += 1.0;
enclosingRect.size.height += 1.0;
enclosingRect = CGRectInset(enclosingRect, 0.5, 0.5);
return [PARBezierPath bezierPathWithOvalInRect:enclosingRect];
}
// polygon
else
{
NSArray *points = self.pointValues;
// single pixel
if (points.count == 1)
{
CGPoint point = PARPointFromValue(points[0]);
return [PARBezierPath bezierPathWithRect:CGRectMake(point.x + 0.49, point.y + 0.49, 0.02, 0.02)];
}
PARBezierPath *path = [PARBezierPath bezierPath];
for (NSValue *pointValue in points)
{
CGPoint point = PARPointFromValue(pointValue);
point.x += 0.5;
point.y += 0.5;
if ([path isEmpty])
[path moveToPoint:point];
else
[path lineToPoint:point];
}
path.lineJoinStyle = NSMiterLineJoinStyle;
path.lineCapStyle = NSSquareLineCapStyle;
if (points.count > 2 && shouldClose)
{
[path closePath];
}
return path;
}
return nil;
}
- (PARBezierPath *)bezierPath
{
return [self bezierPathClosed:NO];
}
- (PARBezierPath *)closedBezierPath
{
return [self bezierPathClosed:YES];
}
@end