2017-04-01 116 views
1

我正在嘗試創建三種形狀:圓形,方形&三角形。我創建了圓形&方形,但無法創建三角形。我最大的問題是保持屏幕中心的所有三個形狀。圓形和方形很好,但是當我嘗試製作三角形時,它不起作用。我也試圖讓三角形看起來像一個「播放按鈕」,以便三角形的「尖端」朝向右側。這是代碼。UIBezierPath創建三角形,方形,圓形Swift

func trainglePathWithCenter(center: CGPoint, side: CGFloat) -> UIBezierPath { 
    let path = UIBezierPath() 

    let startX = center.x - side/2 
    let startY = center.y - side/2 

    path.move(to: CGPoint(x: startX, y: startY)) 
    path.addLine(to: CGPoint(x: startX, y: startY - side)) 
    path.addLine(to: CGPoint(x: startX + side, y: startY + side/2)) 
    path.close() 

    return path 
} 


func circlePathWithCenter(center: CGPoint, radius: CGFloat) -> UIBezierPath { 
    let circlePath = UIBezierPath() 
    circlePath.addArc(withCenter: center, radius: radius, startAngle: -CGFloat(M_PI), endAngle: -CGFloat(M_PI/2), clockwise: true) 
    circlePath.addArc(withCenter: center, radius: radius, startAngle: -CGFloat(M_PI/2), endAngle: 0, clockwise: true) 
    circlePath.addArc(withCenter: center, radius: radius, startAngle: 0, endAngle: CGFloat(M_PI/2), clockwise: true) 
    circlePath.addArc(withCenter: center, radius: radius, startAngle: CGFloat(M_PI/2), endAngle: CGFloat(M_PI), clockwise: true) 
    circlePath.close() 
    return circlePath 
} 

func squarePathWithCenter(center: CGPoint, side: CGFloat) -> UIBezierPath { 
    let squarePath = UIBezierPath() 
    let startX = center.x - side/2 
    let startY = center.y - side/2 

    squarePath.move(to: CGPoint(x: startX, y: startY)) 

    squarePath.addLine(to: squarePath.currentPoint) 
    squarePath.addLine(to: CGPoint(x: startX + side, y: startY)) 
    squarePath.addLine(to: squarePath.currentPoint) 
    squarePath.addLine(to: CGPoint(x: startX + side, y: startY + side)) 
    squarePath.addLine(to: squarePath.currentPoint) 
    squarePath.addLine(to: CGPoint(x: startX, y: startY + side)) 
    squarePath.addLine(to: squarePath.currentPoint) 
    squarePath.close() 
    return squarePath 

} 

我在哪裏錯了三角形的幾何?

回答

3

當您需要添加時,會減去此值。請記住,+Y已關閉。

變化:

path.addLine(to: CGPoint(x: startX, y: startY - side)) 

要:

path.addLine(to: CGPoint(x: startX, y: startY + side)) 

這是在遊樂場運行:

Triangle demo running in a Playground


以下是Playground演示的完整代碼:

class Custom: UIView { 
    override func draw(_ rect: CGRect) { 
     let path = trainglePathWithCenter(center: self.center, side: self.bounds.width/2) 

     path.stroke() 
    } 

    func trainglePathWithCenter(center: CGPoint, side: CGFloat) -> UIBezierPath { 
     let path = UIBezierPath() 

     let startX = center.x - side/2 
     let startY = center.y - side/2 

     path.move(to: CGPoint(x: startX, y: startY)) 
     path.addLine(to: CGPoint(x: startX, y: startY + side)) 
     path.addLine(to: CGPoint(x: startX + side, y: startY + side/2)) 
     path.close() 

     return path 
    } 
} 

let custom = Custom(frame: CGRect(x: 0, y: 0, width: 200, height: 200)) 
custom.backgroundColor = .white