Call CGPatternCreate in Swift

余生颓废 提交于 2019-12-10 18:08:34

问题


I'm wondering how to convert the following objective-c method to Swift function?

CGPatternRef pattern = CGPatternCreate(NULL,
                                       rect,
                                       CGAffineTransformIdentity,
                                       24,
                                       24,
                                       kCGPatternTilingConstantSpacing,
                                       true,
                                       &callbacks);

My code:

    let callbacks : CGPatternCallbacks = CGPatternCallbacks(version: 0)

    let pattern : CGPatternRef = CGPatternCreate(nil,
        rect,
        CGAffineTransformIdentity,
        24,
        24,
        kCGPatternTilingConstantSpacing,
        true,
        callbacks)

But I got an error message:

'CGPatternCallbacks' is not convertible to 'CConstPointer'

Is there any sample code for this? Thanks


回答1:


Something like that

var callbacks : CGPatternCallbacks = CGPatternCallbacks(version: 0)

var pattern = CGPatternCreate(nil,
    rect,
    CGAffineTransformIdentity,
    24,
    24,
    kCGPatternTilingConstantSpacing,
    true,
    &callbacks)



回答2:


This solution is a problematic one:

The pointer registered within CGPatternCallbacks (for a function that draws the pattern) should be CFunctionPointer<(UnsafeMutablePointer, CGContext>)->Void) This means that the function pointer should be transformed to UnasfeMutablePointer then to COpaquePointer then to CFuncfionPointer

And still anyway i'm getting an exception on function call, there is a simplier solution: [http://www.raywenderlich.com/90695/modern-core-graphics-with-swift-part-3][1]




回答3:


  1. Option 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. Option 2 - the 'swift' way

    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)
    


来源:https://stackoverflow.com/questions/24179988/call-cgpatterncreate-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!