【发布时间】:2012-08-31 23:52:47
【问题描述】:
我已经在 iOS 上编程两年了,从来没有在 mac 上编程。我正在开发一个小实用程序来处理我在 iOS 开发中的一些简单图像需求。无论如何,我在 iOS 中有可以完美运行的工作代码,但我完全不知道 mac 的等价物是什么。
我尝试了很多不同的方法,但我真的不明白如何在 Mac 上的“drawRect:”方法之外启动图形上下文。在 iPhone 上,我只使用 UIGraphicsBeghinImageContext()。我知道其他帖子说过要使用 lockFocus/unlockFocus,但我不确定如何准确地满足我的需要。哦,我真的很想念 UIImage 的“CGImage”属性。我不明白为什么 NSImage 不能有一个,尽管听起来比这有点棘手。
这是我在 iOS 上的工作代码——基本上它只是从蒙版创建一个反射图像并将它们组合在一起:
UIImage *mask = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle]pathForResource:@"Mask_Image.jpg" ofType:nil]];
UIImage *image = [UIImage imageNamed::@"Test_Image1.jpg"];
UIGraphicsBeginImageContextWithOptions(mask.size, NO, [[UIScreen mainScreen]scale]);
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(ctx, 0.0, mask.size.height);
CGContextScaleCTM(ctx, 1.f, -1.f);
[image drawInRect:CGRectMake(0.f, -mask.size.height, image.size.width, image.size.height)];
UIImage *flippedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
CGImageRef maskRef = mask.CGImage;
CGImageRef maskCreate = CGImageMaskCreate(CGImageGetWidth(maskRef),
CGImageGetHeight(maskRef),
CGImageGetBitsPerComponent(maskRef),
CGImageGetBitsPerPixel(maskRef),
CGImageGetBytesPerRow(maskRef),
CGImageGetDataProvider(maskRef), NULL, false);
CGImageRef masked = CGImageCreateWithMask([flippedImage CGImage], maskCreate);
CGImageRelease(maskCreate);
UIImage *maskedImage = [UIImage imageWithCGImage:masked];
CGImageRelease(masked);
UIGraphicsBeginImageContextWithOptions(CGSizeMake(image.size.width, image.size.height + (image.size.height * .5)), NO, [[UIScreen mainScreen]scale]);
[image drawInRect:CGRectMake(0,0, image.size.width, image.size.height)];
[maskedImage drawInRect:CGRectMake(0, image.size.height, maskedImage.size.width, maskedImage.size.height)];
UIImage *anotherImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
//do something with anotherImage
对于在 Mac 上(简单地)实现这一点有什么建议吗?
【问题讨论】:
-
简单:
(CGContextRef)[[NSGraphicsContext currentContext] graphicsPort] -
这会启动图形上下文吗?如果是这样,我如何将图像绘制到其中并检索它们(如 UIGraphicsGetImageFromCurrentImageContext())。另外,我将如何在 NSImage 和 CGImage 之间切换?
-
添加了 Swift 版本:stackoverflow.com/a/34361216/1226095
标签: ios macos core-graphics converter cgcontext