我希望制作一个应用程序,用户可以在屏幕上绘图并保存他们的作品。以下是我的UIView
绘制代码:
import UIKit
class DrawView: UIView {
var lines: [Line] = [] // Line is a custom class, shown below
var lastPoint: CGPoint!
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
lastPoint = touches.anyObject()?.locationInView(self)
}
override func touchesMoved(touches: NSSet, withEvent event: UIEvent) {
var newPoint = touches.anyObject()?.locationInView(self)
lines.append(Line(start: lastPoint, end: newPoint!))
lastPoint = newPoint
self.setNeedsDisplay()
}
override func drawRect(rect: CGRect) {
var context = UIGraphicsGetCurrentContext()
CGContextBeginPath(context)
CGContextSetLineCap(context, kCGLineCapRound)
for line in lines {
CGContextMoveToPoint(context, line.start.x, line.start.y)
CGContextAddLineToPoint(context, line.end.x, line.end.y)
}
CGContextSetRGBStrokeColor(context, 0, 0, 0, 1)
CGContextSetLineWidth(context, 5)
CGContextStrokePath(context)
}
}
Line类的代码:
import UIKit
class Line {
var start: CGPoint
var end: CGPoint
init(start _start: CGPoint, end _end: CGPoint ) {
start = _start
end = _end
}
}
现在我想使用NSUserDefaults
保存这个绘图。我该怎么做?