2010-04-21 28 views
4

我將一個iphone應用程序移植到Mac應用程序,我必須將所有UIKit相關的類更改爲AppKit。 如果你能幫助我,這真的很感謝。這是做下面的部分最好的辦法..如何更改UIKit UIImage:drawInRect方法到AppKIt NSImage:drawInRect方法

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]; 

回答

5

The docsthe docs是你的朋友;他們會解釋很多你在這裏濫用的東西。

[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); 

這顯然是所有你gsaved的。創建矩形不受gstate影響,因爲它不是繪圖操作(矩形只是一組數字;您不是在這裏繪製矩形)。

此外,您應該使用當前的transformation matrix作爲比例。

[NSGraphicsContext restoreGraphicsState]; 

然後在你所創建的上下文grestore,而不是一個你gsaved。

[編輯]再次在此尋找了一年半後,我想你誤解作爲UIGraphicsPushContextUIGraphicsPopContext的對應方的saveGraphicsStaterestoreGraphicsState方法。他們不是; saveGraphicsStaterestoreGraphicsState推送並彈出當前上下文的圖形狀態。當前上下文是單獨控制的(setCurrentContext:),並沒有推送/彈出API。 [/編輯]

我假設你在CALayer的drawInContext:方法?如果這是在NSView中,那麼你已經有了一個當前的上下文,並且不需要(也不應該)創建一個上下文。

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

The NSCompositeClear operation清除目的地像素,就像你喜歡的畫圖程序橡皮擦工具。它不繪製圖像。你想要the NSCompositeSourceOver operation