2015-11-18 43 views
1

當我試圖用像素陣列CoreGraphics中繪製的圖像在我的像素陣列忽略。阿爾法使用CGBitmapContextCreate

我的形象是568x320這裏是我的代碼:

int k = 0; 
unsigned char pixels[320 * 568*4]; 
for(int i = 0; i<568/1;i++) { 
    for(int j = 0; j<320/1;j++) { 
     pixels[k] = 212; //B 
     pixels[k+1] = 2; //G 
     pixels[k+2] = 87;//R 
     pixels[k+3] = drand48()*255; //A 
     k+=4; 
    } 
} 
void *baseAddress = &pixels; 


NSUInteger bitsPerComponent = 8; 

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); 

CGContextRef context = CGBitmapContextCreate(baseAddress, 568, 320, 8, 4*568, colorSpace, kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedFirst); 

CGImageRef cgImage = CGBitmapContextCreateImage(context); 

CGContextRelease(context); 
CGColorSpaceRelease(colorSpace); 

UIImage *textureImage = [UIImage imageWithCGImage:cgImage]; 

基本上,顏色看起來正確的,但沒有透明度。如果alpha爲0,則圖像爲黑色,否則爲藍色。

任何想法,爲什麼我越來越沒有透明度?

編輯:

這裏是我的結果,我和阿爾法

current result expected result

想到我買了

for(int i = 0; i<568/1;i++) { 
    for(int j = 0; j<320/1;j++) { 
     [[UIColor colorWithRed:87./255 green:2.0/255 blue:212.2/255 alpha:drand48()] setFill]; 
     CGContextFillRect(ctx, CGRectMake(i, j, 1, 1)); 
    } 
} 

第二個結果的結果,但相比它的極其緩慢到CGBitmapContextCreate

+0

您是否嘗試過「正常」的設置與RGB秩序和單獨'kCGImageAlphaPremultipliedLast'標誌? – Kegluneq

+0

你是指什麼正常設置?去ARGB而不是BGRA? – Neva

+0

我的意思是rgba(因此'kCGImageAlphaPremultipliedLast'標誌)。 – Kegluneq

回答

1

您錯誤地使用了CGBitmapContextCreate。第一個參數是目的地,而不是數據源。你甚至不需要創建位圖上下文來創建CGImage。檢查下面的代碼。

int k = 0; 
unsigned char pixels[320*568*4]; 
for(int i=0; i<568; i++) { 
    for(int j=0; j<320; j++) { 
     pixels[k] = 87; //R 
     pixels[k+1] = 2; //G 
     pixels[k+2] = 212; //B 
     pixels[k+3] = drand48()*255; //A 
     k+=4; 
    } 
} 

CGDataProviderRef data = CGDataProviderCreateWithData(NULL, &pixels, 320*568*4*sizeof(char), NULL); 
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); 

CGImageRef cgImg = CGImageCreate(568, 320, 8, 4*8, 4*568, colorSpace, kCGBitmapByteOrderDefault | kCGImageAlphaLast, data, NULL, true, kCGRenderingIntentDefault); 
UIImage *textureImage = [UIImage imageWithCGImage:cgImg]; 

CGColorSpaceRelease(colorSpace); 
CGDataProviderRelease(data); 
CGImageRelease(cgImg); 

如果要更改顏色順序,請使用kCGBitmapByteOrderDefault | kCGImageAlphaLast標誌進行播放。

Btw。你爲什麼在循環條件下除以1?

+0

它的工作表示感謝。爲了測試的目的,我除以1之前將其除以1,並且將1以更快的類型輸入。謝謝 – Neva