I managed to display the lines with the following steps:
- Create a graphics context based on a bitmap and make it the current context using
UIGraphicsBeginImageContext . - Draw a context.
- Extract the CGImageRef from the context and convert it to a UIImage object.
- Show image on WKInterfaceGroup or WKInterfaceImage.
the code:
// Create a graphics context let size = CGSizeMake(100, 100) UIGraphicsBeginImageContext(size) let context = UIGraphicsGetCurrentContext() // Setup for the path appearance CGContextSetStrokeColorWithColor(context, UIColor.whiteColor().CGColor) CGContextSetLineWidth(context, 4.0) // Draw lines CGContextBeginPath (context); CGContextMoveToPoint(context, 0, 0); CGContextAddLineToPoint(context, 100, 100); CGContextMoveToPoint(context, 0, 100); CGContextAddLineToPoint(context, 100, 0); CGContextStrokePath(context); // Convert to UIImage let cgimage = CGBitmapContextCreateImage(context); let uiimage = UIImage(CGImage: cgimage!) // End the graphics context UIGraphicsEndImageContext() // Show on WKInterfaceImage image.setImage(uiimage)
image - property WKInterfaceImage. This works for me.
I can also draw using UIBezierPath on watchOS as follows:
// Create a graphics context let size = CGSizeMake(100, 100) UIGraphicsBeginImageContext(size) let context = UIGraphicsGetCurrentContext() UIGraphicsPushContext(context!) // Setup for the path appearance UIColor.greenColor().setStroke() UIColor.whiteColor().setFill() // Draw an oval let rect = CGRectMake(2, 2, 96, 96) let path = UIBezierPath(ovalInRect: rect) path.lineWidth = 4.0 path.fill() path.stroke() // Convert to UIImage let cgimage = CGBitmapContextCreateImage(context); let uiimage = UIImage(CGImage: cgimage!) // End the graphics context UIGraphicsPopContext() UIGraphicsEndImageContext() image.setImage(uiimage)
You can check the code samples here .
shu223
source share