2008-11-04 67 views
5

我需要將來自NSProgressIndicator的圖像放入NSOutlineView單元格。我已經寫了代碼,做這行確定的指標和它的作品好了:從NSProgressIndicator獲取NSImage

NSProgressIndicator *progressIndicator = [[NSProgressIndicator alloc] initWithFrame:NSMakeRect(0, 0, 16, 16)]; 
[progressIndicator setStyle:NSProgressIndicatorSpinningStyle];   
[progressIndicator setIndeterminate:NO]; 
[progressIndicator setMaxValue:100.0]; 
[progressIndicator setDoubleValue:somePercentage];   

NSImage *updateImage = [[NSImage alloc] initWithData:[progressIndicator dataWithPDFInsideRect:[progressIndicator frame]]]; 
[progressIndicator release]; 


return [updateImage autorelease]; 

我試圖修改代碼也給我不確定的指針影像。但對於不確定的情況,我總是會得到一張空白的16x16圖像。 (我已經通過在每種情況下將圖像寫入文件來確認這一點,確定的情況給了我進度指示器圖像,不確定的情況始終是16x16白色正方形)。

修改後的代碼是:

if(self.lengthUnknown) 
{ 
    NSProgressIndicator *progressIndicator = [[NSProgressIndicator alloc] initWithFrame:NSMakeRect(0, 0, 16, 16)]; 
    [progressIndicator setStyle:NSProgressIndicatorSpinningStyle];   
    [progressIndicator setIndeterminate:YES]; 

    NSImage *updateImage = [[NSImage alloc] initWithData:[progressIndicator dataWithPDFInsideRect:[progressIndicator frame]]]; 
    [progressIndicator release]; 


    return [updateImage autorelease]; 
} 
else 
{ 
// Same code as the first listing, this case works fine 
} 

做不確定的進度指標使用某種類型的繪圖導致-dataWithPDFInsideRect:是無法捕捉到自己的形象?


的更多信息:我試着設置進度指示器不使用螺紋動畫,以及試圖通過NSImage中的lockFocus方法來獲取內容如下建議,但那些都嘗試了一定的作用。

Dave在下面提到的進度指示器單元代碼(AMIndeterminateProgressIndicatorCell)是一個很好的解決方法,但我仍然想知道爲什麼我不能使用與確定模式一起使用的相同技術。

回答

2

進度指示器使用一個後臺線程來保持自己的動畫描繪即使主線程忙於做其他事情,所以有可能這就是造成問題。你可能會嘗試在繪圖前調用setUsesThreadedAnimation:NO進度指示器,看看是否有所作爲。

另一個方法是創建一個空白的NSImage,然後調用進度指示器的drawRect:方法將其內容渲染到圖像緩衝區中。那看起來像這樣:

 
NSProgressIndicator* progressIndicator; 
NSImage* image = [[NSImage alloc] initWithSize:[progressIndicator bounds].size]; 
[image lockFocus]; 
[progressIndicator drawRect:[progressIndicator bounds]]; 
[image unlockFocus];