CATiledLayer的使用

作者: LJ的ios开发 | 来源:发表于2018-07-24 10:37 被阅读124次
    效果图.png

    使用CATiledLayer解决加载大图的问题。如:地图

    class ViewController: UIViewController, CALayerDelegate, UIScrollViewDelegate {
        
        var contentView:UIView?
        
        @IBOutlet weak var scrollView: UIScrollView!
        
        override func viewDidLoad() {
            super.viewDidLoad()
            let rect = CGRect(x: 0, y: 0, width: 1280, height: 960)
            
            let contentView = UIView(frame: rect)
            //瓦片
            let tiledLayer = CATiledLayer()
            tiledLayer.frame = rect
            tiledLayer.delegate = self
            contentView.layer.addSublayer(tiledLayer)
            scrollView.addSubview(contentView)
            scrollView.contentSize = contentView.frame.size
            //draw layer
            tiledLayer.setNeedsDisplay()
            self.contentView = contentView
        }
        
        func draw(_ layer: CALayer, in ctx: CGContext) {
            let layer = layer as! CATiledLayer
            
            //配置瓦片位置
            let bounds = ctx.boundingBoxOfClipPath
            let x = bounds.origin.x / layer.tileSize.width
            let y = bounds.origin.y / layer.tileSize.height
            
            //加载瓦片图片
            let imageName = "LiuYan_0\(Int(x))_0\(Int(y))"//大图切成的小图
            let tileImage = UIImage(named: imageName)
            
            //draw tile
            UIGraphicsPushContext(ctx)
            tileImage?.draw(in: bounds)
            UIGraphicsPopContext()
        }
        
        func viewForZooming(in scrollView: UIScrollView) -> UIView? {
            return self.contentView
        }
    }
    
    

    Github地址: https://github.com/LJjack/LearnCATiledLayer

    相关文章

      网友评论

      本文标题:CATiledLayer的使用

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