2012-11-03 29 views
2

我在我的代碼中從頭開始創建NSImage。要啓動予分配的字節的數組:從字節數組創建NSImage的複雜索引錯誤

pixels = malloc((int)(size.width * size.height) * 4 * 8 * sizeof(unsigned char)); 

然後我試圖創建一個測試圖像,即應包含一個梯度從純黑色左邊到右邊純紅色打算:

-(void)generateTestImage{ 
    int idx =0; 
    for(int i=0; i<(int)(size.height); i++){// Rows 
     for (int j=0; j<(int) size.width; j++){// Columns    
      pixels[ idx + 0 ] = 255 * ((float) j/size.width); // r 
      pixels[ idx + 1 ] = 0; // g 
      pixels[ idx + 2 ] = 0; // b 
      pixels[ idx + 3 ] = 255;// a 

      idx += 4; 
     } 
    } 
} 

最後,我的字節數組轉換成使用NSImage

-(void) convertPixelsToImage{ 

    if (renderImage == NULL) 
     renderImage = [[NSImage alloc] initWithSize:size]; 
    else{ 

     NSArray *prevReps = [renderImage representations]; 
     for (id r in prevReps) 
      [renderImage removeRepresentation:r]; 
    } 

    NSLog(@"Creating bitmapImageReprsentation with size:%@", NSStringFromSize(size)); 
    NSBitmapImageRep *imgRep = 
    [[NSBitmapImageRep alloc] initWithBitmapDataPlanes:&pixels 
              pixelsWide:size.width 
              pixelsHigh:size.height 
             bitsPerSample:8 
             samplesPerPixel:sampPerPix 
               hasAlpha:true 
               isPlanar:false 
             colorSpaceName:NSDeviceRGBColorSpace 
              bitmapFormat:0 
              bytesPerRow:0 
              bitsPerPixel:0]; 

    [renderImage addRepresentation:imgRep]; 
} 

然而,得到的圖像是不是我所期望。

enter image description here

下面是一個考慮到分度的縮放偏移 enter image description here

我的我的索引關斷時,作爲梯度圖案由9個像素向左移動每個看來好像行。

另外我通過在圖像底部的白色條紋迷茫......

我已經花了幾個小時嘗試不同的索引方案非其解決問題。我已經驗證我在我的代碼中使用了相同的size。此外,我已驗證所得圖像具有正確的尺寸,但其內容已關閉。

這段代碼有明顯的問題嗎?有想法該怎麼解決這個嗎?

+0

這是一個很好的效果,無一例外。 –

+0

請記住,行被四捨五入到一些邊界 - 我在想像16個像素。 –

+0

@HotLicks,這實際上解決了這個問題。最初的行數是839,當我將它提高到848時,問題得到糾正。我很樂意爲您提供幫助。如果您將此作爲答案發布,我會接受它。我也很想看到一些文檔的鏈接! – slayton

回答

0

請記住,行被四捨五入到一些邊界 - 我在想像16個像素。