为什么strokeColor for CAShapeLayer不能与alpha组件一起使用?它有2个不同颜色的边框

问题描述 投票:1回答:1

添加我的代码。它正在添加另一个带有另一个alpha的边框,比如阴影。

let sliderLayer = CAShapeLayer()
    sliderLayer.fillColor = UIColor.white.cgColor
    sliderLayer.strokeColor = UIColor.red.withAlphaComponent(0.5).cgColor
    sliderLayer.lineWidth = 20
    sliderLayer.miterLimit = 0.0
    sliderLayer.lineCap = kCALineCapRound
    sliderLayer.lineJoin = kCALineJoinRound
    let bezierPath = UIBezierPath()
    bezierPath.addArc(withCenter: CGPoint(x:bounds.midX, y:bounds.midY), radius: 190 / 2, startAngle: 0, endAngle: CGFloat(Double.pi * 2), clockwise: true)
    sliderLayer.path = bezierPath.cgPath
ios swift calayer
1个回答
4
投票

这是因为笔划与填充颜色重叠。当你给它一个0.5的alpha值时,你让白色显示50%,因此红色看起来是粉红色的一半。 50%红色,50%白色=粉红色。

enter image description here

这是一个展示如何使用alpha值实现边框的游乐场。您需要使用2个圆圈并将它们分层以获得所需的效果。

import UIKit
import PlaygroundSupport

class MyViewController : UIViewController {
    override func loadView() {
        super.loadView()

        self.view.backgroundColor = .black
        self.view.frame = CGRect(x: 0, y: 0, width: 1024, height: 768)

        let bezierPath = UIBezierPath()
        bezierPath.addArc(withCenter: CGPoint(x:200, y:200), radius: 190 / 2, startAngle: 0, endAngle: CGFloat(Double.pi * 2), clockwise: true)

        let redCircle = CAShapeLayer()
        redCircle.fillColor = UIColor.red.withAlphaComponent(0.5).cgColor
        redCircle.path = bezierPath.cgPath

        let bezierPath2 = UIBezierPath()
        bezierPath2.addArc(withCenter: CGPoint(x:200, y:200), radius: 170 / 2, startAngle: 0, endAngle: CGFloat(Double.pi * 2), clockwise: true)

        let whiteCircle = CAShapeLayer()
        whiteCircle.fillColor = UIColor.white.cgColor
        whiteCircle.path = bezierPath2.cgPath

        redCircle.addSublayer(whiteCircle)
        self.view.layer.addSublayer(redCircle)
    }
}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()
PlaygroundPage.current.needsIndefiniteExecution = true

生产:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.