How to save and restore graphic context in Swift on iOS?

I am porting a Mac application on iOS (and from Objective-C to Swift), and on Xcode I get a few errors in the console, stating that I am 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 deleting the code in which I dipped in Core Graphics, and only using UIColor and UIBezierPath, errors remain.

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

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)
}

Can two different context values โ€‹โ€‹be used here? Is this a problem with this code? Thank you for your help.

+4
source share
2 answers

Here is what I use 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)
+4
source

Updated Swift-3 code to save and restore graphic context : -

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

//To restore 
    context!.restoreGState()
+3
source

Source: https://habr.com/ru/post/1544191/


All Articles