1.简介
CATiledLayer是一个会异步绘制内容的图层,对于处理非常大的图像时,很有用,可以看到一部分,而无序加载全部。
2.属性
属性 | 作用 |
---|---|
levelsOfDetail | 细节数,默认为1 |
levelsOfDetailBias | 放大级数,默认为0 |
tileSize | 内部小模块的大小 |
方法 | 作用 |
---|---|
class fadeDuration() | 出现的时间,默认0.25 |
3.使用
//首先,自定义一个TiledLayer
import UIKit
class CustomTiledLayer: CATiledLayer {
//重写出现的时间
override class func fadeDuration() -> CFTimeInterval {
return 0
}
}
class TiledBackgroundView: UIView {
let sideLength = CGFloat(50)
//返回CATiledLayer
override class var layerClass: AnyClass {
return CustomTiledLayer.self
}
override init(frame: CGRect) {
super.init(frame: frame)
//srand48:生成种子的初始值
srand48(Int(NSDate().timeIntervalSince1970))
//创建出CATiledLayer
let layer = self.layer as! CustomTiledLayer
//系统分辨率
let scale = UIScreen.main.scale
//瓦块的大小,按照分辨率缩放
layer.tileSize = CGSize(width: sideLength*scale, height: sideLength*scale)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func draw(_ rect: CGRect) {
let context = UIGraphicsGetCurrentContext()
//drand48:产生一个[0.0, 1.0]区间中的浮点数。
let red = CGFloat(drand48())
let green = CGFloat(drand48())
let blue = CGFloat(drand48())
context?.setFillColor(red: red, green: green, blue: blue, alpha: 1)
context?.fill(rect)
}
}
//使用
import UIKit
class ViewController: UIViewController {
var tiedBackgroundView: TiledBackgroundView!
override func viewDidLoad() {
super.viewDidLoad()
setUpLayer()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func setUpLayer() {
tiedBackgroundView = TiledBackgroundView(frame: view.frame)
view.addSubview(tiedBackgroundView)
}
}
最终结果如图: