我在使用CAShapeLayer
绘制圆圈时遇到问题。我有一个自定义视图MainLogoAnimationView
代码如下:
import UIKit
class MainLogoAnimationView: UIView {
@IBOutlet var customView: UIView!
var redCircle: AnimationCircleView!
// MARK: Object Lifecycle
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
func setup() {
_ = Bundle.main.loadNibNamed("MainLogoAnimationView", owner: self, options: nil)?[0] as! UIView
self.addSubview(customView)
customView.frame = self.bounds
let circleWidth = frame.size.width*0.25
let yPos = frame.size.height/2 - circleWidth/2
redCircle = AnimationCircleView(frame: CGRect(x: 10, y: yPos, width: circleWidth, height: circleWidth))
redCircle.backgroundColor = UIColor.yellow
addSubview(redCircle)
}
override func layoutSubviews() {
super.layoutSubviews()
}
}
在界面构建器中,我创建了浅蓝色UIView
并选择了MainLogoAnimationView
作为子视图。
AnimationCircleView
就像这样:
import UIKit
class AnimationCircleView: UIView {
// MARK: Object lifecycle
var circleColor = UIColor.red.withAlphaComponent(0.5).cgColor {
didSet {
shapeLayer.fillColor = circleColor
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
let shapeLayer = CAShapeLayer()
func setup() {
let circlePath = UIBezierPath(ovalIn: frame)
shapeLayer.path = circlePath.cgPath
shapeLayer.fillColor = circleColor
shapeLayer.frame = self.frame
shapeLayer.backgroundColor = UIColor.gray.cgColor
layer.addSublayer(shapeLayer)
}
}
截图:
似乎CAShapeLayer
框架不正确,红色圆圈也处于错误位置。它应该在黄色方块内。我在这做错了什么?任何指针都会非常感激!谢谢!
更新:
答案 0 :(得分:2)
在AnimationCircleView
里面setup
更改
shapeLayer.frame = self.frame
以强>
shapeLayer.frame = self.bounds
这应确保在黄色矩形内绘制灰色。
修改:
与上面的答案类似,更改
let circlePath = UIBezierPath(ovalIn: frame)
以强>
let circlePath = UIBezierPath(ovalIn: bounds)
将解决您的问题并在灰色区域内绘制圆圈。
CAShapeLayer
帧是相对于其添加的视图的位置计算的,因此将其设置为等于帧,将CAShapeLayer
添加到原点的ax和y位置偏移值在self.frame
中传递的x和y。