0

我正在尝试从 NSTextField 创建 CGImage。
我在这方面取得了一些成功。我仍然无法获得仅包含文本的 CGImage。我的意思是说,每次捕获文本字段时,我都会得到背景窗口的颜色。(看起来我没有得到 alpha 通道信息)

我尝试了以下来自http://www.cocoadev.com/index.pl?ConvertNSImageToCGImage的片段

 
NSBitmapImageRep * bm = [NSBitmapImageRep alloc];
[theView lockFocus];
[bitmap initWithFocusedViewRect:[theView bounds]];
[theView unlockFocus]

[bma retain];// data provider will release this
int     rowBytes, width, height;

rowBytes = [bm bytesPerRow];
width = [bm pixelsWide];
height = [bm pixelsHigh];

CGDataProviderRef provider = CGDataProviderCreateWithData( bm, [bm bitmapData], rowBytes * height, BitmapReleaseCallback );
CGColorSpaceRef colorspace = CGColorSpaceCreateWithName( kCGColorSpaceGenericRGB );
CGBitmapInfo    bitsInfo = kCGImageAlphaPremultipliedLast;

CGImageRef img = CGImageCreate( width, height, 8, 32, rowBytes, colorspace, bitsInfo, provider, NULL, NO, kCGRenderingIntentDefault );

CGDataProviderRelease( provider );
CGColorSpaceRelease( colorspace );

return img;


获得没有背景颜色的 CGImage 有什么帮助吗?

4

1 回答 1

1

-initWithFocusedViewRect:从窗口后备存储读取,所以本质上它是窗口那部分的屏幕截图。这就是您在图像中获得窗口背景颜色的原因。

-[NSView cacheDisplayInRect:toBitmapImageRep:]非常相似,但它会导致视图及其子视图(而不是其父视图)重绘自己。如果您的文本字段是无边界的,那么这对您来说可能就足够了。(确保用于-bitmapImageRepForCachingDisplayInRect:创建您的 NSBitmapImageRep!)

还有一个选项可能被认为比上述更正确。NSTextField 使用它的 NSTextFieldCell 绘制它的内容。没有什么能真正阻止您创建具有适当大小的图像,锁定焦点,然后调用-drawInteriorWithFrame:inView:. 那应该只是绘制文本,就像在文本字段中绘制的一样。

最后,如果您只想绘制文本,请不要忘记NSStringDrawing. NSString 有一些方法可以使用属性(drawAtPoint:withAttributes:)进行绘制,NSAttributedString 也有绘制方法(drawAtPoint:)。您可以使用其中之一,而不是要求 NSTextFieldCell 为您绘制。

于 2010-08-06T13:52:43.757 回答