gpt4 book ai didi

ios - 使用 UIBezierPath 的 PrgressView

转载 作者:行者123 更新时间:2023-11-28 15:38:27 24 4
gpt4 key购买 nike

enter image description here

大家好,尝试创建一个如下所示的自定义进度 View :

但是在设置 progressView.progress = 0.25 时收到很多警告任何人都可以看看这段代码并告诉我哪里出了问题,而且当前的代码似乎不是实现这一目标的最佳选择。也欢迎提出其他想法。

希望我们不需要设置笔画。

这是源代码:

class MyProgressView: UIView {
var progress: CGFloat = 0.5 {
didSet {
setProgress()
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
func setup() {
self.backgroundColor = UIColor.clear
}
override func draw(_ rect: CGRect) {
super.draw(rect)
setProgress()
}
func setProgress() {
var progress = self.progress
progress = progress > 1.0 ? progress / 100 : progress

self.layer.cornerRadius = self.frame.height / 2.0

let width = self.frame.width
let height = self.frame.height

let bgPath = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: width, height: height), cornerRadius: height / 2.0)
UIColor.gray.setFill()
bgPath.fill()
//UIColor.clear.setStroke()
//bgPath.stroke()
bgPath.close()

let width2 = self.frame.width * progress
let highlightPath = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: width2, height: height), cornerRadius: height / 2.0)
UIColor.red.setFill()
highlightPath.fill()
highlightPath.close()

let gapPath1 = UIBezierPath(rect: CGRect(x: width/4-2, y: 0, width: 2, height: height))
UIColor.white.setFill()
gapPath1.fill()
gapPath1.close()

let gapPath2 = UIBezierPath(rect: CGRect(x: width/2-2, y: 0, width: 2, height: height))
UIColor.white.setFill()
gapPath2.fill()
gapPath2.close()

let gapPath3 = UIBezierPath(rect: CGRect(x: width*3/4-2, y: 0, width: 2, height: height))
UIColor.white.setFill()
gapPath3.fill()
gapPath3.close()

self.setNeedsDisplay()
}
}

警告开始于:

CGContextSetFillColorWithColor:无效上下文 0x0。如果要查看回溯,请设置 CG_CONTEXT_SHOW_BACKTRACE 环境变量。5 月 18 日 13:34:13 [7500]:CGContextSaveGState:无效上下文 0x0。如果要查看回溯,请设置 CG_CONTEXT_SHOW_BACKTRACE 环境变量。5 月 18 日 13:34:13 [7500]:CGContextSetFlatness:无效上下文 0x0。如果要查看回溯,请设置 CG_CONTEXT_SHOW_BACKTRACE 环境变量。

最佳答案

CGContextSetFillColorWithColor: invalid context 0x0.

这意味着您正在尝试在没有有效绘图上下文的情况下执行核心图形绘图操作。 0x0nil

当您在没有当前图形上下文的情况下尝试填充或描边路径时,您将获得此输出。

当你自己制作一个当前图形上下文时,这将用于在屏幕外绘制图像,或者当 UIKit 制作一个图形上下文时,它在调用 draw(_ rect:)

您从 draw(_ rect:) 中调用 setProgress(),在这些情况下您的绘图将工作并且不会抛出错误,尽管您需要删除 setNeedsDisplay 从最后调用,因为这只会导致绘图一次又一次地发生。

但是,您也可以从属性观察器中调用它(didSet under progress)。不要直接调用该绘图代码,它不会有上下文,因此会给您控制台警告而不是绘图,您应该只在属性观察器中调用 setNeedsDisplay

关于ios - 使用 UIBezierPath 的 PrgressView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44042890/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com