我正在尝试在Circle的中心渲染形状,Circle是UIView的自定义子类(第一个代码段)。然后,在我的VC中添加Circle作为子视图并添加约束(第二个片段)。
当限制高度和宽度时,渲染的形状的中心(不希望地)位于“圆”视图(波纹管)的左上角。当仅限制“圆”视图的X和Y时,形状将按预期在中心。
为什么会发生这种情况,我该怎么做才能约束Circle,但仍在Circle的中心渲染形状?谢谢。
圆圈:
class Circle: UIView {
func render(){
let shapeLayer = CAShapeLayer()
let center = self.center
let endAngle = 2 * CGFloat.pi
let circularPath = UIBezierPath(arcCenter: center, radius: 100, startAngle: 0, endAngle: endAngle, clockwise: true)
shapeLayer.path = circularPath.cgPath
self.layer.addSublayer(shapeLayer)
}
}
VC:
class VC: UIViewController {
let circle = Circle()
override func viewDidLoad() {
super.viewDidLoad()
configure()
circle.render()
}
func configure(){
view.backgroundColor = .white
view.addSubview(progressCircle)
progressCircle.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
progressCircle.centerYAnchor.constraint(equalTo: view.centerYAnchor),
progressCircle.centerXAnchor.constraint(equalTo: view.centerXAnchor),
progressCircle.heightAnchor.constraint(equalToConstant: 200),
progressCircle.widthAnchor.constraint(equalToConstant: 200)
])
}
}
结果:
class Circle: UIView {
let shapeLayer = CAShapeLayer()
override func layoutSubviews() {
super.layoutSubviews()
shapeLayer.position = CGPoint(x: self.bounds.midX, y: self.bounds.midY)
}
func render(){
let center = self.center
let endAngle = 2 * CGFloat.pi
let circularPath = UIBezierPath(arcCenter: center, radius: 100, startAngle: 0, endAngle: endAngle, clockwise: true)
shapeLayer.path = circularPath.cgPath
self.layer.addSublayer(shapeLayer)
}
}
class TTCircleView: UIView {
private var backbroundLayer: CAShapeLayer!
private var foregroundLayer: CAShapeLayer!
private var textLayer: CATextLayer!
override func draw(_ rect: CGRect) {
let width = rect.width
let height = rect.height
let lineWidth = 0.1 * min(width, height)
let center = CGPoint(x: width / 2, y: height / 2)
let radius = (min(width, height) - lineWidth) / 2
let startAngle = -CGFloat.pi / 2
let endAngle = startAngle + 2 * CGFloat.pi
let circularPath = UIBezierPath(arcCenter: center, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: true)
backbroundLayer = CAShapeLayer()
backbroundLayer.path = circularPath.cgPath
backbroundLayer.strokeColor = UIColor.lightGray.cgColor
backbroundLayer.lineWidth = lineWidth
backbroundLayer.fillColor = UIColor.clear.cgColor
backbroundLayer.lineCap = .round
layer.addSublayer(backbroundLayer)
}
}