views:

22

answers:

1

Hi everybody,
I am trying to create CGImage from NSTextField.
I got some success in this. Still I cant get CGImage that consisting of only text. I mean to say that,every time capturing the textfield I am getting color of the background window along with it.(Looks like I am not getting alpha channel info)

I tried following snippet from 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;


Any help to get CGImage without background color?

+1  A: 

-initWithFocusedViewRect: reads from the window backing store, so essentially it's a screenshot of that portion of the window. That's why you're getting the window background color in your image.

-[NSView cacheDisplayInRect:toBitmapImageRep:] is very similar, but it causes the view and its subviews, but not its superviews, to redraw themselves. If your text field is borderless, then this might suffice for you. (Make sure to use -bitmapImageRepForCachingDisplayInRect: to create your NSBitmapImageRep!)

There's one more option that might be considered even more correct than the above. NSTextField draws its content using its NSTextFieldCell. There's nothing really stopping you from just creating an image with the appropriate size, locking focus on it, and then calling -drawInteriorWithFrame:inView:. That should just draw the text, exactly as it was drawn in the text field.

Finally, if you just want to draw text, don't forget about NSStringDrawing. NSString has some methods that will draw with attributes (drawAtPoint:withAttributes:), and NSAttributedString also has drawing methods (drawAtPoint:). You could use one of those instead of asking the NSTextFieldCell to draw for you.

kperryua
Actually, I am going to generate textures from the CGImage. Anyway thanks for your soln,I will be back soon.
shakthi
That's fine. All of the above methods produce an NSImage or NSBitmapImageRep which you can create a CGImage from.
kperryua
Its working fine, Thanks.
shakthi