如何在Swift中保存CoreGraphics绘图

时间:2015-02-13 15:49:55

标签: ios swift uiview save core-graphics

我想创建一个应用程序,用户可以在屏幕上绘图,然后保存他们的图纸。以下是我的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 class代码:

import UIKit

class Line {

    var start: CGPoint
    var end: CGPoint

    init(start _start: CGPoint, end _end: CGPoint ) {
        start = _start
        end = _end

    }
}

现在我希望能够使用NSUserDefaults保存此图形。我该怎么做?

2 个答案:

答案 0 :(得分:4)

要捕获视图,您可以使用UIGraphicsBeginImageContextWithOptionsdrawViewHierarchyInRect

UIGraphicsBeginImageContextWithOptions(view.bounds.size, false, 0.0)
view.drawViewHierarchyInRect(view.bounds, afterScreenUpdates: true)
let image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

要将其保存在NSUserDefaults中,您可以:

let data = UIImagePNGRepresentation(image)
let userDefaults = NSUserDefaults.standardUserDefaults()
userDefaults.setObject(data, forKey: "snapshot")
userDefaults.synchronize()

要从NSUserDefaults检索它,您可以:

if let data = NSUserDefaults.standardUserDefaults().dataForKey("snapshot"), let image = UIImage(data: data) {
    // do something with image
}

就个人而言,我不倾向于将图像存储在NSUserDefaults中。我将它保存到持久存储中。例如,要将其保存到Documents文件夹中,您可以:

do {
    let documentsURL = try NSFileManager.defaultManager().URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: false)
    let fileURL = documentsURL.URLByAppendingPathComponent("test.png")

    try data.writeToURL(fileURL, options: .AtomicWrite)
} catch {
    print(error)
}

答案 1 :(得分:2)

    //I would recomend you to save line on touches end
     override func touchesEnded(touches: NSSet, withEvent event: UIEvent) {

        save()
    }

    func save() {

        var data : NSMutableData=NSMutableData()

        var archiver=NSKeyedArchiver(forWritingWithMutableData: data)
        archiver.encodeObject(lines, forKey:"classLine")
        archiver.finishEncoding()

        NSUserDefaults.standardUserDefaults().setObject(data, forKey: "shape")
    }


    class func loadSaved() {
        if let data = NSUserDefaults.standardUserDefaults().objectForKey("shape") as? NSData {

            var unarchiver :NSKeyedUnarchiver = NSKeyedUnarchiver(forReadingWithData: data);

            var line : Line = unarchiver.decodeObjectForKey("classLine") as Line!

        }

    }



}


class Line : NSObject {

    var start: CGPoint
    var end: CGPoint

    init(start _start: CGPoint, end _end: CGPoint ) {
        start = _start
        end = _end

    }

    func encodeWithCoder(aCoder: NSCoder) {

            aCoder.encodeCGPoint(start, forKey: "start")
            aCoder.encodeCGPoint(end, forKey: "end")

    }

    required init(coder aDecoder: NSCoder) {

        start  = aDecoder.decodeCGPointForKey("start")
        end  = aDecoder.decodeCGPointForKey("end")


 }
}