Render a line graph on Apple Watch using watchOS 2

前端 未结 5 1126
说谎
说谎 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:22

    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 {

    @IBOutlet var graphImage: WKInterfaceImage!
    override func awake(withContext context: Any?) {
        super.awake(withContext: context)
    
        // Configure interface objects here.
    }
    override func willActivate() {
    
        super.willActivate()
        let path = createBeizePath()
    
        //Change graph to image
        let image:UIImage = UIImage.shapeImageWithBezierPath(bezierPath: path, fillColor: .red, strokeColor: .black)
        graphImage.setImage(uiimage)
    }
    
    //Draw graph here
    func createBeizePath() -> UIBezierPath
    {
        let path = UIBezierPath()
        //Rectangle path Trace
        path.move(to: CGPoint(x: 20, y: 100) )
        path.addLine(to: CGPoint(x: 50 , y: 100))
        path.addLine(to: CGPoint(x: 50, y: 150))
        path.addLine(to: CGPoint(x: 20, y: 150))
        return path
      }
    }
    
    extension UIImage {
            class func shapeImageWithBezierPath(bezierPath: UIBezierPath, fillColor: UIColor?, strokeColor: UIColor?, strokeWidth: CGFloat = 0.0) -> UIImage! {
                bezierPath.apply(CGAffineTransform(translationX: -bezierPath.bounds.origin.x, y: -bezierPath.bounds.origin.y ) )
                let size = CGSize(width: 100    , height: 100)
                UIGraphicsBeginImageContext(size)
                let context = UIGraphicsGetCurrentContext()
                var image = UIImage()
                if let context  = context {
                    context.saveGState()
                    context.addPath(bezierPath.cgPath)
                    if strokeColor != nil {
                        strokeColor!.setStroke()
                        context.setLineWidth(strokeWidth)
                    } else { UIColor.clear.setStroke() }
                    fillColor?.setFill()
                    context.drawPath(using: .fillStroke)
                     image = UIGraphicsGetImageFromCurrentImageContext()!
                    context.restoreGState()
                    UIGraphicsEndImageContext()
                }
                return image
            }
        }
    

提交回复
热议问题