ios - CAShapeLayer 路径未显示
问题描述
我目前正在制作圆形进度条,为此我创建了一个 customView。但是 shapeLayer 没有被显示。我尝试向 shapeLayer 以及背景颜色添加一个框架,但是这只显示了一个矩形而不是我期望看到的圆形路径。关于我做错了什么的任何想法:思考:
import UIKit
class CircularProgressBar: UIView {
override func draw(_ rect: CGRect) {
setupProgressView()
}
private func setupProgressView() {
let shapeLayer = CAShapeLayer()
let circularPath = UIBezierPath(arcCenter: center,
radius: 100,
startAngle: 0,
endAngle: 2*CGFloat.pi,
clockwise: true)
shapeLayer.path = circularPath.cgPath
shapeLayer.fillColor = UIColor.blue.cgColor
shapeLayer.strokeColor = UIColor.yellow.cgColor
shapeLayer.lineWidth = 20
self.layer.addSublayer(shapeLayer)
}
}
解决方案
设置 shapeLayer 框架
shapeLayer.frame = bounds
更好的方法是不使用draw方法
import UIKit
@IBDesignable
class CircularProgressBar: UIView {
private lazy var shapeLayer: CAShapeLayer = {
let shape = CAShapeLayer()
shape.fillColor = UIColor.blue.cgColor
shape.strokeColor = UIColor.yellow.cgColor
shape.lineWidth = 20
return shape
}()
override init(frame: CGRect) {
super.init(frame: frame)
addLayers()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
addLayers()
}
private func addLayers() {
layer.addSublayer(shapeLayer)
}
override func layoutSubviews() {
updatePath()
}
private func updatePath() {
let circularPath = UIBezierPath(arcCenter: CGPoint(x: bounds.midX, y: bounds.midY),
radius: min(bounds.midX, bounds.midY) - shapeLayer.lineWidth/2,
startAngle: 0,
endAngle: 2*CGFloat.pi,
clockwise: true)
shapeLayer.frame = bounds
shapeLayer.path = circularPath.cgPath
}
}
推荐阅读
- ios - 调用方法 reloadData()
- python - 这个给定的文本是 json 格式。因为我是 python 新手,所以告诉我如何只从用户那里获取 id
- jmeter - 如何在 Jmeter 的本地主机上记录 Web 应用程序的测试脚本?
- python - .py 文件的依赖项
- python - 使用 python-onvif-zeep 禁用 IP PTZ 摄像机自动对焦
- python - Bamboo 错误 - ImportError:没有名为 pandas 的模块
- java - 如何在 mybatis 中获取字符串数组“String[]”的返回原语
- python - 为什么所有 vilidation 样本输出相同的输出
- sql - Oracle:即使没有约束或索引,重命名列也会出现“ORA-00903:无效表名”错误
- websphere - 如何使用 ADFS 配置 WebSphere Portal、IBM Watson 和 IBM Connections?