简体   繁体   中英

CALayer Rotation around center

I wanna do something like round progress bar, drawing bezier path in UIView, but it appears rotated by PI/2. So I need to rotate it by PI/2. Problem is, that it is rotating around some very strange point, and I don't know how to deal with it. I tried to follow these instructions, but it doesn't help, because I wanna rotate it around center. Here is my code:

required init(coder aDecoder: NSCoder) {
    ringLayer = CAShapeLayer()
    ringLayerBackground = CAShapeLayer()
    super.init(coder: aDecoder)
    ringLayer.lineCap = kCALineCapButt
    ringLayer.fillColor = nil
    ringLayerBackground.lineCap = kCALineCapButt
    ringLayerBackground.fillColor = nil
    ringLayerBackground.strokeColor = UIColor(white: 0.5, alpha: 0.1).CGColor
    }


override func layoutSubviews() {
    layer.addSublayer(ringLayer)
    layer.addSublayer(ringLayerBackground)
    addSubview(imageView)
    let rectForRing = CGRectInset(bounds, lineWidth/2, lineWidth/2)        
    //ringLayer.setAffineTransform(CGAffineTransformMakeRotation(5))
    ringLayer.transform = CATransform3DRotate(ringLayer.transform, CGFloat(-M_PI/20), 0.0, 0.0, 1.0)
    //Tried both ways
    ringLayer.path = CGPathCreateWithEllipseInRect(rectForRing, nil)
    ringLayerBackground.path = CGPathCreateWithEllipseInRect(rectForRing, nil)
    super.layoutSubviews()
    }

Here is what I'm getting

I know there are a lot of similar question, but they don't help. Thanks!

UPDATE Found magic number, that works on iPhone 6: 140

let o = 140.0
ringLayer.transform = CATransform3DTranslate(ringLayer.transform, CGFloat(o), CGFloat(o), 0)
ringLayer.transform = CATransform3DRotate(ringLayer.transform, CGFloat(-M_PI/2), 0.0, 0.0, 1.0)
ringLayer.transform = CATransform3DTranslate(ringLayer.transform, CGFloat(-o), CGFloat(-o), 0)

Works fine, but I can't guess where that number comes from.

UPDATE Solved it. It was thing in ringLayer.position , need to set it to the centre of view. After that, I made rect for bezier path so, that its center is the same with ringLayer.position . So code became complex, solution from @chrisco is much more applicable.

To answer your problem, but not your immediate question:

var progreessLayer = CAShapeLayer()
// add layer to your view etc

var path = UIBezierPath(arcCenter: center,
    radius: 100, startAngle: CGFloat(-M_PI_2),
    endAngle: CGFloat(3 * M_PI_2), clockwise: true)
progreessLayer.path = path.CGPath
progreessLayer.lineWidth = 10
progreessLayer.strokeColor = UIColor.blackColor().CGColor
progreessLayer.fillColor = nil

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM