简体   繁体   English

多个带有.round lineCap的CAShapeLayers相互重叠

[英]Multiple CAShapeLayers with .round lineCap are overlapped by each other

I try to combine multiple layers using .round lineCap and a semicircle path:我尝试使用lineCap .round半圆路径组合多个图层:

let layer = CAShapeLayer()
layer.lineWidth = 12
layer.lineCap = .round
layer.strokeColor = color.withAlphaComponent(0.32).cgColor
layer.fillColor = UIColor.clear.cgColor
// angles calculation
let path = UIBezierPath(arcCenter: arcCenter,
                        radius: radius,
                        startAngle: startAngle,
                        endAngle: engAngle,
                        clockwise: true)
layer.path = path.cgPath

trying to achieve the following:试图实现以下目标:

在此处输入图像描述

but my layers are overlapped by each other.但我的图层相互重叠。 Is it possible to fix it somehow fast or do I need to implement path calculating with rounded corners manually?是否可以以某种方式快速修复它,还是我需要手动实现带圆角的路径计算?

在此处输入图像描述

When .lineCap =.round we get a "circle" centered at the endpoint with a radius of 1/2 the line width:.lineCap =.round我们得到一个以端点为中心的“圆”,半径为线宽的 1/2:

在此处输入图像描述

So, to get the circle-round end to sit at the endpoint, we can adjust the endpoint by asin(lineWidth * 0.5 / radius) :因此,要让圆形末端位于端点处,我们可以通过asin(lineWidth * 0.5 / radius)调整端点:

在此处输入图像描述

Assuming we're going in a clockwise direction:假设我们顺时针方向:

let delta: CGFloat = lineCap == .round ? asin(lineWidth * 0.5 / radius) : 0.0

let path = UIBezierPath(arcCenter: center,
                        radius: radius,
                        startAngle: startDegrees.radians + delta,
                        endAngle: endDegrees.radians - delta,
                        clockwise: true)

So, if we have a series of degrees forming this image with .lineEnd =.butt (the default):所以,如果我们用.lineEnd =.butt (默认值)形成这个图像的一系列度数:

在此处输入图像描述

we can get this by offsetting the start and end angles:我们可以通过偏移开始和结束角度来得到这个:

在此处输入图像描述

Here's a complete example class:这是一个完整的示例 class:

class ConnectedArcsView: UIView {
    
    public var segmentDegrees: [CGFloat] = [] {
        didSet {
            var n: Int = 0
            if let subs = layer.sublayers {
                n = subs.count
                if n > segmentDegrees.count {
                    // if we already have sublayers,
                    //  remove any extras
                    for _ in 0..<n - segmentDegrees.count {
                        subs.last?.removeFromSuperlayer()
                    }
                }
            }
            // add sublayers if needed
            while n <  segmentDegrees.count {
                let l = CAShapeLayer()
                l.fillColor = UIColor.clear.cgColor
                layer.addSublayer(l)
                n += 1
            }
            setNeedsLayout()
        }
    }
    
    // segment colors default: [.red, .green, .blue]
    public var segmentColors: [UIColor] = [.red, .green, .blue] { didSet { setNeedsLayout() } }
    
    // line width default: 12
    public var lineWidth: CGFloat = 12 { didSet { setNeedsLayout() } }
    
    // line cap default: .round
    public var lineCap: CAShapeLayerLineCap = .round  { didSet { setNeedsLayout() } }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        guard let subs = layer.sublayers else { return }
        
        let radius = (bounds.size.width - lineWidth) * 0.5
        let center = CGPoint(x: bounds.midX, y: bounds.midY)
        
        // if lineCap == .round
        //  calculate delta for start and end angles
        let delta: CGFloat = lineCap == .round ? asin(lineWidth * 0.5 / radius) : 0.0
        
        // calculate start angle so the "gap" is centered at the bottom
        let totalDegrees: CGFloat = segmentDegrees.reduce(0.0, +)
        var startDegrees: CGFloat = 90.0 + (360.0 - totalDegrees) * 0.5
        
        for i in 0..<segmentDegrees.count {
            let endDegrees = startDegrees + segmentDegrees[i]
            
            guard let shape = subs[i] as? CAShapeLayer else { continue }
            
            shape.lineWidth = lineWidth
            shape.lineCap = lineCap
            shape.strokeColor = segmentColors[i % segmentColors.count].cgColor
            
            let path = UIBezierPath(arcCenter: center,
                                    radius: radius,
                                    startAngle: startDegrees.radians + delta,
                                    endAngle: endDegrees.radians - delta,
                                    clockwise: true)
            
            shape.path = path.cgPath
            
            startDegrees += segmentDegrees[i]
        }
        
    }

}

and an example view controller showing its usage:和一个示例视图 controller 显示其用法:

class ExampleViewController: UIViewController {
    
    let testView = ConnectedArcsView()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = .systemBlue
        
        let degrees: [CGFloat] = [
            40, 25, 140, 25, 40
        ]
        
        let colors: [UIColor] = [
            .systemRed, .systemYellow, .systemGreen, .systemYellow, .systemRed
        ] //.map { ($0 as UIColor).withAlphaComponent(0.5) }
        
        testView.segmentDegrees = degrees
        testView.segmentColors = colors
        testView.lineWidth = 12
        
        testView.backgroundColor = .black
        testView.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(testView)
        
        // add an info label
        let v = UILabel()
        v.textAlignment = .center
        v.numberOfLines = 0
        v.text = "Tap anywhere to toggle between\n\".round\" and \".butt\""
        v.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(v)
        
        let g = view.safeAreaLayoutGuide
        NSLayoutConstraint.activate([
            
            testView.topAnchor.constraint(equalTo: g.topAnchor, constant: 40.0),
            testView.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 40.0),
            testView.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: -40.0),
            testView.heightAnchor.constraint(equalTo: testView.widthAnchor),
            
            v.topAnchor.constraint(equalTo: testView.bottomAnchor, constant: 20.0),
            v.widthAnchor.constraint(equalTo: testView.widthAnchor),
            v.centerXAnchor.constraint(equalTo: testView.centerXAnchor),
            
        ])
        
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        testView.lineCap = testView.lineCap == .round ? .butt : .round
    }
    
}

When running, tapping anywhere will toggle between .round and .butt .跑步时,点击任意位置将在 .round 和.round之间.butt


Edit - forgot to include the helper extension:编辑- 忘记包含辅助扩展:

extension CGFloat {
    var degrees: CGFloat {
        return self * CGFloat(180) / .pi
    }
    var radians: CGFloat {
        return self * .pi / 180.0
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM