2014-01-12 30 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