微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ios – 使用watchOS 2在Apple Watch上渲染折线图

我正在尝试使用watchOS 2在Apple Watch上渲染线条/步骤图.与iOS 9不同,watchOS 2不支持Quartz.它只支持Core Graphics.我尝试编写一些代码绘制折线图但我得到一个错误“CG​​ContextRestoreGState:无效的上下文0x0.这是一个严重的错误.这个应用程序,或它使用的库,正在使用无效的上下文,从而有助于整体系统稳定性和可靠性降低.这个通知是礼貌的:请解决这个问题.在即将到来的更新中它将成为一个致命错误.“

以下是我使用的代码

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()
    }
}

我的最终结果应该像Apple Watch上的Stocks app.每当用户点击特定股票时,他将能够查看/可视化该股票的统计数据.任何人都可以帮助我实现这一目标.

解决方法

我成功地使用以下步骤渲染线条:

>创建基于位图的图形上下文,并使用UIGraphicsBeginImageContext将其设置为当前上下文.
>借鉴上下文.
>从上下文中提取CGImageRef并将其转换为UIImage对象.
>在WKInterfaceGroup或WKInterfaceImage上显示图像.

码:

// 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);
CGContextAddLinetoPoint(context,100,100);
CGContextMovetoPoint(context,100);
CGContextAddLinetoPoint(context,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是WKInterfaceImage属性.这个对我有用.

我也可以在watchOS上使用UIBezierPath绘制如下:

// 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)

您可以查看示例代码here.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐