SVGImageElement.m 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. #import "SVGImageElement.h"
  2. #import "CALayerWithClipRender.h"
  3. #import "SVGHelperUtilities.h"
  4. #import "NSData+NSInputStream.h"
  5. #import "SVGKImage.h"
  6. #import "SVGKSourceURL.h"
  7. #import "SVGKSourceNSData.h"
  8. #import "SVGKInlineResource.h"
  9. CGImageRef SVGImageCGImage(UIImage *img)
  10. {
  11. #if SVGKIT_UIKIT
  12. return img.CGImage;
  13. #else
  14. CGImageRef cgImage = [img CGImageForProposedRect:NULL context:nil hints:nil];
  15. return cgImage;
  16. #endif
  17. }
  18. @interface SVGImageElement()
  19. @property (nonatomic, strong, readwrite) NSString *href;
  20. @end
  21. @implementation SVGImageElement
  22. @synthesize transform; // each SVGElement subclass that conforms to protocol "SVGTransformable" has to re-synthesize this to work around bugs in Apple's Objective-C 2.0 design that don't allow @properties to be extended by categories / protocols
  23. @synthesize viewBox; // each SVGElement subclass that conforms to protocol "SVGFitToViewBox" has to re-synthesize this to work around bugs in Apple's Objective-C 2.0 design that don't allow @properties to be extended by categories / protocols
  24. @synthesize preserveAspectRatio; // each SVGElement subclass that conforms to protocol "SVGFitToViewBox" has to re-synthesize this to work around bugs in Apple's Objective-C 2.0 design that don't allow @properties to be extended by categories / protocols
  25. @synthesize x = _x;
  26. @synthesize y = _y;
  27. @synthesize width = _width;
  28. @synthesize height = _height;
  29. @synthesize href = _href;
  30. - (void)postProcessAttributesAddingErrorsTo:(SVGKParseResult *)parseResult {
  31. [super postProcessAttributesAddingErrorsTo:parseResult];
  32. if( [[self getAttribute:@"x"] length] > 0 )
  33. _x = [[self getAttribute:@"x"] floatValue];
  34. if( [[self getAttribute:@"y"] length] > 0 )
  35. _y = [[self getAttribute:@"y"] floatValue];
  36. if( [[self getAttribute:@"width"] length] > 0 )
  37. _width = [[self getAttribute:@"width"] floatValue];
  38. if( [[self getAttribute:@"height"] length] > 0 )
  39. _height = [[self getAttribute:@"height"] floatValue];
  40. if( [[self getAttribute:@"href"] length] > 0 )
  41. self.href = [self getAttribute:@"href"];
  42. [SVGHelperUtilities parsePreserveAspectRatioFor:self];
  43. }
  44. - (CALayer *) newLayer
  45. {
  46. CALayer* newLayer = [CALayerWithClipRender layer];
  47. [SVGHelperUtilities configureCALayer:newLayer usingElement:self];
  48. NSData *imageData;
  49. NSURL* imageURL = [NSURL URLWithString:_href];
  50. SVGKSource* effectiveSource = nil;
  51. if ([_href hasPrefix:@"http:"] || [_href hasPrefix:@"https:"] )
  52. imageData = [NSData dataWithContentsOfURL:imageURL];
  53. else
  54. if( [_href hasPrefix:@"data:"])
  55. {
  56. self.href = [_href stringByReplacingOccurrencesOfString:@"\\s+"
  57. withString:@""
  58. options:NSRegularExpressionSearch
  59. range:NSMakeRange(0, [_href length]) ];
  60. imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:_href]];
  61. }
  62. else
  63. {
  64. effectiveSource = [self.rootOfCurrentDocumentFragment.source sourceFromRelativePath:_href];
  65. NSInputStream *stream = effectiveSource.stream;
  66. if (stream) {
  67. [stream open]; // if we do this, we CANNOT parse from this source again in future
  68. NSError *error = nil;
  69. imageData = [NSData dataWithContentsOfStream:stream initialCapacity:NSUIntegerMax error:&error];
  70. if( error )
  71. SVGKitLogError(@"[%@] ERROR: unable to read stream from %@ into NSData: %@", [self class], _href, error);
  72. } else {
  73. SVGKitLogError(@"[%@] ERROR: unable to load the source from URL: %@", [self class], _href);
  74. }
  75. }
  76. /** Now we have some raw bytes, try to load using Apple's image loaders
  77. (will fail if the image is an SVG file)
  78. */
  79. UIImage *image = [[UIImage alloc] initWithData:imageData];
  80. if( image == nil ) // NSData doesn't contain an imageformat Apple supports; might be an SVG instead
  81. {
  82. SVGKImage *svg = nil;
  83. if( effectiveSource == nil )
  84. effectiveSource = [SVGKSourceURL sourceFromURL:imageURL];
  85. if( effectiveSource != nil )
  86. {
  87. SVGKitLogInfo(@"Attempting to interpret the image at URL as an embedded SVG link (Apple failed to parse it): %@", _href );
  88. if( imageData != nil )
  89. {
  90. /** NB: sources can only be used once; we've already opened the stream for the source
  91. earlier, so we MUST pass-in the already-downloaded NSData
  92. (if not, we'd be downloading it twice anyway, which can be lethal with large
  93. SVG files!)
  94. */
  95. svg = [SVGKImage imageWithSource: [SVGKSourceNSData sourceFromData:imageData URLForRelativeLinks:imageURL]];
  96. }
  97. else
  98. {
  99. svg = [SVGKImage imageWithSource: effectiveSource];
  100. }
  101. if( svg != nil )
  102. {
  103. image = svg.UIImage;
  104. }
  105. }
  106. // If still fail, use the broken image placeholder
  107. if (!image) {
  108. image = SVGKGetBrokenImageRepresentation();
  109. }
  110. }
  111. if( image != nil )
  112. {
  113. CGRect frame = CGRectMake(_x, _y, _width, _height);
  114. if( imageData )
  115. self.viewBox = SVGRectMake(0, 0, image.size.width, image.size.height);
  116. else
  117. self.viewBox = SVGRectMake(0, 0, _width, _height);
  118. CGImageRef imageRef = SVGImageCGImage(image);
  119. BOOL imageRefHasBeenRetained = false; // only one codepath CREATES a new image, because of Apple's API; the rest use an existing reference
  120. // apply preserveAspectRatio
  121. if( self.preserveAspectRatio.baseVal.align != SVG_PRESERVEASPECTRATIO_NONE
  122. && ABS( self.aspectRatioFromWidthPerHeight - self.aspectRatioFromViewBox) > 0.00001 )
  123. {
  124. double ratioOfRatios = self.aspectRatioFromWidthPerHeight / self.aspectRatioFromViewBox;
  125. if( self.preserveAspectRatio.baseVal.meetOrSlice == SVG_MEETORSLICE_MEET )
  126. {
  127. // shrink the image to fit in the frame, preserving the aspect ratio
  128. frame = [self clipFrame:frame fromRatio:ratioOfRatios];
  129. }
  130. else if( self.preserveAspectRatio.baseVal.meetOrSlice == SVG_MEETORSLICE_SLICE )
  131. {
  132. // crop the image
  133. CGRect cropRect = CGRectMake(0, 0, image.size.width, image.size.height);
  134. cropRect = [self clipFrame:cropRect fromRatio:1.0 / ratioOfRatios];
  135. imageRef = CGImageCreateWithImageInRect(imageRef, cropRect);
  136. imageRefHasBeenRetained = true;
  137. }
  138. }
  139. /** transform our LOCAL path into ABSOLUTE space */
  140. frame = CGRectApplyAffineTransform(frame, [SVGHelperUtilities transformAbsoluteIncludingViewportForTransformableOrViewportEstablishingElement:self]);
  141. newLayer.frame = frame;
  142. newLayer.contents = (__bridge id)imageRef;
  143. if( imageRefHasBeenRetained )
  144. CGImageRelease( imageRef );
  145. }
  146. #if OLD_CODE
  147. __block CALayer *layer = [[CALayer layer] retain];
  148. layer.name = self.identifier;
  149. [layer setValue:self.identifier forKey:kSVGElementIdentifier];
  150. CGRect frame = CGRectMake(_x, _y, _width, _height);
  151. frame = CGRectApplyAffineTransform(frame, [SVGHelperUtilities transformAbsoluteIncludingViewportForTransformableOrViewportEstablishingElement:self]);
  152. layer.frame = frame;
  153. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  154. NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:_href]];
  155. SVGImageRef image = [SVGImage imageWithData:imageData];
  156. // _href = @"http://b.dryicons.com/images/icon_sets/coquette_part_4_icons_set/png/128x128/png_file.png";
  157. // NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:_href]];
  158. // UIImage *image = [UIImage imageWithData:imageData];
  159. dispatch_async(dispatch_get_main_queue(), ^{
  160. layer.contents = (id)SVGImageCGImage(image);
  161. });
  162. });
  163. return layer;
  164. #endif
  165. return newLayer;
  166. }
  167. - (CGRect)clipFrame:(CGRect)frame fromRatio:(double)ratioOfRatios
  168. {
  169. if( ratioOfRatios > 1 ) // if we're going to have space to either side
  170. {
  171. CGFloat width = frame.size.width;
  172. frame.size.width = frame.size.width / ratioOfRatios;
  173. switch( self.preserveAspectRatio.baseVal.align )
  174. {
  175. case SVG_PRESERVEASPECTRATIO_XMIDYMIN:
  176. case SVG_PRESERVEASPECTRATIO_XMIDYMID:
  177. case SVG_PRESERVEASPECTRATIO_XMIDYMAX:
  178. {
  179. frame.origin.x = frame.origin.x + ((width - frame.size.width) / 2);
  180. }break;
  181. case SVG_PRESERVEASPECTRATIO_XMAXYMIN:
  182. case SVG_PRESERVEASPECTRATIO_XMAXYMID:
  183. case SVG_PRESERVEASPECTRATIO_XMAXYMAX:
  184. {
  185. frame.origin.x = frame.origin.x + width - frame.size.width;
  186. }break;
  187. default:
  188. break;
  189. }
  190. }
  191. else // if we're going to have space above and below
  192. {
  193. CGFloat height = frame.size.height;
  194. frame.size.height = frame.size.height * ratioOfRatios;
  195. switch( self.preserveAspectRatio.baseVal.align )
  196. {
  197. case SVG_PRESERVEASPECTRATIO_XMINYMID:
  198. case SVG_PRESERVEASPECTRATIO_XMIDYMID:
  199. case SVG_PRESERVEASPECTRATIO_XMAXYMID:
  200. {
  201. frame.origin.y = frame.origin.y + ((height - frame.size.height) / 2);
  202. }break;
  203. case SVG_PRESERVEASPECTRATIO_XMINYMAX:
  204. case SVG_PRESERVEASPECTRATIO_XMIDYMAX:
  205. case SVG_PRESERVEASPECTRATIO_XMAXYMAX:
  206. {
  207. frame.origin.y = frame.origin.y + height - frame.size.height;
  208. }break;
  209. default:
  210. break;
  211. }
  212. }
  213. return frame;
  214. }
  215. - (void)layoutLayer:(CALayer *)layer {
  216. }
  217. -(double)aspectRatioFromWidthPerHeight
  218. {
  219. return self.height == 0 ? 0 : self.width / self.height;
  220. }
  221. -(double)aspectRatioFromViewBox
  222. {
  223. return self.viewBox.height == 0 ? 0 : self.viewBox.width / self.viewBox.height;
  224. }
  225. @end