Re: Drawing an NSImage in a CALayer
Re: Drawing an NSImage in a CALayer
- Subject: Re: Drawing an NSImage in a CALayer
- From: David Duncan <email@hidden>
- Date: Thu, 18 Sep 2008 16:30:10 -0700
On Sep 18, 2008, at 3:33 PM, Brad Gibbs wrote:
The PNG is in the main bundle -- in my Resources folder.
You can do this to get a CGImageRef directly. (written in Mail, no
error checking).
CFURLRef imageURL = CFBundleCopyResourceURL(CFBundleGetMainBundle(),
(CFStringRef)@"myImage.png", NULL, NULL);
CGImageSourceRef imageSource = CGImageSourceCreateWithURL(imageURL,
NULL);
CFRelease(imageURL);
CGImageRef image = CGImageSourceCreateImageAtIndex(imageSource, 0,
NULL);
CFRelease(imageSource);
Then you can assign 'image' to your layer's contents.
On Sep 18, 2008, at 3:18 PM, Matt Long wrote:
Use this code:
- (CGImageRef)nsImageToCGImageRef:(NSImage*)image;
{
NSData * imageData = [image TIFFRepresentation];
CGImageRef imageRef;
if(imageData)
{
CGImageSourceRef imageSource =
CGImageSourceCreateWithData(
(CFDataRef)imageData, NULL);
imageRef = CGImageSourceCreateImageAtIndex(
imageSource, 0, NULL);
}
return imageRef;
}
While this code is popular, I wouldn't recommend it as a general
conversion. Creating a TIFF representation in order to generate a
CGImageRef is going to be considerably more costly than a more direct
alternative. Instead I would recommend creating a CGBitmapContext,
drawing the NSImage to it and then extracting a CGImageRef from the
bitmap context. Something like this (again, written in Mail, no error
checking).
CGColorSpaceRef genericRGB =
CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB);
CGContextRef context = CGBitmapContextCreate(NULL, desiredWidth,
desiredHeight, 8, 0, genericRGB, kCGImageAlphaPremultipliedFirst);
NSGraphicsContext *nsGraphicsContext = [NSGraphicsContext
graphicsContextWithGraphicsPort:context flipped:NO];
[NSGraphicsContext saveGraphicsState];
[myNSImage drawAtPoint:NSZeroPoint fromRect:NSZeroRect
op:NSCompositeCopy fraction:1.0];
[NSGraphicsContext setCurrentContext:nsGraphicsContext];
CGImageRef image = CGBitmapContextCreateImage(context);
CFRelease(context);
--
David Duncan
Apple DTS Animation and Printing
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden