@@ -192,30 +192,35 @@ - (UIImage *)createBitmapSVGWithData:(nonnull NSData *)data targetSize:(CGSize)t
192192 }
193193
194194 CGSize size = SDCGSVGDocumentGetCanvasSize (document);
195- if (CGSizeEqualToSize (targetSize, CGSizeZero)) {
196- targetSize = size;
195+ CGRect rect = CGRectMake (0 , 0 , size.width , size.height );
196+ CGRect targetRect = rect;
197+ if (!CGSizeEqualToSize (targetSize, CGSizeZero)) {
198+ targetRect = CGRectMake (0 , 0 , targetSize.width , targetSize.height );
197199 }
198200
199- CGFloat xRatio = targetSize. width / size.width ;
200- CGFloat yRatio = targetSize. height / size.height ;
201+ CGFloat xRatio = targetRect. size . width / rect. size .width ;
202+ CGFloat yRatio = targetRect. size . height / rect. size .height ;
201203 CGFloat xScale = preserveAspectRatio ? MIN (xRatio, yRatio) : xRatio;
202204 CGFloat yScale = preserveAspectRatio ? MIN (xRatio, yRatio) : yRatio;
203205
204206 CGAffineTransform scaleTransform = CGAffineTransformMakeScale (xScale, yScale);
205- CGSize scaledSize = CGSizeApplyAffineTransform (size, scaleTransform);
206- CGAffineTransform translationTransform = CGAffineTransformMakeTranslation (targetSize.width / 2 - scaledSize.width / 2 , targetSize.height / 2 - scaledSize.height / 2 );
207+ CGAffineTransform transform = CGAffineTransformIdentity;
208+ if (preserveAspectRatio) {
209+ // Calculate the offset
210+ transform = CGAffineTransformMakeTranslation ((targetRect.size .width / xScale - rect.size .width ) / 2 , (targetRect.size .height / yScale - rect.size .height ) / 2 );
211+ }
207212
208- SDGraphicsBeginImageContextWithOptions (targetSize , NO , 0 );
213+ SDGraphicsBeginImageContextWithOptions (targetRect. size , NO , 0 );
209214 CGContextRef context = SDGraphicsGetCurrentContext ();
210215
211216#if SD_UIKIT || SD_WATCH
212217 // Core Graphics coordinate system use the bottom-left, UIkit use the flipped one
213- CGContextTranslateCTM (context, 0 , targetSize .height );
218+ CGContextTranslateCTM (context, 0 , targetRect. size .height );
214219 CGContextScaleCTM (context, 1 , -1 );
215220#endif
216221
217- CGContextConcatCTM (context, translationTransform);
218222 CGContextConcatCTM (context, scaleTransform);
223+ CGContextConcatCTM (context, transform);
219224
220225 SDCGContextDrawSVGDocument (context, document);
221226
0 commit comments