我试图在Swift中画一个圆圈,但是当我编写代码时,我收到一个错误"找不到“初始化”的过载。接受提供的参数。
在类UIBezierPath中有一个init函数:
init(arcCenter center: CGPoint, radius: CGFloat, startAngle: CGFloat, endAngle: CGFloat, clockwise: Bool) -> UIBezierPath
但是当我用这个代码声明这个时我得到错误..需要我将任何变量转换为其他类型吗?但如果我在iphone 4中编译了这个,我就不会在iphone 5 / 5s中得到错误。怎么能正确地声明这个?
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)
谢谢!
答案 0 :(得分:10)
您需要将在UIBezierPath的init方法中作为参数传递的值转换为CGFloat,因为Swift将它们视为Double或Float(让半径)。
let circlePath : UIBezierPath = UIBezierPath(arcCenter: arcCenter, radius:
CGFloat(radius), startAngle: CGFloat(-rad(90)), endAngle: CGFloat(rad(360-90)), clockwise: true)
答案 1 :(得分:0)
斯威夫特3:
let circlePath = UIBezierPath(arcCenter: CGPoint.zero, radius: radius, startAngle: CGFloat(0), endAngle:CGFloat(M_PI * 2), clockwise: true)
答案 2 :(得分:0)
这可以被复制到游乐场:
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)