SVGImageElement.m 10 KB

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