iOS SVG图形裁剪

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();
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值