OS X 上使用核心动画(Core Animation)
自从swift推出以来,我断然放弃了object_c,转向swift,我多年使用C++,所以swift对我来说要容易一些。基本的swift的内容这里就不说了。
最近我开始研究核心动画(Core Animation),在这里做个记录。
建立一个基本的Cocoa 应用,修改代码为:
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
@IBOutlet weak var window: NSWindow!
@IBOutlet weak var theView: NSView!
let circleLayer = CAShapeLayer()
func applicationDidFinishLaunching(aNotification: NSNotification) {
// Insert code here to initialize your application
theView.wantsLayer = true
let rect = theView.frame
circleLayer.fillColor = CGColorGetConstantColor(kCGColorBlack)
circleLayer.path = CGPathCreateWithEllipseInRect( rect, nil)
self.theView.layer?.addSublayer(circleLayer)
}
func applicationWillTerminate(aNotification: NSNotification) {
// Insert code here to tear down your application
}
}
也就是添加蓝色代码,编译,如果没有错误的话,你可以可以看到
这个界面巨丑,所以就不贴全图了。它第一次出现我还是小激动了一下。
上面虽然只有短短的几行代码,却花费了我不少时间和心思。网络上关于OS X 的例子相当难找。
theView.wantsLayer = true
上面这句是OS X 和 IOS区别的关键点。因为IOS 底层根本就是使用图层和 Core Animation绘制视图的,而缺省情况下 OS X并没有。如果你打算在OS X使用,就需要打开这个开关,通知 NSView为你准备好图层,你可以查看视图的属性,layer属性缺省为nil。
这里的第二个问题就是CGPath。网上有句话这样写:将bezierPath的CGPath赋值给caShapeLayer的path,即caShapeLayer.path = bezierPath.CGPath
在OS X 的 NSBezierPath里面并没有这个CGPath属性。当然,总有办法把 NSBezierPath变成 CGPath,我们为什么不直接使用CGPath呢?然后是CGColor。从普通的道理上讲,使用CGPath和CGColor是最正宗的方式,不然苹果就没有必要提供这些类。
接下来及时NSView,跟层相关的东西还有不少。前面只是大致看了看,接下来我会继续研究。