此代码在框架的x和y为0时有效,但在使用不同的x和y时失败:
class Triangle: UIView {
override func draw(_ rect: CGRect) {
let path = UIBezierPath()
let startX = self.center.x
let startY: CGFloat = 0
path.move(to: CGPoint(x: startX, y: startY))
path.addLine(to: CGPoint(x: self.bounds.width, y: self.bounds.height))
path.addLine(to: CGPoint(x: 0, y: self.bounds.height))
path.close()
UIColor.green.setStroke()
path.stroke()
}
}
import UIKit
class ViewController: UIViewController {
@IBAction func animate(_ sender: UIButton) {
let triangleView = Triangle(frame: CGRect(x: 50, y: 50, width: 30, height: 30))
triangleView.backgroundColor = .clear
self.view.addSubview(triangleView)
}
}
这有效:
let triangleView = Triangle(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
失败时看起来像这样:
那是一个丑陋的三角形。为什么它适用于x:0和y:0并且在那里使用不同的浮点数时会失败?我该如何解决这个问题?
答案 0 :(得分:1)
用let startX = self替换let startX = self.center.x。 bounds.width / 2