用UIBezierPath画一条线

第一次使用BezierPaths,想知道这个函数实际上应该如何实现。 目前贝塞尔path在图像的框架内移动,而不是在屏幕上绘图。

有没有更好的方法来做到这一点?

func drawLineFromPoint(start : CGPoint, toPoint end:CGPoint, ofColor lineColor: UIColor, inView view:UIView) { var maxWidth = abs(start.x - end.x) var maxHeight = abs(start.y - end.y) var contextSize : CGSize! if maxWidth == 0 { contextSize = CGSize(width: 1, height: maxHeight) }else { contextSize = CGSize(width: maxWidth, height: 1) } //design the path UIGraphicsBeginImageContextWithOptions(contextSize, false, 0) var path = UIBezierPath() path.lineWidth = 1.0 lineColor.set() //draw the path and make visible path.moveToPoint(start) path.addLineToPoint(end) path.stroke() //create image from path and add to subview var image = UIGraphicsGetImageFromCurrentImageContext() var imageView = UIImageView(image: image) view.addSubview(imageView) UIGraphicsEndImageContext() } 

结束这样做:

 func drawLineFromPoint(start : CGPoint, toPoint end:CGPoint, ofColor lineColor: UIColor, inView view:UIView) { //design the path var path = UIBezierPath() path.moveToPoint(start) path.addLineToPoint(end) //design path in layer var shapeLayer = CAShapeLayer() shapeLayer.path = path.CGPath shapeLayer.strokeColor = lineColor.CGColor shapeLayer.lineWidth = 1.0 view.layer.addSublayer(shapeLayer) } 

Swift 3.1版本的威廉猎鹰的答案+改进

这只是已经接受的答案的更新版本,我只是多加了一点点。

 func drawLineFromPointToPoint(startX: Int, toEndingX endX: Int, startingY startY: Int, toEndingY endY: Int, ofColor lineColor: UIColor, widthOfLine lineWidth: CGFloat, inView view: UIView) { let path = UIBezierPath() path.move(to: CGPoint(x: startX, y: startY)) path.addLine(to: CGPoint(x: endX, y: endY)) let shapeLayer = CAShapeLayer() shapeLayer.path = path.cgPath shapeLayer.strokeColor = lineColor.cgColor shapeLayer.lineWidth = lineWidth view.layer.addSublayer(shapeLayer) } 

当然,实施将是

 drawLineFromPointToPoint(startX: Int, toEndingX: Int, startingY: Int, toEndingY: Int, ofColor: UIColor, widthOfLine: CGFloat, inView: UIView) 

我接受的答案改变了

我改变了variables,让它更容易inputx和y的开始和结束。 我也允许用户改变线的宽度。

我select的值是Inttypes,但是您可以将其更改为其他允许的选项。

在上面画水平线:

 let path = UIBezierPath() path.moveToPoint(CGPoint(x: 0, y: 0)) path.addLineToPoint(CGPoint(x: yourView.frame.width, y: 0)) let shapeLayer = CAShapeLayer() shapeLayer.path = path.CGPath shapeLayer.strokeColor = UIColor.lightGrayColor().CGColor shapeLayer.lineWidth = 0.5 yourView.layer.addSublayer(shapeLayer) 

在底部画水平线:

 let path = UIBezierPath() path.moveToPoint(CGPoint(x: 0, y: yourView.frame.height)) path.addLineToPoint(CGPoint(x: yourView.frame.width, y: yourView.frame.height)) let shapeLayer = CAShapeLayer() shapeLayer.path = path.CGPath shapeLayer.strokeColor = UIColor.lightGrayColor().CGColor shapeLayer.lineWidth = 0.5 yourView.layer.addSublayer(shapeLayer)