原文使用ObjC编码,我翻译为了Swift. 先看运行效果图
实现一个绘图板功能的view,可以使用CoreGraphics调用draw完成,缺点是在绘制的后面的时候每次都重绘制全部内容,非常没有必要. 另一个建议,使用CAShapeLayer纪录绘制的路径,而且CAShapeLayer是专门为绘制路径所优化的layer,当然更有效率. 同时最重要的一点,声明当前UIView实现的layerClass为CAShapeLayer.
使用专有图层可以完成相应的更近恰当的任务,这样会比直接使用CoreGraphics绘制更加的高效.
// // DrawingView.swift // layerDemo // // Created by grath on 15/9/17. // Copyright © 2015年 stone. All rights reserved. // import UIKit class DrawingView: UIView { var path = UIBezierPath() // init() { super.init(frame: CGRectZero) let shapeLayer = self.layer as! CAShapeLayer shapeLayer.lineWidth = 2.0 shapeLayer.lineCap = kCALineCapRound shapeLayer.strokeColor = UIColor.redColor().CGColor shapeLayer.fillColor = UIColor.clearColor().CGColor shapeLayer.masksToBounds = true //裁减掉超出当前view的layer绘制 shapeLayer.shadowOffset = CGSizeMake(2.0,4.0) shapeLayer.shadowRadius = 2.0 shapeLayer.shadowColor = UIColor.purpleColor().CGColor } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override class func layerClass() -> AnyClass { //指定返回的layer类型 默认返回CALayer类型 return CAShapeLayer.classForCoder() } override func touchesBegan(touches: Set<UITouch>,withEvent event: UIEvent?) { let p = touches.first?.locationInView(self) path.moveToPoint(p!) } override func touchesMoved(touches: Set<UITouch>,withEvent event: UIEvent?) { let p = touches.first?.locationInView(self) path.addLineToPoint(p!) //增加绘制点 let shapeLayer = self.layer as! CAShapeLayer //指定path 开始绘制 shapeLayer.path = self.path.CGPath } }
以上为实现代码.
使用方法如下:
func addDrawView() { let drawVw = DrawingView() drawVw.layer.borderWidth = 4.0 drawVw.layer.borderColor = UIColor.grayColor().CGColor drawVw.frame = CGRectInset(self.view.bounds,50,100) var atrans = CATransform3DIdentity atrans.m34 = -1/500.0 atrans = CATransform3DRotate(atrans,CGFloat(M_PI_4),1,0) //drawVw.layer.transform = atrans view.addSubview(drawVw) }