I am trying to render a line/step graph on Apple Watch using watchOS 2. Unlike iOS 9, watchOS 2 doesn't support Quartz. It only supports Core Graphics. I tried writing some code to draw a line graph but I am getting an error "CGContextRestoreGState: invalid context 0x0. This is a serious error. This application, or a library it uses, is using an invalid context and is thereby contributing to an overall degradation of system stability and reliability. This notice is a courtesy: please fix this problem. It will become a fatal error in an upcoming update."
Following is the piece of code I used:
import WatchKit
import Foundation
import UIKit
class InterfaceController: WKInterfaceController{
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
let path = UIBezierPath()
let startPoint = CGPointMake(0.0, 0.0)
path.moveToPoint(startPoint)
let nextPoint = CGPointMake(20.0, 20.0)
path.addLineToPoint(nextPoint)
path.lineWidth = 1.0
UIColor.whiteColor().setStroke()
path.stroke()
}
override func willActivate() {
super.willActivate()
}
override func didDeactivate() {
super.didDeactivate()
}
}
My end result should be something like Stocks app present on Apple Watch. Wwhenever user clicks on particular stock, he will be able to view/visualize the statistics of that stock. Can anybody please help me in achieving this.
The context here are not CGContext, thus you have the issue. I do not think you can use Core Graphics directly on Apple Watch.
Graph render is done by the help of bezierPath and which is converted to image to attached to Apple Watch
//Swift-3 Xcode-8.1
import UIKit class InterfaceController: WKInterfaceController {
Here's the example project that shows how to do dynamic graphs on WatchKit 2.0
https://github.com/vlm/ExampleWatchGraph
The gist of it is in the GraphPainter.swift file, where CoreGraphics is used to draw into an off-screen buffer (as @shu223 suggested), then display this buffer in a WKInterfaceImage.
Animated Watch Interface GIF.
Here's code in watchOS 3
I succeeded to render lines with following steps:
UIGraphicsBeginImageContext
.Code:
image
is WKInterfaceImage property. It works for me.Also I can draw using UIBezierPath on watchOS as follow:
You can check the sample codes here.