无法对齐UIView和CAShapeLayer
我在调整UIView
和CAShapeLayer
遇到了麻烦。
以下是演示此问题的示例代码:
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) } }
这是结果的图像:
如何让两者对齐?
您需要做的唯一更改是添加:
strokeLayer.frame = square.layer.bounds
紧接着:
let strokeLayer = CAShapeLayer()
也就是说,
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
如果将形状图层定位在(0,0),该怎么办?
strokeLayer.position = CGPointMake( 0, 0 )