Render a line graph on Apple Watch using watchOS 2

前端 未结 5 1123
说谎
说谎 2021-02-01 11:13

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 cod

5条回答
  •  北荒
    北荒 (楼主)
    2021-02-01 11:35

    I succeeded to render lines with following steps:

    • Create a bitmap-based graphics context and makes it the current context using UIGraphicsBeginImageContext.
    • Draw into the context.
    • Extract CGImageRef from the context and convert it to UIImage object.
    • Show the image on WKInterfaceGroup or WKInterfaceImage.

    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 is WKInterfaceImage property. It works for me.

    Also I can draw using UIBezierPath on watchOS as follow:

    // 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 sample codes here.

提交回复
热议问题