CAShapeLayer的意外StrokeEnd

时间:2019-07-18 19:56:38

标签: ios swift cashapelayer

我正在使用CAShapeLayer绘制圆,由于某种原因,笔划只会以25%的间隔绘制。例如,将StrokeEnd设置为0.4会将笔划绘制到圆的50%。

如何将CAShapeLayer的笔划绘制到预期位置?

import UIKit

class DrawCircle {
    let shapeLayer = CAShapeLayer()
    let trackLayer = CAShapeLayer()
    let center: CGPoint
    let radius: CGFloat
    let startAngle: CGFloat
    let endAngle: CGFloat
    let clockwise: Bool

    let fillColor: CGColor
    let strokeColor: CGColor
    let lineWidth: CGFloat
    var strokeEnd: CGFloat
    let view: UIView
    let circularPath: UIBezierPath
    let withTrack: Bool
    private var trackColor: CGColor

    init(withTrack: Bool, trackColor: CGColor, radius: CGFloat, center: CGPoint, clockwise: Bool, fillColor: CGColor, strokeColor: CGColor, lineWidth: CGFloat, view: UIView) {
        //path params
        self.center = center
        self.radius = radius
        self.startAngle = -CGFloat.pi / 2
        self.endAngle = 2 * CGFloat.pi
        self.clockwise = clockwise
        self.circularPath = UIBezierPath(arcCenter: center, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: clockwise)
        //shape params
        self.fillColor = fillColor
        self.strokeColor = strokeColor
        self.strokeEnd = 0.4
        self.lineWidth = lineWidth

        //view to attach to
        self.view = view
        self.withTrack = withTrack
        if withTrack {
            self.trackColor = trackColor
        } else {
            self.trackColor = UIColor.clear.cgColor
        }
    }

    func draw() {
        if withTrack {
            drawTrack()
            print("track drawn: \(self.trackLayer)")
        }
        shapeLayer.path = circularPath.cgPath
        shapeLayer.strokeColor = strokeColor
        shapeLayer.fillColor = fillColor
        shapeLayer.lineWidth = self.lineWidth
        shapeLayer.strokeEnd = self.strokeEnd
        shapeLayer.lineCap = .round
        view.layer.addSublayer(shapeLayer)
    }

    func drawTrack() {
        trackLayer.path = circularPath.cgPath
        trackLayer.strokeColor = trackColor
        trackLayer.fillColor = UIColor.clear.cgColor
        trackLayer.lineWidth = self.lineWidth
        trackLayer.lineCap = .round
        view.layer.addSublayer(trackLayer)
    }

}

该问题被标记为重复,但是问题完全不同,提供的答案画了一个半圈,而不是一个完整的圈。终止角值完全不同

1 个答案:

答案 0 :(得分:1)

将开始和结束角度更改为:

self.startAngle = -CGFloat.pi / 2 
self.endAngle = 1.5 * CGFloat.pi