2008-11-04 66 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];