如何将多个贝塞尔曲线路径添加到同一视图swift 3

时间:2017-06-02 11:20:59

标签: ios swift3 uibezierpath

我以这种方式添加了一个三角形

// draw the line graph

    UIColor.white.setFill()
    UIColor.white.setStroke()

    ///--------SETUP FIRST TRIANGLE-----------------------------------------------
    //set up the points line
    let graphPath = UIBezierPath()
    //go to start of line
    graphPath.move(to: CGPoint.init(x: rect.minX, y: rect.minY))
    graphPath.addLine(to: CGPoint.init(x: (rect.maxX/2.0), y: (rect.maxY/2.0)))
    graphPath.addLine(to: CGPoint.init(x: rect.minX, y: rect.maxY))
    graphPath.stroke()
    //2 - make a copy of the path
    let clippingPath = graphPath.copy() as! UIBezierPath

    //3 - add lines to the copied path to complete the clip area
    clippingPath.addLine(to: CGPoint.init(x: rect.minX, y: rect.minY))
    clippingPath.close()

    //4 - add the clipping path to the context
    clippingPath.addClip()

    let startPoint = CGPoint(x:(rect.maxX/2.0), y: (rect.maxY/2.0))
    let endPoint = CGPoint(x:rect.minX, y:(rect.maxY/2.0))
    let gradient=self.getGradient(tiangleNo: 1)
    let context = UIGraphicsGetCurrentContext()
    context!.drawLinearGradient(gradient, start: startPoint, end: endPoint, options: CGGradientDrawingOptions(rawValue: 0))

这是我想要的三角形。现在我想绘制另一个三角形。所以我确实喜欢这个。

///------------SECOND TRIANGLE -----------------------------------------------


    let graphPath2 = UIBezierPath()

    graphPath2.move(to: CGPoint.init(x: rect.minX, y: rect.minY))
    graphPath2.addLine(to: CGPoint.init(x: rect.maxX, y: rect.minY))
    graphPath2.addLine(to: CGPoint.init(x: (rect.maxX/2.0), y: (rect.minY/2.0)))
    graphPath2.stroke()

    let oldPath1=clippingPath.copy() as! UIBezierPath
    oldPath1.append(graphPath2)

    let startPoint2 = CGPoint(x:(rect.maxX/2.0), y: (rect.maxY/2.0))
    let endPoint2 = CGPoint(x:(rect.maxX/2.0), y:rect.minY)
    let gradient2=self.getGradient(tiangleNo: 2)
    let context2 = UIGraphicsGetCurrentContext()
    context2!.drawLinearGradient(gradient2, start: startPoint2, end: endPoint2, options: CGGradientDrawingOptions(rawValue: 0))

但这只是在前一个内部添加了一个三角形。rect是我的UIScreen矩形

1 个答案:

答案 0 :(得分:4)

简单解决方案

你可以写一个像这样的函数

func drawTriangle(point1:CGPoint, point2:CGPoint, point3:CGPoint) {

    let path = UIBezierPath()
    path.move(to: point1)
    path.addLine(to: point2)
    path.addLine(to: point3)
    path.close()

    path.lineWidth = 2.0
    UIColor.red.setFill()
    path.fill()

}

通过调用函数

绘制triagles
//Triagle 1

let pointA = CGPoint(x: 0, y: 0)
let pointB = CGPoint(x: 100, y: 0)
let pointC = CGPoint(x: 0, y: 100)

drawTriangle(point1: pointA, point2: pointB, point3: pointC)

//Triagle 2

let pointD = CGPoint(x: 120, y: 0)
let pointE = CGPoint(x: 220, y: 0)
let pointF = CGPoint(x: 220, y: 100)

drawTriangle(point1: pointD, point2: pointE, point3: pointF)

你会得到这样的东西,

enter image description here