2014-01-12 27 views
2

当涉及到将照片剪裁到自定义UIBezierPath时,我遇到了问题。它并不是在路径中显示区域,而是显示照片的另一部分(不同的大小和位置,而不是应该在的位置,但仍与绘制的形状相同)。注意我还想保留原始照片的完整质量。在保留图像质量的同时将UIImage剪裁到自定义UIBezierPath

我在下面添加了照片和标题,以更深入地解释我的问题。如果有人能给我另一种办法来做这样的事情,我会很乐意重新开始。

The user draws a UIBezierPath with his finger 以上是UIImageView中的UIImage的示意图,所有UIView内的显示UIBezierPath的CAShapeLayer都是子图层。对于这个例子,假定红色路径是由用户绘制的。

Visualization 在该图中是CAShapeLayer和使用原始图像大小创建的图形上下文。我如何剪辑上下文以便产生下面的结果(请原谅它的混乱)?

The result 这就是我希望在完成所有工作时产生的结果。注意我希望它仍然与原始尺寸/质量相同。

下面是我的一些代码相关部分:一个路径

-(UIImage *)maskImageToPath:(UIBezierPath *)path { 
    // Precondition: the path exists and is closed 
    assert(path != nil); 


    // Mask the image, keeping original size 
    UIGraphicsBeginImageContextWithOptions(self.size, NO, 0); 

    [path addClip]; 
    [self drawAtPoint:CGPointZero]; 

    // Extract the image 
    UIImage *maskedImage = UIGraphicsGetImageFromCurrentImageContext(); 
    UIGraphicsEndImageContext(); 

    return maskedImage; 
} 

这增加了指向UIBezierPath

- (void)drawClippingLine:(UIPanGestureRecognizer *)sender { 
    CGPoint nextPoint = [sender locationInView:self]; 

    // If UIBezierPath *clippingPath is nil, initialize it. 
    // Otherwise, add another point to it. 
    if(!clippingPath) { 
     clippingPath = [UIBezierPath bezierPath]; 
     [clippingPath moveToPoint:nextPoint]; 
    } 
    else { 
     [clippingPath addLineToPoint:nextPoint]; 
    } 

    UIGraphicsBeginImageContext(_image.size); 
    [clippingPath stroke]; 
    UIGraphicsEndImageContext(); 


} 
+0

所有的图像都是一个角度,你应用变换?显示您实现的实际结果的屏幕截图。 – Wain

回答

1

你得到不正确的作物

这个剪辑图像因为UIImage被缩放以适应UIImageView。基本上这意味着您必须将UIBezierPath坐标转换为UIImage内的正确坐标。最简单的方法是使用UIImageView类别,该类别将UIImageView中的点从一个视图(本例中为UIBezierPath,即使它不是真正的视图)转换为正确的点。 你可以看到这样一个类别here的例子。更具体地说,您需要使用该类别中的convertPointFromView:方法来转换您的UIBezierPath中的每个点。 (对不起,没有完整的代码,我在我的手机上输入)

+0

这正是我想要的!我对这个问题有一种模糊的认识,你只能证实它。如果我只知道更早的话,这将会为我节省很多时间! – thebradbain

+0

@thebradbain很高兴帮助你。如果您遇到使用它的问题,请告诉我。 – Gad