forked from fjolnir/SVGPathSerializing
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SVGLayer.m
278 lines (248 loc) · 11.5 KB
/
SVGLayer.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
#import "SVGLayer.h"
#import "SVGPortability.h"
#import "SVGPathSerializing.h"
CGRect _AdjustCGRectForContentsGravity(CGRect aRect, CGSize aSize, NSString *aGravity);
@implementation SVGLayer {
NSMutableArray *_untouchedPaths;
NSMapTable *_pathAttributes;
NSMutableArray *_shapeLayers;
#ifdef DEBUG
dispatch_source_t _fileWatcher;
#endif
}
- (void)_init
{
_shapeLayers = [NSMutableArray new];
#if TARGET_OS_IPHONE
self.shouldRasterize = YES;
self.rasterizationScale = [[UIScreen mainScreen] scale];
#endif
}
- (instancetype)initWithCoder:(NSCoder * const)aDecoder
{
if((self = [super initWithCoder:aDecoder]))
[self _init];
return self;
}
- (instancetype)init
{
if((self = [super init]))
[self _init];
return self;
}
- (void)setSvgSource:(NSString * const)aSVG
{
[self willChangeValueForKey:@"svgSource"];
#ifdef DEBUG
if(_fileWatcher)
dispatch_source_cancel(_fileWatcher), _fileWatcher = NULL;
#endif
_svgSource = aSVG;
[_shapeLayers makeObjectsPerformSelector:@selector(removeFromSuperlayer)];
[_shapeLayers removeAllObjects];
_untouchedPaths = [NSMutableArray new];
if([aSVG length] == 0)
return;
[CATransaction begin];
[CATransaction setDisableActions:YES];
NSMapTable *attributes;
for(__strong id path in CGPathsFromSVGString(aSVG, &attributes)) {
CAShapeLayer * const layer = [CAShapeLayer new];
NSDictionary * const attrs = [attributes objectForKey:path];
if(attrs[@"transform"]) {
CGAffineTransform const transform = [attrs[@"transform"] svg_CGAffineTransformValue];
CGPathRef const newPath = CGPathCreateCopyByTransformingPath((__bridge CGPathRef)path, &transform);
[attributes setObject:[attributes objectForKey:path]
forKey:(__bridge id)newPath];
[attributes removeObjectForKey:path];
path = (__bridge id)newPath;
}
layer.path = (__bridge CGPathRef)path;
layer.lineWidth = attrs[@"stroke-width"] ? [attrs[@"stroke-width"] floatValue] : 1.0;
layer.opacity = attrs[@"opacity"] ? [attrs[@"opacity"] floatValue] : 1;
[self insertSublayer:layer atIndex:(unsigned int)[_shapeLayers count]];
[_shapeLayers addObject:layer];
[_untouchedPaths addObject:path];
}
_pathAttributes = attributes;
[self setNeedsLayout];
[self layoutIfNeeded];
[CATransaction commit];
[self didChangeValueForKey:@"svgSource"];
}
- (void)loadSVGNamed:(NSString * const)aFileName
{
#if !TARGET_INTERFACE_BUILDER
NSString * const path = [[NSBundle mainBundle] pathForResource:aFileName ofType:@"svg"];
NSParameterAssert(aFileName && path);
#else
NSString *path = nil;
NSPredicate * const pred = [NSPredicate predicateWithFormat:@"lastPathComponent LIKE[c] %@",
[aFileName stringByAppendingPathExtension:@"svg"]];
NSString * const sourceDirs = [[NSProcessInfo processInfo] environment][@"IB_PROJECT_SOURCE_DIRECTORIES"];
for(NSString *dir in [sourceDirs componentsSeparatedByString:@","]) {
NSArray * const results = [[[NSFileManager defaultManager] subpathsAtPath:dir]
filteredArrayUsingPredicate:pred];
if([results count] > 0) {
path = [dir stringByAppendingPathComponent:results[0]];
break;
}
}
#endif
self.svgSource = [NSString stringWithContentsOfFile:path
usedEncoding:NULL
error:nil];
#ifdef DEBUG
__weak SVGLayer *self_ = self;
int const fdes = open([path fileSystemRepresentation], O_RDONLY);
_fileWatcher = dispatch_source_create(DISPATCH_SOURCE_TYPE_VNODE, fdes,
DISPATCH_VNODE_DELETE | DISPATCH_VNODE_WRITE,
dispatch_get_main_queue());
dispatch_source_set_event_handler(_fileWatcher, ^{
unsigned long const l = dispatch_source_get_data(_fileWatcher);
if(l & DISPATCH_VNODE_DELETE || l & DISPATCH_VNODE_WRITE) {
NSLog(@"Reloading %@", aFileName);
dispatch_source_cancel(_fileWatcher);
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)),
dispatch_get_main_queue(), ^{
[self_ loadSVGNamed:aFileName];
});
}
});
dispatch_source_set_cancel_handler(_fileWatcher, ^{
close(fdes);
});
dispatch_resume(_fileWatcher);
#endif
}
- (void)dealloc
{
#ifdef DEBUG
if(_fileWatcher)
dispatch_source_cancel(_fileWatcher);
#endif
}
- (void)setFillColor:(CGColorRef)aColor
{
_fillColor = aColor;
[_shapeLayers setValue:(__bridge id)_fillColor forKey:@"fillColor"];
}
- (void)setStrokeColor:(CGColorRef)aColor
{
_strokeColor = aColor;
[_shapeLayers setValue:(__bridge id)_strokeColor forKey:@"strokeColor"];
}
- (CGSize)preferredFrameSize
{
CGRect bounds = CGRectZero;
for(id path in _untouchedPaths) {
bounds = CGRectUnion(bounds, CGPathGetPathBoundingBox((__bridge CGPathRef)path));
}
return bounds.size;
}
- (void)layoutSublayers
{
[super layoutSublayers];
#if !TARGET_OS_IPHONE && TARGET_INTERFACE_BUILDER
self.sublayerTransform = CATransform3DTranslate(CATransform3DMakeScale(1, -1, 1),
0, -self.bounds.size.height, 0);
#endif
CGSize const size = [self preferredFrameSize];
CGRect const frame = _AdjustCGRectForContentsGravity(self.bounds, size, self.contentsGravity);
CGAffineTransform const scale = CGAffineTransformMakeScale(frame.size.width / size.width,
frame.size.height / size.height);
CGAffineTransform const layerTransform = CGAffineTransformConcat(CGAffineTransformMakeTranslation(frame.origin.x,
frame.origin.y),
scale);
NSAssert([_shapeLayers count] == [_untouchedPaths count],
@"Layer & Path count in SVG Image View does not match!");
for(NSUInteger i = 0; i < [_untouchedPaths count]; ++i) {
CGPathRef const path = (__bridge CGPathRef)_untouchedPaths[i];
CAShapeLayer * const layer = _shapeLayers[i];
NSDictionary * const attrs = [_pathAttributes objectForKey:(__bridge id)path];
layer.fillColor = _fillColor
?: (__bridge CGColorRef)attrs[@"fill"]
?: [[SVGUI(Color) blackColor] CGColor];
layer.strokeColor = _strokeColor
?: (__bridge CGColorRef)attrs[@"stroke"];
CGRect const pathBounds = CGPathGetPathBoundingBox(path);
layer.frame = CGRectApplyAffineTransform(pathBounds, layerTransform);
CGAffineTransform const pathTransform = CGAffineTransformConcat(
CGAffineTransformMakeTranslation(-pathBounds.origin.x,
-pathBounds.origin.y),
scale);
CGPathRef const transformedPath = CGPathCreateCopyByTransformingPath(path, &pathTransform);
layer.path = transformedPath;
CGPathRelease(transformedPath);
}
}
@end
CGRect _AdjustCGRectForContentsGravity(CGRect const aRect, CGSize const aSize, NSString const *aGravity)
{
if(aSize.width != aRect.size.width || aSize.height != aRect.size.height) {
if([aGravity isEqualToString:kCAGravityLeft])
return (CGRect) { aRect.origin.x,
aRect.origin.y + floor(aRect.size.height/2 - aSize.height/2),
aSize.width, aSize.height };
else if([aGravity isEqualToString:kCAGravityRight])
return (CGRect) { aRect.origin.x + (aRect.size.width - aSize.width),
aRect.origin.y + floor(aRect.size.height/2 - aSize.height/2),
aSize.width, aSize.height };
else if([aGravity isEqualToString:kCAGravityTop])
return (CGRect) { aRect.origin.x + floor(aRect.size.width/2 - aSize.width/2),
aRect.origin.y,
aSize.width, aSize.height };
else if([aGravity isEqualToString:kCAGravityBottom])
return (CGRect) { aRect.origin.x + floor(aRect.size.width/2 - aSize.width/2),
aRect.origin.y + floor(aRect.size.height - aSize.height),
aSize.width, aSize.height };
else if([aGravity isEqualToString:kCAGravityCenter])
return (CGRect) { aRect.origin.x + round(aRect.size.width/2 - aSize.width/2),
aRect.origin.y + round(aRect.size.height/2 - aSize.height/2),
aSize.width, aSize.height };
else if([aGravity isEqualToString:kCAGravityBottomLeft])
return (CGRect) { aRect.origin.x,
aRect.origin.y + floor(aRect.size.height - aSize.height),
aSize.width, aSize.height };
else if([aGravity isEqualToString:kCAGravityBottomRight])
return (CGRect) { aRect.origin.x + (aRect.size.width - aSize.width),
aRect.origin.y + (aRect.size.height - aSize.height),
aSize.width, aSize.height };
else if([aGravity isEqualToString:kCAGravityTopLeft])
return (CGRect) { aRect.origin.x,
aRect.origin.y,
aSize.width, aSize.height };
else if([aGravity isEqualToString:kCAGravityTopRight])
return (CGRect) { aRect.origin.x + (aRect.size.width - aSize.width),
aRect.origin.y,
aSize.width, aSize.height };
else if([aGravity isEqualToString:kCAGravityResizeAspectFill]) {
CGSize size = aSize;
CGFloat const sizeRatio = size.width / size.height;
CGFloat const rectRatio = aRect.size.width / aRect.size.height;
if(sizeRatio > rectRatio) {
size.width = floorf(sizeRatio * aRect.size.height);
size.height = aRect.size.height;
} else {
size.height = floorf(aRect.size.width / sizeRatio);
size.width = aRect.size.width;
}
return (CGRect) { aRect.origin.x + floorf(aRect.size.width/2 - size.width/2),
aRect.origin.y + floorf(aRect.size.height/2 - size.height/2),
size.width, size.height };
} else if([aGravity isEqualToString:kCAGravityResizeAspect]) {
CGSize size = aSize;
if((size.height/size.width) < (aRect.size.height/aRect.size.width)) {
size.height = floorf((size.height/size.width) * aRect.size.width);
size.width = aRect.size.width;
} else {
size.width = floorf((size.width/size.height) * aRect.size.height);
size.height = aRect.size.height;
}
return (CGRect) { aRect.origin.x + floorf(aRect.size.width/2 - size.width/2),
aRect.origin.y + floorf(aRect.size.height/2 - size.height/2),
size.width, size.height };
}
}
return aRect;
}