我收到错误:'(Int, Int)' is not identical to 'CGPoint'
如何将(Int,Int)转换为CGPoint
let zigzag = [(100,100),
(100,150),(150,150),
(150,200)]
override func drawRect(rect: CGRect)
{
// Get the drawing context.
let context = UIGraphicsGetCurrentContext()
// Create the shape (a vertical line) in the context.
CGContextBeginPath(context)
//Error is here
CGContextAddLines(context, zigzag, zigzag.count)
// Configure the drawing environment.
CGContextSetStrokeColorWithColor(context,UIColor.redColor().CGColor)
// Request the system to draw.
CGContextStrokePath(context)
}
答案 0 :(得分:3)
CGContextAddLines()
需要一个CGPoint
数组。如果你已经有了
(Int, Int)
元组的数组,然后您可以使用
let points = zigzag.map { CGPoint(x: $0.0, y: $0.1) }
答案 1 :(得分:2)
避免创建相同类型实例所需的样板代码的另一种方法是让CGPoint
实现ArrayLiteralConvertible
,通过分配CGFloat
数组来初始化它: / p>
extension CGPoint : ArrayLiteralConvertible {
public init(arrayLiteral elements: CGFloat...) {
self.x = elements.count > 0 ? elements[0] : 0.0
self.y = elements.count > 1 ? elements[1] : 0.0
}
}
然后按如下方式使用它:
let zigzag:[CGPoint] = [
[100,100],
[100,150],
[150,150],
[150,200]
]
一些注意事项:
CGPoint
初始化为x = 0
和y = 0
y = 0
答案 2 :(得分:1)
如果它告诉您使用CGPoint,请使用它! Just(number,number)是一对int
s。
let zigzag = [CGPointMake(100,100),
CGPointMake(100,150),CGPointMake(150,150),
CGPointMake(150,200)]
答案 3 :(得分:0)
又一个:
func CGPoints(points:(x:CGFloat, y:CGFloat)...) -> [CGPoint] {
return map(points) { CGPoint($0) }
}
let zigzag = CGPoints(
(100,100),(100,150),(150,150),(150,200)
)