对于初始问题,请查看此帖子的edit-log。
我主要使用here中的代码,现在不确定要放入 outerCircleView(frame:???):,以便正确显示在我为 outerCirvleView:UIButton 设置的约束中。
var circleLayer: CAShapeLayer!
@IBDesignable // enables rendering in StoryBoard
class outerCircleView: UIButton {
override init(frame: CGRect) {
super.init(frame: frame)
// Use UIBezierPath as an easy way to create the CGPath for the layer.
// The path should be the entire circle.
let circlePath = UIBezierPath(arcCenter: CGPoint(x: frame.size.width / 2.0, y: frame.size.height / 2.0), radius: (frame.size.width - 10)/2, startAngle: 0.0, endAngle: CGFloat(M_PI * 2.0), clockwise: true)
// Setup the CAShapeLayer with the path, colors, and line width
circleLayer = CAShapeLayer()
circleLayer.path = circlePath.CGPath
circleLayer.fillColor = UIColor.clearColor().CGColor
circleLayer.strokeColor = UIColor.redColor().CGColor
circleLayer.lineWidth = 5.0;
// Don't draw the circle initially
circleLayer.strokeEnd = 0.0
// Add the circleLayer to the view's layer's sublayers
layer.addSublayer(circleLayer)
}
required init(coder aDecoder: NSCoder!)
{
super.init(coder: aDecoder)
}
func animateCircle(duration: NSTimeInterval) {
// We want to animate the strokeEnd property of the circleLayer
let animation = CABasicAnimation(keyPath: "strokeEnd")
// Set the animation duration appropriately
animation.duration = duration
// Animate from 0 (no circle) to 1 (full circle)
animation.fromValue = 0
animation.toValue = 1
// Do a linear animation (i.e. the speed of the animation stays the same)
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
// Set the circleLayer's strokeEnd property to 1.0 now so that it's the
// right value when the animation ends.
circleLayer.strokeEnd = 1.0
// Do the actual animation
circleLayer.addAnimation(animation, forKey: "animateCircle")
}
}
func addCircleView() {
// Create a new CircleView
var circleView = outerCircleView(frame: ???)
view.addSubview(circleView)
// Animate the drawing of the circle over the course of 1 second
circleView.animateCircle(1.0)
}
答案 0 :(得分:2)
您链接的帖子详细说明了详细信息。
如该帖所述,您不需要使用drawRect。 (因此,调整代码的方法是重新开始使用新方法。) 相反,您需要创建一个CAShapeLayer并将其安装为视图的子层。然后,您可以使用CABasicAnimation为形状图层的strokeEnd属性设置动画。
您编辑的代码中没有任何地方可以设置形状图层的框架。
将以下代码添加到layoutSubviews方法中:(如果您还没有,请创建一个。)
override func layoutSubviews()
{
var frame = self.layer.bounds
circleLayer.frame = frame
}
保留在init中创建circlePath的代码,因为您只想这样做一次。
将创建圈子路径的代码移至layoutSubviews
。初始化后,您的视图大小通常会发生变化。如果视图的大小发生变化,则调用layoutSubviews,这就是您想要的。 (当用户旋转手机时,您的视图可能会改变大小。如果发生这种情况,layoutSubviews
将再次被调用,您将生成一个新的,正确大小的圆圈路径,这是您想要做的。您想要调整大小您的圈子图层,并在每次视图更改大小时重建圆圈路径。)