2014-07-30 23 views
5

Tôi đang cố gắng vẽ một vòng tròn trong Swift, nhưng khi tôi viết mã của mình, tôi gặp lỗi "không thể tìm thấy quá tải cho 'init' chấp nhận các đối số đã cung cấp.Làm thế nào để khởi tạo UIBezierPath để vẽ một vòng tròn nhanh chóng?

Trong lớp UIBezierPath có một init function:

init(arcCenter center: CGPoint, radius: CGFloat, startAngle: CGFloat, endAngle: CGFloat, clockwise: Bool) -> UIBezierPath 

Nhưng khi tôi tuyên bố điều này với mã này tôi nhận được lỗi .. Tôi có cần phải biến biến nào khác không? nhưng nếu tôi biên dịch số này trong iphone 4, tôi không gặp lỗi, chỉ trong iphone 5/5s. Làm cách nào để khai báo chính xác?

let arcCenter = CGPoint(x: CGRectGetMidX(self.bounds), y: CGRectGetMidY(self.bounds)) 
    let radius  = Float(min(CGRectGetMidX(self.bounds) - 1, CGRectGetMidY(self.bounds)-1)) 

    let circlePath : UIBezierPath = UIBezierPath(arcCenter: arcCenter, radius: radius, startAngle: -rad(90), endAngle: rad(360-90), clockwise: true) 

Cảm ơn!

+1

thử điều này: chúng ta hãy circlePath: UIBezierPath = UIBezierPath (arcCenter: arcCenter, bán kính: CGFloat (bán kính), startAngle: CGFloat (-rad (90)), endAngle: CGFloat (rad (360-90)), chiều kim đồng hồ: true) – azimov

+0

Cảm ơn! Chính xác! – user3745888

Trả lời

8

Bạn cần chuyển đổi các giá trị được chuyển làm đối số trong phương thức init của UIBezierPath thành CGFloat, vì Swift xem chúng là Double hoặc Float (để bán kính).

let circlePath : UIBezierPath = UIBezierPath(arcCenter: arcCenter, radius: 
CGFloat(radius), startAngle: CGFloat(-rad(90)), endAngle: CGFloat(rad(360-90)), clockwise: true) 
+1

Tôi không hiểu -rad trong tuyên bố ở trên. Đó có phải là một var được khai báo không? Giá trị của nó là gì? – zeeple

+1

Tôi nghĩ rad sẽ ở lại DegreesToRadians -> func rad (giá trị: Double) -> Double { giá trị trả về * M_PI/180.0 } –

0

Swift 3:

let circlePath = UIBezierPath(arcCenter: CGPoint.zero, radius: radius, startAngle: CGFloat(0), endAngle:CGFloat(M_PI * 2), clockwise: true) 
0

này có thể được copypasted vào sân chơi:

import UIKit 
class Circle: UIView { 
    var strokeColor: UIColor 
    var fillColor: UIColor 
    init(frame: CGRect, strokeColor: UIColor, fillColor: UIColor = .clear) { 
     self.strokeColor = strokeColor 
     self.fillColor = fillColor 
     super.init(frame: frame) 
    } 

    required init?(coder aDecoder: NSCoder) { 
     fatalError("init(coder:) has not been implemented") 
    } 
    override func draw(_ rect: CGRect) { 
     let circlePath = UIBezierPath(arcCenter: CGPoint(x: frame.width/2, y: frame.height/2), radius: frame.height/2, startAngle: CGFloat(0), endAngle: CGFloat.pi * 2, clockwise: true) 
     strokeColor.setStroke() 
     fillColor.setFill() 
     circlePath.lineWidth = 1 
     circlePath.stroke() 
    } 

} 


let circle = Circle(frame: CGRect(x: 0, y: 0, width: 100, height: 100), strokeColor: .red, fillColor: .blue) 
Các vấn đề liên quan