bri*_*one 5 core-graphics save uiview ios swift
我想创建一个用户可以在屏幕上绘制然后保存其图形的应用程序。以下是我的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)
}
}
Run Code Online (Sandbox Code Playgroud)
Line类的代码:
import UIKit
class Line {
var start: CGPoint
var end: CGPoint
init(start _start: CGPoint, end _end: CGPoint ) {
start = _start
end = _end
}
}
Run Code Online (Sandbox Code Playgroud)
现在,我希望能够使用保存该图形NSUserDefaults。我该怎么做?
要捕获视图,可以使用UIGraphicsImageRenderer和drawHierarchy:
let image = UIGraphicsImageRenderer(bounds: view.bounds).image { _ in
view.drawHierarchy(in: view.bounds, afterScreenUpdates: true)
}
Run Code Online (Sandbox Code Playgroud)
要将其保存在中UserDefaults,您可以:
if let data = image.pngData() {
UserDefaults.standard.set(data, forKey: "snapshot")
}
Run Code Online (Sandbox Code Playgroud)
要从中检索它UserDefaults,您可以:
if let data = UserDefaults.standard.data(forKey: "snapshot"), let image = UIImage(data: data) {
...
}
Run Code Online (Sandbox Code Playgroud)
就个人而言,我不会倾向于将图像存储在中UserDefaults。我会将其保存到持久性存储中。例如,要将其保存到“应用程序支持”文件夹中,您可以:
do {
let fileURL = try FileManager.default
.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
.appendingPathComponent("test.png")
try data.write(to: fileURL, options: .atomicWrite)
} catch {
print(error)
}
Run Code Online (Sandbox Code Playgroud)