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))
}
,但它沒有做任何事情
嘗試在調用'drawRect()'後添加子視圖而不是 –
爲什麼不用UIView而不是NSView子類? –
因爲它是可可(MacOS)而非UIKit(iOS)應用程序。 –