【问题标题】:Trouble aligning a UIView and a CAShapeLayer无法对齐 UIView 和 CAShapeLayer
【发布时间】:2016-02-27 00:08:26
【问题描述】:

我在对齐 UIViewCAShapeLayer 时遇到问题。

以下是演示该问题的示例代码:

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)
    }
}

这是结果的图像:

如何让两者对齐?

【问题讨论】:

    标签: ios swift uiview cashapelayer


    【解决方案1】:

    您需要做的唯一更改是添加:

    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
    

    【讨论】:

      【解决方案2】:

      如果您将形状图层定位在 (0,0) 会怎样

      strokeLayer.position = CGPointMake( 0, 0 )
      

      【讨论】:

      • 也从你的形状层中移除变换
      猜你喜欢
      • 2015-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多