2012-03-22 42 views
10

在Mac OSX(可可)绘制到屏幕外的图像,这是很容易使特定大小的空白图像,并绘制到其关闭屏幕:的UIImage VS NSImage中:在IOS

NSImage* image = [[NSImage alloc] initWithSize:NSMakeSize(64,64)]; 
[image lockFocus]; 
/* drawing code here */ 
[image unlockFocus]; 

然而,在iOS(可可触摸)中,似乎没有对UIImage的等效调用。我想使用UIImage(或其他等效类)来做同样的事情。也就是说,我想制作一个明确的尺寸,最初是空的图像,我可以使用像UIRectFill(...)[UIBezierPath stroke]这样的调用来绘制图像。

我该怎么做?

回答

8

CoreGraphics在这里所需要,为的UIImage不具备高水平的功能,如你解释什么..

UIGraphicsBeginImageContext(CGSizeMake(64,64)); 

CGContextRef context = UIGraphicsGetCurrentContext(); 
// drawing code here (using context) 

UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); 
UIGraphicsEndImageContext(); 
3

你能做到这一点,如下所示:

UIGraphicsBeginImageContext(CGSizeMake(64, 64)); 
//Drawing code here 
UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); 
UIGraphicsEndImageContext(); 

这里是苹果公司的Graphics and Drawing参考。

+1

但不要忘了,结束图像内容! – 2012-03-22 19:59:50

+0

是的,我忘了复制它。 – sch 2012-03-22 20:01:48

+0

好吧,我认为这相当于创建'NSImage'并调用'lockFocus',但我将如何解锁焦点? – mtmurdock 2012-03-22 20:01:48

0

事情是这样的:

UIGraphicsBeginImageContextWithOptions(mySize, NO, 0.0f);  
CGContextRef context = UIGraphicsGetCurrentContext(); 
UIGraphicsPushContext(context); 

[myImage drawInRect:myImageRect]; 
[myText drawAtPoint:myOrigin withFont:myFont]; 

UIGraphicsPopContext(); 
UIImage *myNewImage = UIGraphicsGetImageFromCurrentImageContext(); 
UIGraphicsEndImageContext(); 
+0

注意,您需要使用UIGraphicsBeginImageContextWithOptions而不是UIGraphicsBeginImageContext,以便绘制设备支持的比例尺。使用UIGraphicsBeginImageContext在视网膜显示上看起来很差。 – 2012-03-22 20:02:56

+2

'UIGraphicsPushContext(context);'和'UIGraphicsPopContext();'可以被移除,因为'UIGraphicsBeginImageContextWithOptions(mySize,NO,0.0f);'和'UIGraphicsEndImageContext();'已经做到了。 – sch 2012-03-22 20:11:20

+0

是的,我想知道这件事。谢谢。 – 2012-03-22 20:17:45