简体   繁体   中英

How do I save and restore a graphics context in Swift on iOS?

I am porting a Mac app to iOS (and from Objective-C to Swift) and in Xcode I get several errors in the console stating that I'm using an invalid graphics context:

: CGContextSetFillColorWithColor: invalid context 0x0.

: CGContextSetStrokeColorWithColor: invalid context 0x0.

: CGContextGetCompositeOperation: invalid context 0x0.

: CGContextSetCompositeOperation: invalid context 0x0.

: CGContextFillRects: invalid context 0x0.

However, even after removed the code where I was dropping down into Core Graphics and only using UIColor and UIBezierPath, the errors remain.

The only code where I'd used Core Graphics directly was to set shadows, but I strongly suspect my code for saving and restoring the graphics context in Swift is wrong:

if let context: CGContext! = UIGraphicsGetCurrentContext() {
    CGContextSaveGState(context)
    let shadowColor = UIColor(white:0, alpha:0.75).CGColor
    CGContextSetShadowWithColor(context, offset, blurRadius, shadowColor)
}

// Do drawing here...

if let context: CGContext! = UIGraphicsGetCurrentContext() {
    CGContextSetShadowWithColor(context, CGSizeMake(0.0, 0.0), CGFloat(0.0), nil)
    CGContextRestoreGState(context)
}

Would two different values for context be used here? Is that the problem with this code? Thanks for your help.

Here's what I'm using to save and restore context in Swift:

// Save the graphics context
let currentContext = UIGraphicsGetCurrentContext()
CGContextSaveGState(currentContext)

... your graphics operations here ...

// Restore the previously saved context
CGContextRestoreGState(currentContext)

Updated Swift-3 Code to save and restore Graphic Context :-

//To save current Context
    let context = UIGraphicsGetCurrentContext()
    context!.saveGState()

//To restore 
    context!.restoreGState()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM