2012-03-22 43 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