2011-11-03 27 views
2

我有一個CGContextRef,可以在它上面繪製並指定alpha,如果我嘗試並使用它,它可以很好地工作。但是,我試圖對它進行着色(當前是紅色或綠色),但無論選擇哪種混合模式,Alpha都設置爲1(因爲我使用alpha作爲1)。畫出正確的顏色並不是一個真正可行的選擇,因爲我希望能夠從文件系統加載顏色UIImage,所以我應該如何實現這一點?Colourise CGContextRef但是保留阿爾法

編輯:實施例的代碼(寬度和高度是預定義的浮標,點是位於上下文和顏色內的所有的CGPoints的陣列具有100%的不透明度一個的UIColor) -

UIGraphicsBeginImageContext(CGSizeMake(width,height)); 

CGContextRef contextRef = UIGraphicsGetCurrentContext(); 
CGContextClearRect(contextRef, CGRectMake(0.0f, 0.0f, width, height)); 
CGContextSetRGBStrokeColor(contextRef, 0.0f, 0.0f, 0.0f, 1.0f); 
CGContextSetRGBFillColor(contextRef, 1.0f, 1.0f, 1.0f, 1.0f); 
CGContextSetLineWidth(contextRef, lineWidth); 

CGContextBeginPath(contextRef); 
CGContextMoveToPoint(contextRef, points[0].x, points[0].y); 
for (int i = 1; i < 4; i++) { 
    CGContextAddLineToPoint(contextRef, points[i].x, points[i].y); 
} 
CGContextAddLineToPoint(contextRef, points[0].x, points[0].y); // Encloses shape 

CGContextDrawPath(contextRef, kCGPathFillStroke); 

[color setFill]; 

CGContextBeginPath(contextRef); 
CGContextSetBlendMode(contextRef, kCGBlendModeMultiply); 
CGContextAddRect(contextRef, CGRectMake(0.0f, 0.0f, width, height)); 
CGContextDrawPath(contextRef, kCGPathFill); 

UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); 
UIGraphicsEndImageContext(); 

謝謝你提前尋求你的幫助,
jrtc27

+0

你能給我們一些例子的代碼,所以我們可以更好地看看你的問題? –

+0

請參閱我的編輯。 – jrtc27

+0

好吧,這有助於。我試圖抓住你的想法,所以請告訴我,如果我是正確的。 從我在這裏看到的是你正在試圖繪製一個黑色的邊框沒有透明度的白色矩形。然後你做一個未知的函數[color setFill];我不知道它是幹什麼的(即使這些名字爲自己說話,你也可能想給我們一些信息)。然後,您正在繪製另一條具有相同尺寸的路徑,並放在前面的矩形上。然後,您想要繪製該圖並將其存儲在該圖像var中。 –

回答

2

問題是我需要一個CGContextClipToMask。這意味着需要以下我的代碼:

CGContextTranslateCTM(contextRef, 0, height); 
CGContextScaleCTM(contextRef, 1.0, -1.0); 

轉換的座標,然後

CGRect rect = CGRectMake(0.0f, 0.0f, width, height); 
CGContextClipToMask(contextRef, rect, UIGraphicsGetImageFromCurrentImageContext().CGImage); 

修復它。