2010-08-06 53 views
0

我想从NSTextField创建CGImage。
我在这方面取得了一些成功。我仍然不能获得只包含文本的CGImage。我的意思是说,每捕获文本字段我得到的背景画面的颜色与它一起。时间(貌似我没有得到alpha通道信息)从http://www.cocoadev.com/index.pl?ConvertNSImageToCGImage从NSView中检索CGImage


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的帮助?

回答

1

-initWithFocusedViewRect:从窗口后台存储读取,所以基本上它是该窗口部分的屏幕截图。这就是为什么你要在图像中获得窗口背景颜色。

-[NSView cacheDisplayInRect:toBitmapImageRep:]是非常相似,但它会导致视图和它的子视图,但不是它的superviews,重绘自己。如果你的文本域是无边界的,那么这对你来说就足够了。 (请务必使用-bitmapImageRepForCachingDisplayInRect:来创建您的NSBitmapImageRep!)

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

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

+0

其实,我要从CGImage生成纹理。无论如何感谢你的soln,我很快就会回来。 – shakthi 2010-08-06 17:18:55

+0

这很好。以上所有方法都会生成一个NSImage或NSBitmapImageRep,您可以从中创建CGImage。 – kperryua 2010-08-06 19:39:29

+0

其工作正常,谢谢。 – shakthi 2010-08-09 05:04:46