Objective c 从NSProgressIndicator获取NSImage

Objective c 从NSProgressIndicator获取NSImage,objective-c,cocoa,Objective C,Cocoa,我需要将来自NSProgressIndicator的图像放入NSOutlineView单元格。我已经为一个确定的指标编写了这样的代码,它非常有效: NSProgressIndicator *progressIndicator = [[NSProgressIndicator alloc] initWithFrame:NSMakeRect(0, 0, 16, 16)]; [progressIndicator setStyle:NSProgressIndicatorSpinningStyle];

我需要将来自NSProgressIndicator的图像放入NSOutlineView单元格。我已经为一个确定的指标编写了这样的代码,它非常有效:

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在下面提到的进度指示器单元格代码()是一个很好的解决方法,但我仍然想知道为什么我不能使用与确定模式相同的技术。

我在单元格中使用了不确定的进度指示器。它不是一个真正的NSProgressIndicator,就像它自己绘制的一样,但它是一个相当好的复制品,IMO



(来源:)

即使主线程正忙于做其他事情,进度指示器也会使用背景线程来保持动画绘制,因此这可能是导致问题的原因。在进行绘图之前,可以尝试在进度指示器上调用setUseSThreadAnimation:NO,以查看这是否会产生影响

另一种方法是创建一个空白NSImage,然后调用进度指示器的drawRect:方法将其内容呈现到图像缓冲区中。这看起来像:

NSProgressIndicator* progressIndicator; NSImage* image = [[NSImage alloc] initWithSize:[progressIndicator bounds].size]; [image lockFocus]; [progressIndicator drawRect:[progressIndicator bounds]]; [image unlockFocus]; 进程指示器*进程指示器; NSImage*image=[[NSImage alloc]initWithSize:[progressIndicator bounds].size]; [图像锁定焦点]; [progressIndicator drawRect:[progressIndicator界限]]; [图像解锁焦点];