Saya mencoba memusatkan CAShapeLayer di kotak hitam tetapi untuk beberapa alasan, bentuknya selalu digambar jauh di atas kotak seperti:

enter image description here

Berikut adalah kode yang saya gunakan untuk menggambar lingkaran:

var pulsatingLayer: CAShapeLayer!
let shapeLayer = CAShapeLayer()
    
let timerLabel: UILabel = {
        let label = UILabel()
        label.textAlignment = .center
        if UIScreen.main.bounds.width > 414 {
            label.font = UIFont.systemFont(ofSize: 26, weight: .semibold)
        }
        else {
            label.font = UIFont.systemFont(ofSize: 37, weight: .semibold)
        }
        
        label.textColor = .white
        return label
}()
override func viewDidLoad() {
        super.viewDidLoad()
        
        let circularPath = UIBezierPath(arcCenter: .zero, radius: 35, startAngle: -CGFloat.pi / 2, endAngle: 3 * CGFloat.pi / 2, clockwise: true)

        // timerContainer is the black box
        
        pulsatingLayer = CAShapeLayer()
        pulsatingLayer.path = circularPath.cgPath
        pulsatingLayer.strokeColor = UIColor.clear.cgColor
        pulsatingLayer.lineWidth = 5
        pulsatingLayer.fillColor = UIColor.magenta.cgColor
        pulsatingLayer.position = timerContainer.center
        view.layer.addSublayer(pulsatingLayer)
        
        let trackLayer = CAShapeLayer()
        trackLayer.path = circularPath.cgPath
        trackLayer.strokeColor = UIColor.lightGray.cgColor
        trackLayer.lineWidth = 5
        trackLayer.fillColor = timerContainer.backgroundColor?.cgColor
        trackLayer.position = timerContainer.center
        view.layer.addSublayer(trackLayer)
        
        shapeLayer.path = circularPath.cgPath
        shapeLayer.strokeColor = UIColor.red.cgColor
        shapeLayer.lineWidth = 5
        shapeLayer.fillColor = timerContainer.backgroundColor?.cgColor
        shapeLayer.strokeEnd = 0
        shapeLayer.lineCap = .round
        shapeLayer.position = timerContainer.center
        view.layer.addSublayer(shapeLayer)
        
        view.addSubview(timerLabel)
        timerLabel.frame = CGRect(x: 0, y: 0, width: timerContainer.bounds.width, height: timerContainer.bounds.height)
        timerLabel.center = timerContainer.center
        
        
}

Mengapa lingkaran tidak dipusatkan pada tampilan hitam?

1
Andy_V 10 Juli 2020, 16:56

1 menjawab

Jawaban Terbaik

Anda perlu mengatur posisi di viewDidLayoutSubviews()

     timerContainer.layer.addSublayer(pulsatingLayer)
     timerContainer.layer.addSublayer(trackLayer)
     timerContainer.layer.addSublayer(shapeLayer)
1
Jawad Ali 10 Juli 2020, 16:15