解决方案:这是我最终创建的类的 GitHub 链接/将在 https://github.com/ckalas/SimpleSwiftBarGraph 上扩展
我正在尝试(在 Playground 上)使用 Core Graphics 绘制条形图。我将其基于 Obj-C 中的这段代码:
- (void)drawRect:(CGRect)rect {
CGFloat height = self.bounds.size.height;
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextClearRect(context, rect);
CGContextSetFillColorWithColor(context, [UIColor grayColor].CGColor);
CGFloat barWidth = 30;
int count = 0;
for (NSNumber *num in values) {
CGFloat x = count * (barWidth + 10);
CGRect barRect = CGRectMake(x, height - ([num floatValue] * height), barWidth, [num floatValue] * height);
CGContextAddRect(context, barRect);
count++;
}
CGContextFillPath(context);
}
我正在尝试转换它,但在第二行,Xcode 不知道 UIGraphicsGetCurrentContext()。有人可以提供帮助吗?
编辑:这是我当前的代码...现在问题出现在我评论的 for 循环中,无论我尝试什么组合,我都无法让该行工作。只是错误无法将类型转换为类型,我尝试将数组声明为 [NSNumber],但没有成功。
class CustomView: UIView {
init(frame: CGRect) {
super.init(frame: frame)
}
override func drawRect(rect: GCRect) {
let values: [UInt8] = [1,2,3]
let height = self.bounds.size.height
let context = UIGraphicsGetCurrentContext()
CGContextClearRect(context, self.frame)
CGContextSetFillColorWithColor(context, UIColor.grayColor().CGColor!);
let barWidth = 30.0 as CGFloat
var count = 0 as CGFloat
for number in values {
let x = count * (barWidth + 10) as CGFloat
let barRect = CGRectMake(x, (height - number*height), barWidth, number*height) // issues here can't convert one type to another
CGContextAddRect(context, barRect)
count++
}
CGContextFillPath(context)
}
最佳答案
将您的 values
数组声明为 [CGFloat]
类型。我做了一些其他风格上的更改(删除了分号,CGColor
已经隐式展开,因此不需要 !
,并且更喜欢类型声明来强制转换)。
class CustomView: UIView {
init(frame: CGRect) {
super.init(frame: frame)
}
override func drawRect(rect: CGRect) {
let values: [CGFloat] = [0.3, 0.6, 0.9]
let height = self.bounds.size.height
let context = UIGraphicsGetCurrentContext()
CGContextClearRect(context, self.frame)
CGContextSetFillColorWithColor(context, UIColor.grayColor().CGColor)
let barWidth:CGFloat = 30.0
var count:CGFloat = 0
for number in values {
let x = count * (barWidth + 10)
let barRect = CGRectMake(x, (height - number*height), barWidth, number*height)
CGContextAddRect(context, barRect)
count++
}
CGContextFillPath(context)
}
}
values
数组中的值范围应为 0.0
(无条形高度)到 1.0
(全条形高度)。
关于objective-c - Swift - 从 obj-c 移植条形图代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24926741/