在Swift中调用CGPatternCreate
我想知道如何将下面的Objective-C方法转换为Swift函数?
CGPatternRef pattern = CGPatternCreate(NULL, rect, CGAffineTransformIdentity, 24, 24, kCGPatternTilingConstantSpacing, true, &callbacks);
我的代码:
let callbacks : CGPatternCallbacks = CGPatternCallbacks(version: 0) let pattern : CGPatternRef = CGPatternCreate(nil, rect, CGAffineTransformIdentity, 24, 24, kCGPatternTilingConstantSpacing, true, callbacks)
但是我收到一条错误消息:
“CGPatternCallbacks”不能转换为“CConstPointer”
有没有这样的示例代码? 谢谢
就是这样
var callbacks : CGPatternCallbacks = CGPatternCallbacks(version: 0) var pattern = CGPatternCreate(nil, rect, CGAffineTransformIdentity, 24, 24, kCGPatternTilingConstantSpacing, true, &callbacks)
这个解决scheme是有问题的:
在CGPatternCallbacks中注册的指针(对于绘制模式的函数)应该是CFunctionPointer <(UnsafeMutablePointer,CGContext>) – > Void)这意味着函数指针应该被转换为UnasfeMutablePointer,然后转换为COpaquePointer,然后转换为CFuncfionPointer
仍然无论如何,我得到函数调用exception,有一个简单的解决scheme:[ http://www.raywenderlich.com/90695/modern-core-graphics-with-swift-part-3%5D [1 ]
-
选项1
//global function - outside of the class func myDrawColoredPattern(info: UnsafeMutablePointer<Void>, context: CGContextRef?) -> Void { //draw pattern using context.... } var callbacks : CGPatternCallbacks = CGPatternCallbacks(version: 0, drawPattern: myDrawColoredPattern, releaseInfo: nil) let pattern: CGPatternRef? = CGPatternCreate(nil, rect, CGAffineTransformIdentity, 24, 24, CGPatternTiling.ConstantSpacing, true, &callbacks)
-
选项2 – “快捷”的方式
let drawPattern: CGPatternDrawPatternCallback = { (_, context) in //draw pattern using context... } var callbacks = CGPatternCallbacks(version: 0, drawPattern: drawPattern, releaseInfo: nil) let pattern: CGPatternRef? = CGPatternCreate(nil, rect, CGAffineTransformIdentity, 24, 24, CGPatternTiling.ConstantSpacing, true, &callbacks)