使用Beta 4,我的代码运行良好:
var red, green, blue, alpha: UnsafePointer<CGFloat>
red = UnsafePointer<CGFloat>.alloc(1)
green = UnsafePointer<CGFloat>.alloc(1)
blue = UnsafePointer<CGFloat>.alloc(1)
alpha = UnsafePointer<CGFloat>.alloc(1)
myColor.getRed(red, green: green, blue: blue, alpha: alpha)
CGContextSetRGBStrokeColor(context, red.memory, green.memory, blue.memory, 1)
red.dealloc(1)
green.dealloc(1)
blue.dealloc(1)
alpha.dealloc(1)
现在使用Beta5,我收到错误“'UnsafePointer.Type'没有名为'alloc'的成员。”
我要做的就是根据UIColor设置CGContext的笔触颜色。我现在应该怎么做? “withUnsafePointers”函数有点儿玩笑 - 它给出了奇怪的错误,它最多只需要三个不安全的指针,而我在这种情况下尝试使用四个。
答案 0 :(得分:25)
这很有效,Swift很聪明,知道如何处理&
运算符:
let color = UIColor.purpleColor()
var r:CGFloat, g:CGFloat, b:CGFloat, a:CGFloat = 0
color.getRed(&r, green: &g, blue: &b, alpha: &a)
CGContextSetRGBStrokeColor(c, r, g, b, a)
如果您真的想自己做分配,请使用您喜欢的味道并构建指针,如下所示:
let p = UnsafeMutablePointer<CGFloat>(calloc(1, UInt(sizeof(CGFloat))))
// later don't forget to free(p)
答案 1 :(得分:9)
UnsafePointer<T>
不再拥有会员.alloc
。请改用UnsafeMutablePointer<T>.alloc
。例如以下blankof()
可用作通用初始化程序。
func blankof<T>(type:T.Type) -> T {
var ptr = UnsafeMutablePointer<T>.alloc(sizeof(T))
var val = ptr.memory
ptr.destroy()
return val
}
var red = blankof(CGFloat)
var green = blankof(CGFloat)
var blue = blankof(CGFloat)
var alpha = blankof(CGFloat)
color.getRed(&red, green:&green, blue:&blue, alpha:&alpha)
CGContextSetRGBStrokeColor(context, red, green, blue, 1)
// no need to dealloc because they are all structs, not pointers
答案 2 :(得分:4)
要回答有关从UIColor
设置描边颜色的问题,这将有效:
CGContextSetStrokeColorWithColor(myUIColor.CGColor);
我在基于C ++的Quartz 2D代码中做了很多。
答案 3 :(得分:1)
从Beta 5开始,您只需传递前缀为&amp;的变量即可。 只需确保初始化它们
有关https://developer.apple.com/swift/blog/?id=6
的更多信息要使用单个变量,您只需将它们设置为零值
即可var r: CGFloat = 0, g: CGFloat = 0, b: CGFloat = 0, a: CGFloat = 0
color.getRed(&r, green: &g, blue: &b, alpha: &a)
要使用C数组,只需创建一个包含预期索引的普通数组
var points:[NSPoint] = [NSPoint(), NSPoint(), NSPoint()] //notice how we set empty NSPoints
self.elementAtIndex(index, associatedPoints: &points)
CGPathAddCurveToPoint(path, nil, points[0].x, points[0].y, points[1].x, points[1].y, points[2].x, points[2].y)