如何使 UIBezierPath 从视图中间开始(目前它是从视图的左角开始)

Posted

技术标签:

【中文标题】如何使 UIBezierPath 从视图中间开始(目前它是从视图的左角开始)【英文标题】:How to make UIBezierPath to start from mid of view (currently it is starting from left corner side of view) 【发布时间】:2021-06-10 08:19:06 【问题描述】:

我正在使用以下代码在其图层上创建带有进度条的圆形视图,但进度条总是从左上角开始,我想让它从视图的顶部中间开始

func buildRoundView1(roundView: UIView, total: Int, borderColor: UIColor, shapeLayer: CAShapeLayer)

    let trackLayer = CAShapeLayer()
    
    let rect = CGRect(x: 0, y: 0, width: roundView.frame.size.width, height: roundView.frame.size.height)
    let circularPath = UIBezierPath(roundedRect: rect, cornerRadius: 10)
    
    trackLayer.path = circularPath.cgPath
    
    trackLayer.lineWidth = 4
    trackLayer.fillColor = UIColor.clear.cgColor
    trackLayer.lineCap = CAShapeLayerLineCap.round
    roundView.layer.addSublayer(trackLayer)
    shapeLayer.path = circularPath.cgPath
    
    shapeLayer.strokeColor = borderColor.cgColor
    shapeLayer.lineWidth = 4
    shapeLayer.fillColor = UIColor.clear.cgColor
    shapeLayer.lineCap = CAShapeLayerLineCap.round
    
    shapeLayer.strokeEnd = 0
    roundView.layer.addSublayer(shapeLayer)
    
    let basicAnimation = CABasicAnimation(keyPath: "strokeEnd")
    let startValue = Double(10800-total).normalize(min: 0.0, max: 10800.0)
    basicAnimation.fromValue = 1 - startValue
    basicAnimation.toValue = 1
    basicAnimation.duration = CFTimeInterval(total)
    basicAnimation.fillMode = CAMediaTimingFillMode.backwards
    basicAnimation.isRemovedOnCompletion = true
    
    shapeLayer.add(basicAnimation, forKey: "urSoBasic")
    

【问题讨论】:

设置矩形框的x位置为x = roundView.frame.size.width/2 它没有用。它超出了roundview范围 【参考方案1】:

一些想法:

    制作您自己的几何图形,而不是使用 UIBezierPath(roundedRect: rect, cornerRadius: 10) 通过移动到点、添加线到点、添加曲线到点等来构造它 将您从UIBezierPath(roundedRect: rect, cornerRadius: 10) 获得的路径旋转 90 度(将其中心平移到原点,然后旋转,再平移回来) 使高度和宽度交换的贝塞尔路径,并通过对其应用变换来旋转 shapeLayer

【讨论】:

以上是关于如何使 UIBezierPath 从视图中间开始(目前它是从视图的左角开始)的主要内容,如果未能解决你的问题,请参考以下文章

为 UIBezierPath 着色

如何使表格视图内的单元格开始向下?

UIBezierPath 路径形状可点击和可拖动

UIBezierPath 动画 - 对象固定在左上角

在视图中绘制许多 UIBezierPath

如何以给定的顺序动画/填充 UIBezierPath?