2010-07-14 42 views
9

我需要把NSView的內容放在NSImage的實驗項目中。這可能嗎?我做了一些谷歌搜索,嘗試了兩種方法,我發現 - 但他們沒有真正的工作。有什麼建議麼?如何拍攝NSView的「截圖」?

+4

哪些方法沒不工作,爲什麼? – 2010-07-14 23:20:35

回答

19
[[NSImage alloc] initWithData:[view dataWithPDFInsideRect:[view bounds]]]; 
+0

非常感謝。 – Debashis 2010-07-15 02:11:53

+2

+1值得注意的是,儘管這是一般的正確方法,但有些情況下它不起作用,例如像'NSOpenGLView'這樣的視圖有自己的OpenGL渲染上下文。在這種情況下,您需要直接獲取像素數據,並從中創建一個位圖代表,這不太整潔。 – walkytalky 2010-07-19 01:11:06

+0

Obs:陰影和cornerRadius將被忽略 – codrut 2017-09-25 08:30:45

6
let dataOfView = view.dataWithPDFInsideRect(view.bounds) 
let imageOfView = NSImage(data: dataOfView) 
11

從WWDC 2012屆245(翻譯爲SWIFT):

let viewToCapture = self.window!.contentView! 
let rep = viewToCapture.bitmapImageRepForCachingDisplayInRect(viewToCapture.bounds)! 
viewToCapture.cacheDisplayInRect(viewToCapture.bounds, toBitmapImageRep: rep) 

let img = NSImage(size: viewToCapture.bounds.size) 
img.addRepresentation(rep) 
+0

swift 3 let rep = viewToCapture.bitmapImageRepForCachingDisplay(in:viewToCapture.bounds)! viewToCapture.cacheDisplay(在:viewToCapture.bounds,至:REP) 讓IMG = NSImage中(尺寸:viewToCapture.bounds.size) img.addRepresentation(REP) – spacecash21 2017-07-02 17:56:43

+0

注:不總是正常工作。我已經發布了帶有旋轉座標系的標籤。 – Ash 2017-07-04 14:16:30

+0

這對我來說是最好的解決方案,與pdf版本不同,這也是陰影和圓角的原因。與窗口版本不同,這隻能捕捉當前視圖。 Obj C code: ' - (NSImage *)screenCap { \t NSBitmapImageRep * bitmap = [self bitmapImageRepForCachingDisplayInRect:self.bounds]; \t [self cacheDisplayInRect:self.bounds toBitmapImageRep:bitmap]; \t NSImage * result = [[NSImage alloc] initWithSize:self.bounds.size]; \t [result addRepresentation:bitmap]; \t返回結果; } ' – codrut 2017-10-16 13:36:27