2016-06-28 33 views
1

我一直試圖在使用swift的cocoa應用程序中繪製一個簡單的線條,但是我未能完全理解如何使用CGContext類。在cocoa swift中繪製

我創建這個類:在主窗口

import Cocoa 
class Drawing: NSView { 
override func drawRect(dirtyRect: NSRect) { 
    super.drawRect(dirtyRect) 

    let context = NSGraphicsContext.currentContext()?.CGContext; 

    CGContextBeginPath(context) 
    CGContextMoveToPoint(context, 0, 0) 
    CGContextAddLineToPoint(context, 100, 100) 
    CGContextSetRGBStrokeColor(context, 1, 1, 1, 1) 
    CGContextSetLineWidth(context, 5.0) 
    CGContextStrokePath(context) 

    } 
} 

,並用它像這樣

override func viewDidLoad() { 
    super.viewDidLoad() 
    let dr = Drawing() 
    self.view.addSubview(dr) 
    dr.drawRect(NSRect(x: 0, y: 0, width: 100, height: 100)) 
} 

,但它沒有做任何事情

+0

嘗試在調用'drawRect()'後添加子視圖而不是 –

+0

爲什麼不用UIView而不是NSView子類? –

+3

因爲它是可可(MacOS)而非UIKit(iOS)應用程序。 –

回答

2

您需要初始化你的Drawing視圖與框架,否則系統將不知道在哪裏畫它,如下所示:

override func viewDidLoad() { 
    super.viewDidLoad() 
    let dr = Drawing(frame: NSRect(x: 0, y: 0, width: 100, height: 100)) 
    self.view.addSubview(dr) 
} 

同樣如David所說,您不需要自己撥打drawRect,因爲系統會自動調用它。

+1

更重要的是,你*不應該自己調用'drawRect()'。系統在調用該方法之前爲您的視圖設置圖形上下文。當你自己調用它時,你並沒有進行相同的設置,所以圖形上下文將不正確,甚至根本不存在。 – Caleb