我想在代碼中繪製一個alpha蒙版圖像。現在我做:如何爲alpha蒙版圖像創建位圖上下文?
1)創建一個位圖上下文使用CGBitmapContextCreate
與選項CGColorSpaceCreateDeviceRGB
和kCGImageAlphaPremultipliedFirst
。
2)然後,我在這個背景下,只使用像白色和黑色的灰度色。
3)然後,我使用CGImageMaskCreate
從該上下文創建一個遮罩圖像。
結論:我浪費了很多內存!因爲從我的理解來看,蒙版圖像只有灰度,對嗎?那麼爲什麼要首先在ARGB中創建一個上下文。
如何創建一個旨在用於繪製遮罩圖像的CGContextRef?我的想法是使用CGColorSpaceCreateDeviceGray
,但這裏的問題開始。這是確切的代碼我如何創建我的ARGB位圖背景:
CGContextRef context = NULL;
CGColorSpaceRef colorSpace;
uint32_t * bitmapData;
int imageWidth = round(size.width);
int imageHeight = round(size.height);
int bitmapBytesPerRow = (imageWidth * 4);
int bitmapByteCount = (bitmapBytesPerRow * imageHeight);
colorSpace = CGColorSpaceCreateDeviceRGB();
bitmapData = malloc(bitmapByteCount);
context = CGBitmapContextCreate(bitmapData,
imageWidth,
imageHeight,
8, // bits per component
bitmapBytesPerRow,
colorSpace,
kCGImageAlphaPremultipliedFirst);
CGColorSpaceRelease(colorSpace);
我不知道如何計算bitmapBytesPerRow
這樣的背景下。我認爲這只是imageWidth
?我必須提供什麼bits per component
CGBitmapContextCreate
?
有CGColorSpaceGetNumberOfComponents()
但它只報告組件數量。這並不能告訴我一個組件有多少個字節。
還有什麼讓我感到緊張的是4
和8
是硬編碼在我的代碼上面。誰說它每個組件總是4個字節,誰說它是每個組件8位?我只是從那裏的各種示例代碼中拿出這個。每個人似乎都這樣做。有用。但未來的證據?可能不會。
你會讓我的一天有一些很好的答案。謝謝。
編輯:我發現了一個代碼片段,但令人困惑:
CGColorSpaceRef colorSpace2 = CGColorSpaceCreateDeviceGray();
CGContextRef gradientBitmapContext = CGBitmapContextCreate (NULL, 1, reflectRect.size.height,8, 0, colorSpace2, kCGImageAlphaNone);
爲什麼0每行的字節?文檔沒有說你可以通過0.看起來錯了。
您還應該使用calloc而不是malloc來在創建圖像之前將圖像清零,否則它將具有隨機像素(如果要使用顏色填充顏色,則不重要)。 – Chris