1.思路:捕捉绘图操作。iOS的绘图操作是在UIView类的drawRect方法中完成的,所以如果我们要想在一个UIView中绘图,需要写一个扩展UIView 的类,并重写drawRect方法,在这里进行绘图操作,程序会自动调用此方法进行绘图。
2.具体实现:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch = touches.first
let startPoint = touch?.location(in: touch?.view)
var pathPoints : [NSValue] = []
if let startPoint = startPoint{
pathPoints.append(NSValue(cgPoint: startPoint))
totalPathPoints.append(pathPoints)
setNeedsDisplay()
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch = touches.first
if let movePoint = touch?.location(in: touch?.view){
totalPathPoints[totalPathPoints.count - 1].append(NSValue(cgPoint: movePoint))
setNeedsDisplay()
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
self.touchesMoved(touches, with: event)
}
//中心 重写drawrect方法
override func draw(_ rect: CGRect) {
let context = UIGraphicsGetCurrentContext()
for(_, pathPoints) in totalPathPoints.enumerated(){
for(i, pos) in pathPoints.enumerated(){
let point = pos.cgPointValue
if i == 0 {
context?.move(to: point)
}else{
context?.addLine(to: point)
}
}
}
context?.setStrokeColor(lineColor.cgColor)
context?.setLineCap(CGLineCap.round)
context?.setLineJoin(CGLineJoin.round)
context?.setLineWidth(lineWidth)
context?.strokePath()
}
//获取绘图UIImage
func getImage() -> UIImage? {
//截屏操作
UIGraphicsBeginImageContextWithOptions(self.frame.size, true, self.layer.contentsScale)
self.layer.render(in: UIGraphicsGetCurrentContext()!)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
//清除绘图
func clear() {
totalPathPoints.removeAll()
setNeedsDisplay()
}
3.知识点补充:
重绘操作仍然在drawRect方法中完成,但是苹果不建议直接调用drawRect方法,当然如果你强直直接调用此方法,当然是没有效果的。苹果要求我们调用UIView类中的setNeedsDisplay方法,则程序会自动调用drawRect方法进行重绘。(调用setNeedsDisplay会自动调用drawRect)当某些情况下想要手动重画一个View,只需要掉用[self setNeedsDisplay]或[self setNeedsDisplayInRect]方法即可.
另外:若要实时画图,不能使用gestureRecognizer,只能使用touchbegan等方法来掉用setNeedsDisplay实时刷新屏幕(即本实例采取的方法)
以下内容转自:http://www.cnblogs.com/madpanda/p/4728935.html
iOS绘图
在iOS中常用有三套绘图API。一个是UIKit提供的高层API,一个是CoreGraphics提供的C语言层的API,最后一个是OpenGL ES提供的API。
iOS的绘图逻辑代码需要放在UIView的drawRect:方法里面实现,所以绘图只能发生在UIView上面。
绘图后如果我们想要显示图像可以调用
setNeedsDisplay和setNeedsDisplayInRect:。这两个方法是用来标示一个视图是否需要进行重绘,这里标示重绘并不会马上重新绘制,而是等到该RunLoop上面的任务执行完成后才回执行重绘。
触发重绘有以下几种情况:
1.当遮挡你的视图得其它视图被移动或者删除操作得时候;
2.将视图的hidden属性声明设置为No,使其从隐藏状态变为可见;
3.将视图滚出屏幕,然后重新回到屏幕;
4.显示调用视图的setNeedsDisplay或者setNeedsDisplayInRect:方法;