我正在尝试从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不带背景色吗?
发布于 2010-08-06 21:52:44
-initWithFocusedViewRect:从窗口后备存储中读取,因此本质上它是该窗口部分的屏幕截图。这就是为什么你要在你的图像中得到窗口的背景颜色。
-[NSView cacheDisplayInRect:toBitmapImageRep:]非常类似,但它会导致视图及其子视图(而不是其超视图)重新绘制自身。如果您的文本字段是无边框的,那么这可能就足够了。(确保使用-bitmapImageRepForCachingDisplayInRect:创建您的NSBitmapImageRep!)
还有一个选项可能被认为比上面的更正确。NSTextField使用其NSTextFieldCell来绘制其内容。没有什么能真正阻止您创建一个大小合适的图像,将焦点锁定在它上,然后调用-drawInteriorWithFrame:inView:。这应该只绘制文本,与在文本字段中绘制的文本完全相同。
最后,如果您只想绘制文本,请不要忘记NSStringDrawing。NSString有一些使用属性进行绘制的方法(drawAtPoint:withAttributes:),NSAttributedString也有一些绘制方法(drawAtPoint:)。您可以使用其中的一个,而不是要求NSTextFieldCell为您绘图。
https://stackoverflow.com/questions/3423893
复制相似问题