2013-12-07 32 views
2

給定一個被繪製到上下文然後轉換爲CGImageRef的路徑,我將如何剪切上下文(它具有提供的前景圖像),以便所述上下文被CGImage(之前是一條路徑)所掩蓋?剪切當前上下文,以便通過路徑屏蔽它

下面的代碼應該更好地說明我的觀點,如果它不完全清楚。請注意,所有這些都在UIView的drawRect:方法中調用,並且scaledImageRectangle(UIImage * image,CGRect矩形)函數僅返回一個矩形。

// Close the path 
    CGContextClosePath(context); 
    CGContextDrawPath(context, kCGPathFillStroke); 

    // Mask the image 
    CGImageRef mask = CGBitmapContextCreateImage(context); 
    [foregroundImage drawInRect:scaledImageRectangle(foregroundImage, rect)]; 
    CGContextClipToMask(context, scaledImageRectangle(foregroundImage, rect), mask); 

    // Finally draw the masked image 
    UIImage *maskedImage = [UIImage imageWithCGImage:CGBitmapContextCreateImage(context)]; 
    [maskedImage drawInRect:scaledImageRectangle(foregroundImage, rect)]; 

例如,這裏是表示路徑 Before mask

而且這裏的黑色輪廓的圖像是圖像會是什麼樣掩蓋時像 After mask

+2

請退後一步並解釋您嘗試實現的最終結果。你這樣做的方式很奇怪。通常,要剪輯到某個路徑,您只需調用'CGContextClip(path)'或' - [UIBezierPath addClip:]' - 您不需要將路徑轉換爲圖像。 –

+0

另外,'context'是來自'UIGraphicsGetCurrentContext()'的當前上下文,還是它是您創建的獨立上下文? –

+0

謝謝,我現在正在研究這個問題。它會完成與掩蓋圖像相同的事情嗎? – thebradbain

回答

3

我可能會傾向於建設(我使用UIBezierPath),然後您的自定義視圖可以使用該路徑剪切圖像,以及撫摸圍繞該剪切圖像的路徑:

- (void)drawRect:(CGRect)rect 
{ 
    CGContextRef context = UIGraphicsGetCurrentContext(); 

    CGContextSaveGState(context); 

    if (self.isClipped) { 
     CGContextAddPath(context, [self.path CGPath]); 
     CGContextClip(context); 
    } 

    [self.image drawInRect:self.bounds]; 

    CGContextRestoreGState(context); 

    [[UIColor blackColor] setStroke]; 
    self.path.lineWidth = 4.0; 
    [self.path stroke]; 
} 

unclippedclipped

如果你想繪製路徑作爲觸摸進來,我個人會渲染通過單獨CAShapeLayer(避免圖像的不必要重繪)。