我正在尝试围绕其中心点旋转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
}


我的问题是,无论我尝试什么,它总是会抵消:

ios - CAShapeLayer驾驶我疯狂-LMLPHP

两个圆圈的中心应相同。

请帮助这给我发疯...

最佳答案

我已经解决了。需要正确添加边界和锚点:

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)

}

关于ios - CAShapeLayer驾驶我疯狂,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37767336/

10-12 01:51