Search code examples
objective-cnsimagecgimageref

CGImageRef not init/alloc correctly


I am currently having problems with CGImageRef.

Whenever I create a CGImageRef and look at it in debugger view, in Xcode, it is nil.

Here's the code:

-(void)mouseMoved:(NSEvent *)theEvent{
    if (self.shoulddrag) {
        NSPoint event_location = [theEvent locationInWindow];//direct from the docs
        NSPoint local_point = [self convertPoint:event_location fromView:nil];//direct from the docs

        CGImageRef theImage = (__bridge CGImageRef)(self.image);
        CGImageRef theClippedImage = CGImageCreateWithImageInRect(theImage, CGRectMake(local_point.x,local_point.y,1,1));

        NSImage * image = [[NSImage alloc] initWithCGImage:theClippedImage     size:NSZeroSize];

        self.pixleView.image = image;
        CGImageRelease(theClippedImage);
    }
}

Everything else seems to be working though. I can't understand. Any help would be appreciated.

Note: self.pixelView is an NSImageView instance that has not been overridden in any way.


Solution

  • Alright, I figured it out.


    What I was using to create the CGImageRef was:

        CGImageRef theImage = (__bridge CGImageRef)(self.image);
    

    Apparently what I should have used is:

        CGImageSourceRef theImage = CGImageSourceCreateWithData((CFDataRef)[self.image TIFFRepresentation], NULL);
    

    I guess my problem was that for some reason I thought NSImage and CGImageRef had toll free bridging.

    Apparently, I was wrong.