如何将UIKit的UIImage:drawInRect方法改为AppKit的NSImage:drawInRect方法

5
我正在将一个iPhone应用移植到Mac应用程序,因此我需要将所有与UIKit相关的类更改为AppKit。如果您能帮助我,我会非常感激。以下是最好的方法吗?
iPhone应用程序-->使用UIKit
UIGraphicsPushContext(ctx);
[image drawInRect:rect];
UIGraphicsPopContext();

Mac Os --使用 AppKit

[NSGraphicsContext saveGraphicsState];
NSGraphicsContext * nscg = [NSGraphicsContext graphicsContextWithGraphicsPort:ctx flipped:YES];
[NSGraphicsContext setCurrentContext:nscg];
NSRect rect = NSMakeRect(offset.x * scale, offset.y * scale, scale * size.width, scale * size.height);
[NSGraphicsContext restoreGraphicsState];

[image drawInRect:rect fromRect:NSMakeRect( 0, 0, [image size].width, [image size].height )
        operation:NSCompositeClear
         fraction:1.0];
1个回答

6

文档参考手册是你的好朋友;它们会解释很多你在这里误用的东西。

[NSGraphicsContext saveGraphicsState];
NSGraphicsContext * nscg = [NSGraphicsContext graphicsContextWithGraphicsPort:ctx flipped:YES];
[NSGraphicsContext setCurrentContext:nscg];
您可以在当前上下文中保存图形状态,然后立即创建一个新的上下文并将其设置为当前上下文。
NSRect rect = NSMakeRect(offset.x * scale, offset.y * scale, scale * size.width, scale * size.height);

显然这就是您保存的全部内容。创建一个矩形不受gstate影响,因为它不是绘图操作(矩形只是一组数字;您这里没有“画”一个矩形)。

此外,您应该使用当前的转换矩阵进行缩放。

[NSGraphicsContext restoreGraphicsState];
然后你需要在创建的上下文中恢复,而不是在保存时恢复。
【编辑】再次查看这个问题,一年半后,我认为你将saveGraphicsStaterestoreGraphicsState方法解释为UIGraphicsPushContextUIGraphicsPopContext的对应项。它们并不是;saveGraphicsStaterestoreGraphicsState将当前上下文的图形状态推入和弹出。当前上下文是单独控制的(setCurrentContext:),并且没有推入/弹出API。【/编辑】
我假设你在CALayer的drawInContext:方法中?如果这是在NSView中,则已经有一个当前上下文,不需要(也不应该)创建一个。
[image drawInRect:rect fromRect:NSMakeRect( 0, 0, [image size].width, [image size].height )
        operation:NSCompositeClear
         fraction:1.0];
NSCompositeClear操作会清除目标像素,就像您最喜欢的绘画程序中的橡皮擦工具一样。它不会绘制图像。您需要使用NSCompositeSourceOver操作

供将来参考:_实例_方法 -[NSGraphicsContext save|restoreGraphicsState] 确实会推送/弹出这些消息的接收者的图形状态。然而,同名的 _类_方法 +[NSGraphicsContext save|restoreGraphicsState] 却会推送/弹出上下文 - Martin Winter

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接