如何以编程方式在具有约束的视图中放置圆形绘图

How to place programmatically a circle drawing in the view with constraints

我参加了一个关于如何为进度指示器创建一个圆圈的网络研讨会,我对其进行了编码并且运行良好,但我找不到的是如何以编程方式移动我的圆圈的约束以将其从我的视图中心移动到中央较低的位置(y = center-100)。我尝试了各种方式,比如 ->

.centerYAnchor.constraint(等于:view.centerYAnchor,常量:100).isActive = true

但命令无效

  @IBOutlet weak var CircleView: UIView!
  

let shapeLayer = CAShapeLayer()
let basicAnimation = CABasicAnimation(keyPath: "strokeEnd")


override func viewDidLoad() {
    super.viewDidLoad()
    
    
    // Drawing a circle
    
    let center = view.center


    // create track layer
    
    let trackLayer = CAShapeLayer()
    
    let circularPath = UIBezierPath(arcCenter: center, radius: 125, startAngle: -CGFloat.pi / 2, endAngle: 2*CGFloat.pi - CGFloat.pi/2, clockwise: true)
    trackLayer.path = circularPath.cgPath
    trackLayer.strokeColor = UIColor.lightGray.cgColor
    trackLayer.lineWidth = 10
    trackLayer.fillColor = UIColor.clear.cgColor
    view.layer.addSublayer(trackLayer)
    
    // shape layer below
    
    shapeLayer.path = circularPath.cgPath
    //shapeLayer.strokeColor = UIColor.red.cgColor
    shapeLayer.lineWidth = 10
    shapeLayer.fillColor = UIColor.clear.cgColor
    shapeLayer.lineCap = CAShapeLayerLineCap.round
    shapeLayer.strokeEnd = 0

CircleView.layer.addSubview(shapeLayer)

如果您想在视图上绘制一个遵守布局约束的圆圈,它需要在视图中。

我建议创建一个自定义 UIView,将其添加为将绘制圆的视图的子视图,然后对该自定义视图施加约束。

您可以设置 UIView 的自定义子class,它使用 CAShapeLayer 作为其内容层,并在其边界更改时更新其路径。

我创建了一个示例 UIView class,OvalView,它使用 CAShapeLayer 设置自己作为其支持层的 class。当层的边界发生变化时,它会更新形状层中的路径以包含一个圆角矩形,其角半径是视图边界的较短尺寸的 1/2。如果视图的边界是正方形,则形状将是圆形。如果视图的边界是矩形,则形状将为“菱形”。

我创建了一个演示如何使用 OvalView 的示例项目。您可以 download it from Github 并亲自尝试一下。

它使用故事板创建包含 2 个 OvalView 的视图。当您旋转 phone 时,视图的大小会发生变化,因此 OvalView 的大小也会发生变化。

画面是这样的:

下面是 OvalView 的代码:

//
//  OvalView.swift
//  CircleViews
//
//  Created by Duncan Champney on 4/10/22.
//
/*  Copyright © 2022 Duncan Champney.
    Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */



import UIKit


/// This class simply fills its bounds with a rounded rectangle. As the view's bounds change, it updates itself so the path fills the bounds.
/// When the layer's bounds change, it updates the path in the shape layer to contain a rounded rectangle who's corner radius is 1/2 the shorter dimension of the view's bounds. If the view's bounds are a square, the shape will be a circle. If the view's bounds are rectangular, the shape will be a "lozenge"
class OvalView: UIView {

    /// A computed property that casts the view's backing layer to type CAShapeLayer for convenience.
    var shapeLayer: CAShapeLayer { return self.layer as! CAShapeLayer }

    /// This is the color used to draw the oval. If you change it, the didSet will change the layer's strokeColor
    public var ovalColor: UIColor = .blue{
        didSet {
            guard let layer = self.layer as? CAShapeLayer else { return }
            layer.strokeColor = ovalColor.cgColor
        }
    }

    /// This declaration causes the  OvalView's backing layer to be a CAShapeLayer
    override class var layerClass : AnyClass {
       return CAShapeLayer.self}

    /// If the view's bounds change, update our layer's path
    override var bounds: CGRect {
        didSet {
            createPath()
        }
    }

    /// When we get added to a view, set up our shape layer's properties.
    override func didMoveToSuperview() {
        shapeLayer.strokeColor = ovalColor.cgColor
        shapeLayer.fillColor = UIColor.clear.cgColor
        shapeLayer.lineWidth = 1
    }

    /// Build the path for our shape layer and install it.
    func createPath() {
        let cornerRaidus = min(bounds.height, bounds.width)
        let path = UIBezierPath(roundedRect: bounds, cornerRadius: cornerRaidus)
        shapeLayer.path = path.cgPath
    }
}