在我们某些软件开发中, 或许需要更改View里面的部分颜色, 或者画一个简单的图片, 刚好你身边又没有UI设计师, 那么我们就可以使用UIGraphicsGetCurrentContext来绘制我们的图像, 下面我只拿一个简单的Demo来演示.
1.界面布局
PS: 这里面的ViewController的View都是继承与自定义的UIView.
2.代码实现
这里面有5个样式, 我只拿最后一个样式来做讲解, 剩下的都比较简单, 也有注释.
class BoardView: UIView {
// 1.创建一个可变的图形路径
let path = CGPathCreateMutable()
override init(frame: CGRect) {
super.init(frame: frame)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
// 2.手势点击的时候
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
// 2.1.获取得到当前点击点
let p = (touches as NSSet).anyObject()?.locationInView(self)
// 2.2.存储获取得到的点
CGPathMoveToPoint(path, nil, p!.x, p!.y)
}
// 3.手势移动的时候
override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {
// 3.1.获取得到最后点击的点
let p = (touches as NSSet).anyObject()?.locationInView(self)
// 3.2.把前面获取得到的起始点和最后移动的点连起来成为一根线
CGPathAddLineToPoint(path, nil, p!.x, p!.y)
// 3.3.重绘整个View, 只有执行了该方法, 下面的drawRect才会被执行
setNeedsDisplay()
}
// 4.重绘整个View
override func drawRect(rect: CGRect) {
// 4.1.获取当前的内容
let context = UIGraphicsGetCurrentContext()
// 4.2.给当前内容添加路径
CGContextAddPath(context, path)
// 4.3.显示出添加的内容
CGContextStrokePath(context)
}
}
3.最终效果
项目地址: http://pan.baidu.com/s/1pJRIEvx 密码: pwkw