前言
UIBezierPath是UIKit中的一个关于图形绘制的类,是通过Quartz 2D也就是CG(Core Graphics)CGPathRef的封装得到的,从高级特性支持来看不及CG。
UIBezierPath类可以绘制矩形、圆形、直线、曲线以及它们的组合图形。
关于UIBezierPath的相关api这里不再一一列举,下面直入主题:


一.画板界面

在storyBoard中拖入四个按钮,作为功能按钮,中间一个白色的区块,为画板,下面一个sliderView,用来调节线条宽度,下面部分采用按钮的,利用autoLayout布局.
二.核心代码
1.画板LYXDrawingBoardView
设置属性线条颜色,宽度,和线条数组.
var lineColor :UIColor?
var lineWidth :CGFloat?
lazy var lins:[LYXBezierPath] = {
return []
}()
重写drawRect方法,在里面进行线条绘制
override func draw(_ rect: CGRect) {
if self.lins.count > 0 {
for line in self.lins {
line.lineCapStyle = CGLineCap.round
line.lineJoinStyle = .round
line.bezierPathColor?.setStroke()
line.stroke()
}
}
}
重写touchesBegan和touchesMoved方法创建线条(UIBezierPath对象,并对线的起点,终点,线宽,颜色进行设置).
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let line:LYXBezierPath = LYXBezierPath()
line.lineWidth = self.lineWidth!
line.bezierPathColor = self.lineColor!
self.lins.append(line)
let touch:UITouch = touches.first!
line.startPoint = touch.location(in: self)
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
let line = self.lins.last!
line.startPoint = touches.first?.previousLocation(in: self)
line.lastPoint = touches.first?.location(in: self)
line.move(to: line.startPoint!)
line.addLine(to: line.lastPoint!)
line.stroke()
self.setNeedsDisplay()
}
由于UIBezierPath没有起点和终点以及线的颜色属性,这里创建了一个UIBeziePath的子类
class LYXBezierPath:UIBezierPath {
var bezierPathColor:UIColor?
var startPoint:CGPoint?
var lastPoint:CGPoint?
}
2.功能模块
(1).切换线条颜色
@IBAction func changeColorAction(_ sender: UIButton) {
self.drawingBoardView.lineColor = sender.backgroundColor
}
(2).改变线条宽度(默认最小宽度为3)
@IBAction func changeLineWidth(_ sender: UISlider) {
self.drawingBoardView.lineWidth = 3.0 + CGFloat(sender.value * Float(10))
}
(3).重画,清除画板的线条数组即可
@IBAction func drawingAgain(_ sender: UIButton) {
self.drawingBoardView.lins.removeAll()
self.drawingBoardView.setNeedsDisplay()
}
(4).回退,每次回退,去除最后一根线
@IBAction func drawingBack() {
if self.drawingBoardView.lins.count > 0 {
self.drawingBoardView.lins.remove(at: self.drawingBoardView.lins.count - 1)
self.drawingBoardView.setNeedsDisplay()
}
}
(5).橡皮,把线条颜色改成个画板同色并加宽线条宽度
@IBAction func eraser(_ sender: UIButton) {
self.drawingBoardView.lineColor = UIColor.white
self.drawingBoardView.lineWidth = 20
}
(6)保存到相册
@IBAction func saveToAlbum(_ sender: UIButton) {
//要在info.plsit中配置访问相册权限
UIGraphicsBeginImageContextWithOptions(self.drawingBoardView.bounds.size, false, 0.0)
self.drawingBoardView.layer.render(in: UIGraphicsGetCurrentContext()!)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
UIImageWriteToSavedPhotosAlbum(image!, self, nil, nil)
}
一个简单好玩的小画板就做好了
网友评论