Demo地址:https://github.com/ColdChains/QLSVGClipsImage.git
1.项目导入PocketSVG
2.根据svg文件绘制出svg图形
SVGBezierPath *svgPath = [SVGBezierPath pathsFromSVGAtURL:[NSURL fileURLWithPath:self.filepath]].firstObject;
CGSize svgSize = SVGBoundingRectForPaths(@[svgPath]).size;
// 根据svg图形显示scrollview和imageview
self.scrollView.frame = CGRectMake(100, 200, 200, 200 * svgSize.height / svgSize.width);
self.imageView.frame = [self adaptionSize:self.scrollView.bounds.size edgInsets:UIEdgeInsetsZero image:self.imageView.image aspectFit:NO needOrigin:NO];
self.scrollView.contentSize = self.imageView.frame.size;
CGRect drawRect = self.scrollView.frame;
CGFloat scaleWidth = drawRect.size.width / svgSize.width;
CGFloat scaleHeight = drawRect.size.height / svgSize.height;
CGAffineTransform pathTransform = CGAffineTransformConcat(CGAffineTransformMakeTranslation(drawRect.origin.x / scaleWidth, drawRect.origin.y / scaleHeight), CGAffineTransformMakeScale(scaleWidth , scaleHeight));
CGPathRef transformedPath = CGPathCreateCopyByTransformingPath(svgPath.CGPath, &pathTransform);
UIBezierPath *clipPath = [UIBezierPath bezierPathWithCGPath:transformedPath];
UIBezierPath *path = [UIBezierPath bezierPathWithRect:UIScreen.mainScreen.bounds];
[path appendPath:clipPath];
self.maskLayer.path = path.CGPath;
3.计算出图片缩放后需要裁剪的位置
SVGBezierPath *svgPath = [SVGBezierPath pathsFromSVGAtURL:[NSURL fileURLWithPath:self.filepath]].firstObject;
CGSize svgSize = SVGBoundingRectForPaths(@[svgPath]).size;
CGFloat imageScale = self.imageView.frame.size.width / self.imageView.image.size.width;
CGFloat svgWidth = self.scrollView.frame.size.width / imageScale;
CGFloat svgHeight = svgSize.height * svgWidth / svgSize.width;
// 计算svg缩放比
CGAffineTransform pathTransform = CGAffineTransformMakeScale(svgWidth / svgSize.width, svgHeight / svgSize.height);
CGPathRef transformedPath = CGPathCreateCopyByTransformingPath(svgPath.CGPath, &pathTransform);
UIBezierPath *path = [UIBezierPath bezierPathWithCGPath:transformedPath];
UIGraphicsBeginImageContextWithOptions(CGSizeMake(svgWidth, svgHeight), NO, 1.0);
[path addClip];
// 计算绘制位置
CGFloat svgX = self.scrollView.contentOffset.x / imageScale;
CGFloat svgY = self.scrollView.contentOffset.y / imageScale;
[self.imageView.image drawAtPoint:CGPointMake(-svgX, -svgY)];
// 生成裁切后的图片
UIImage *clipImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();