美文网首页
Core Animation Archive

Core Animation Archive

作者: 微微笑的蜗牛 | 来源:发表于2018-11-26 14:05 被阅读45次

    今天读到一篇文章,发现一个新的知识点,Core Animation Archive

    Core Animation Archive是指将CALayer树归档到文件,在其他地方要使用这中类型的CALayer时,从文件中读取即可。storyboard和xib也是类似的方式,相当于其是个数据文件,在使用的时候,进行恢复,生成对应的ui实例。

    它也是使用NSKeyedArchiver/NSUnKeyedArchiver进行归解档,归档后的后缀名是.caar

    其使用起来也比较简单。

    archive

    func archiveLayer() {
        let layer = CAShapeLayer()
        
        let rect = CGRect(x: 0, y: 0, width: 200, height: 200)
        
        layer.path = CGPath(roundedRect: rect, cornerWidth: 5, cornerHeight: 5, transform: nil)
        layer.frame = rect
        
        layer.fillColor = UIColor.red.cgColor
        layer.strokeColor = UIColor.white.cgColor
        layer.lineWidth = 2
        
        let caar = ["rootLayer": layer]
        
        do {
            let data = try NSKeyedArchiver.archivedData(withRootObject: caar, requiringSecureCoding: false)
            
            let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
            let url = URL(fileURLWithPath: "\(path)/redSquare.caar")
            
            try data.write(to: url)
        } catch {
            print(error)
        }
    }
    

    序列化后会生成redSquare.caar,预览如下:

    image.png

    unarchive

    func unarchiveLayer() {
            
        let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let url = URL(fileURLWithPath: "\(path)/redSquare.caar")
        let data = try? Data(contentsOf: url)
    
        if let data = data {
            let caar = try! NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data) as! [String: Any]
            
            let rootLayer = caar["rootLayer"] as! CALayer
            
            print(rootLayer)
        }
    }
    

    这样就拿到了rootLayer了。

    相关文章

      网友评论

          本文标题:Core Animation Archive

          本文链接:https://www.haomeiwen.com/subject/sgkbqqtx.html