CGImageRef 不 init/alloc 正确

CGImageRef not init/alloc correctly

我目前在使用 CGImageRef 时遇到问题。

每当我创建一个 CGImageRef 并在调试器视图中查看它时,在 Xcode 中,它是 nil

代码如下:

-(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);
    }
}

其他一切似乎都正常。我不明白。任何帮助将不胜感激。

注意:self.pixelView 是一个 NSImageView 实例,尚未以任何方式覆盖。

很可能 local_point 不在图片内。您已将点从 window 转换为视图坐标,但这可能不等同于图像坐标。测试它以查看图像的左下角是否导致 local_point(0,0)

不清楚你的视图是如何布局的,但我怀疑你想要做的是减去用户正在与之交互的任何区域(可能是子视图)相对于 self 的原点。

好的,我明白了。


我用来创建 CGImageRef 的是:

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

显然我应该使用的是:

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

我想我的问题是出于某种原因我认为 NSImageCGImageRef 有免费桥接。

看来我错了