我正在尝试围绕其中心点旋转CAShapeLayer。我对边界,框架,锚点和中心点感到困惑。
我在UIView中创建了一个圆形CAShape,并希望围绕它的中心旋转它。我只包含了一些代码。
创建我希望旋转的圆的功能:
func drawCompassImage(){
//Compass Bezel Ring
let baseCirclePath = UIBezierPath()
baseCirclePath.addArcWithCenter(CGPoint(x: CGFloat(self.frame.width/2), y: CGFloat(self.frame.width/2)), radius: CGFloat(baseCircleRadius), startAngle: CGFloat(-M_PI_2), endAngle:CGFloat(M_PI_2*3), clockwise: true)
compassImage.path = baseCirclePath.CGPath
compassImage.fillColor = UIColor.clearColor().CGColor;
compassImage.strokeColor = UIColor.whiteColor().CGColor
compassImage.lineDashPattern = [1.0,2.0]
compassImage.lineWidth = 10.0
self.layer.addSublayer(compassImage)
}
创建红点的功能:
func drawCompassRedDot() {
let compassBall = CAShapeLayer ()
let compassBallPath = UIBezierPath ()
let compassBallRadius :CGFloat = 5
let xStart: Float = Float(Float(baseCircleRadius) * cos(270 * Float(M_PI) / 180)) + Float(self.frame.width/2)
let yStart: Float = Float(Float(baseCircleRadius) * sin(270 * Float(M_PI) / 180)) + Float((self.frame.height/2)+0)
compassBallPath.addArcWithCenter(CGPoint(x: CGFloat(xStart), y: CGFloat(yStart)), radius: compassBallRadius, startAngle: CGFloat(-M_PI_2), endAngle:CGFloat(M_PI_2*3), clockwise: true)
compassBall.path = compassBallPath.CGPath
compassBall.fillColor = UIColor.redColor().CGColor;
compassBall.strokeColor = UIColor.redColor().CGColor
compassBall.lineWidth = 1.0
self.compassImage.addSublayer(compassBall)
}
要旋转的功能:
func animate(){
compassImage.transform = CATransform3DMakeRotation(degree2radian(45), 0, 0, 1)
}
func degree2radian(a:CGFloat)->CGFloat {
let b = CGFloat(M_PI) * a/180
return b
}
我的问题是我尝试的任何事情总是结束:
两个圆圈应该具有相同的中心。
请帮助这让我疯狂......
答案 0 :(得分:1)
我已经解决了。需要正确添加边界和锚点:
compassImage.frame = bounds
compassImage.anchorPoint = CGPoint(x: 0.5, y: 0.5)
因此代码如下所示:
func drawCompassImage(){
//Compass Bezel Ring
let baseCirclePath = UIBezierPath()
baseCirclePath.addArcWithCenter(CGPoint(x: CGFloat(self.frame.width/2), y: CGFloat(self.frame.width/2)), radius: CGFloat(baseCircleRadius), startAngle: CGFloat(-M_PI_2), endAngle:CGFloat(M_PI_2*3), clockwise: true)
compassImage.path = baseCirclePath.CGPath
compassImage.frame = bounds
compassImage.anchorPoint = CGPoint(x: 0.5, y: 0.5)
compassImage.fillColor = UIColor.clearColor().CGColor;
compassImage.strokeColor = UIColor.whiteColor().CGColor
compassImage.lineDashPattern = [1.0,2.0]
compassImage.lineWidth = 10.0
self.layer.addSublayer(compassImage)
}