SVGImageElement.m 9.6 KB

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