首页 > 解决方案 > 在 swift 中使用 CAShapeLayer 填充颜色不起作用

问题描述

我正在尝试下面的代码来绘制形状,这没关系,但是UIView 背景颜色没有显示,因为我给View赋予了橙色

查看我的代码:

let myView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
myView.backgroundColor = .orange
let circlePath = UIBezierPath(arcCenter: CGPoint(x: myView.bounds.size.width / 2, y: 0), radius: myView.bounds.size.height, startAngle: 0.0, endAngle: .pi, clockwise: false)
let circleShape = CAShapeLayer()
circleShape.masksToBounds = false
circleShape.path = circlePath.cgPath
circleShape.fillColor = UIColor.orange.cgColor
circleShape.strokeColor = UIColor.orange.cgColor
myView.layer.mask = circleShape
print(myView)

操场上的输出:

截屏

标签: iosswiftswift5.2

解决方案


试试这个代码:

    let myView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
    myView.backgroundColor = .orange
    let circlePath = UIBezierPath(arcCenter: myView.center,
                                  radius: myView.bounds.size.width / 2,
                                  startAngle: 0.0,
                                  endAngle: .pi,
                                  clockwise: false)
    let circleShape = CAShapeLayer()
    circleShape.path = circlePath.cgPath
    myView.layer.mask = circleShape

我认为由于错误的 arcCenter 或起点和终点天使,您看不到预期的结果

代码结果: 在此处输入图像描述


推荐阅读