2

I'm having trouble aligning a UIView and a CAShapeLayer.

Here is sample code demonstrating the issue:

import UIKit

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        let square = UIView(frame: CGRect(x: 100, y: 100, width: 100, height: 100))
        square.transform = CGAffineTransformMakeRotation(CGFloat(20*M_PI/180))
        square.backgroundColor = UIColor.grayColor()
        view.addSubview(square)

        let strokeLayer = CAShapeLayer()
        strokeLayer.path = UIBezierPath(rect: square.bounds).CGPath
        strokeLayer.position = square.center
        strokeLayer.setAffineTransform(square.transform)

        strokeLayer.fillColor = UIColor.clearColor().CGColor
        strokeLayer.strokeColor = UIColor.redColor().CGColor
        strokeLayer.lineWidth = 1

        view.addSubview(square)
        view.layer.addSublayer(strokeLayer)
    }
}

Here's an image of the result:

Result of code in iOS Simulator

How do I get the two to align?

Unheilig
  • 16,196
  • 193
  • 68
  • 98
Trappar
  • 231
  • 2
  • 12

2 Answers2

2

The only change you would need to make is to add:

strokeLayer.frame = square.layer.bounds

Right after:

let strokeLayer = CAShapeLayer()

I.e.,

let strokeLayer = CAShapeLayer()
strokeLayer.frame = square.layer.bounds
strokeLayer.path = UIBezierPath(rect: square.bounds).CGPath
strokeLayer.position = square.center
strokeLayer.setAffineTransform(square.transform)

strokeLayer.fillColor = UIColor.clearColor().CGColor
strokeLayer.strokeColor = UIColor.redColor().CGColor
strokeLayer.lineWidth = 1
Unheilig
  • 16,196
  • 193
  • 68
  • 98
0

What if you position your shape layer at (0,0)

strokeLayer.position = CGPointMake( 0, 0 )
nielsbot
  • 15,922
  • 4
  • 48
  • 73