我正在尝试制作环形的UIBezierPath
用作path
的{{1}}
以下内容将产生一个循环路径:
CAShapeLayer
但是,我想要一个环形的let radius = 100.0
let circularPath = UIBezierPath(arcCenter: .zero, radius: radius, startAngle: 0.0, endAngle: 2.0 * .pi, clockwise: true)
let layer = CAShapeLayer()
layer.path = circularPath.cgPath
,它填充在UIBezierPath
和radius
之间。
答案 0 :(得分:1)
如果这是您要使用的形状(“环形”形状):
您可以通过创建椭圆形路径并附加较小的椭圆形路径来实现。
您可以直接在Playground页面中运行此命令以获得该结果:
import PlaygroundSupport
import UIKit
class AnnulusView: UIView {
private var annulusLayer: CAShapeLayer!
private var annulusWidth: CGFloat = 10.0
private var fillColor: UIColor = .red
override func layoutSubviews() {
super.layoutSubviews()
if annulusLayer == nil {
annulusLayer = CAShapeLayer()
layer.addSublayer(annulusLayer)
}
let r = bounds
let outerPath = UIBezierPath(ovalIn: r)
let innerPath = UIBezierPath(ovalIn: r.insetBy(dx: annulusWidth, dy:annulusWidth))
outerPath.append(innerPath)
outerPath.usesEvenOddFillRule = true
annulusLayer.path = outerPath.cgPath
annulusLayer.fillRule = kCAFillRuleEvenOdd
annulusLayer.fillColor = fillColor.cgColor
// if you want a border
// annulusLayer.lineWidth = 1
// annulusLayer.strokeColor = UIColor.black.cgColor
}
}
class TestingViewController: UIViewController {
override public var preferredContentSize: CGSize {
get { return CGSize(width: 400, height: 400) }
set { super.preferredContentSize = newValue }
}
var theAnnulusView: AnnulusView = {
let v = AnnulusView()
v.translatesAutoresizingMaskIntoConstraints = false
return v
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
view.addSubview(theAnnulusView)
// make the Annulus view 100x100 centered in this view
NSLayoutConstraint.activate([
theAnnulusView.widthAnchor.constraint(equalToConstant: 100),
theAnnulusView.heightAnchor.constraint(equalToConstant: 100),
theAnnulusView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
theAnnulusView.centerYAnchor.constraint(equalTo: view.centerYAnchor),
])
}
}
let viewController = TestingViewController()
PlaygroundPage.current.liveView = viewController
答案 1 :(得分:0)
检查一下,可能会有所帮助。
如果需要一个完整的圆圈,则需要调整arcCenter
let width:CGFloat = 10
let radius:CGFloat = 100.0-width/2
let circularPath = UIBezierPath(arcCenter: .zero, radius: radius, startAngle: 0.0, endAngle: 2.0 * .pi, clockwise: true)
let layer = CAShapeLayer()
layer.lineWidth = width
layer.path = circularPath.cgPath