Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ios

swift

xcode6

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.

like image 773
DrScott Avatar asked Mar 20 '23 08:03

DrScott


1 Answers

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)
like image 74
GRiker Avatar answered Mar 22 '23 13:03

GRiker