在Swift中设置CorePlot十字准线

时间:2016-08-11 23:52:11

标签: ios swift graph core-plot

我正在尝试在Swift中为我的图形创建一个十字线(垂直线)。我已经查看了如何执行此操作的各种Objective-C示例,并在下面的代码中模仿了它们:

class viewController: UIViewController {

@IBOutlet weak var graphView: CPTGraphHostingView!

var plot1: CPTScatterPlot!
var plot2: CPTScatterPlot!
var plot3: CPTScatterPlot!

var plotDataSource1: CPTFunctionDataSource?
var plotDataSource2: CPTFunctionDataSource?
var plotDataSource3: CPTFunctionDataSource?

var markerAnnotation: CPTPlotSpaceAnnotation?

override func viewDidLoad() {
    super.viewDidLoad()
}


override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    initPlot()

}

func initPlot() {

    configureHostView()
    configureGraph()
    configureChart()
    configureAxes()


}

func configureHostView() {
    graphView.allowPinchScaling = true
    print("host con called")
}

func configureGraph() {
    // 1 - Create the graph
    let graph = CPTXYGraph(frame: graphView.bounds)
    graph.plotAreaFrame?.masksToBorder = true
    graphView.hostedGraph = graph

    // 2 - Configure the graph
    graph.applyTheme(CPTTheme(named: kCPTPlainWhiteTheme))
    graph.fill = CPTFill(color: CPTColor.clearColor())
    graph.paddingBottom = 0.0
    graph.paddingLeft = 0.0
    graph.paddingTop = 0.0
    graph.paddingRight = 0.0


    // 3 - Set up styles
    let titleStyle = CPTMutableTextStyle()
    titleStyle.color = CPTColor.blackColor()
    titleStyle.fontName = "HelveticaNeue-Bold"
    titleStyle.fontSize = 16.0
    titleStyle.textAlignment = .Center
    graph.titleTextStyle = titleStyle


    // 4 - Set up plot space
    let xMin = -10.0
    let xMax = 10.0
    let yMin = -10.0
    let yMax = 10.0
    guard let plotSpace = graph.defaultPlotSpace as? CPTXYPlotSpace else { return }
    plotSpace.allowsUserInteraction = true

    plotSpace.xRange = CPTPlotRange(locationDecimal: CPTDecimalFromDouble(xMin), lengthDecimal: CPTDecimalFromDouble(xMax - xMin))

    plotSpace.yRange = CPTPlotRange(locationDecimal: CPTDecimalFromDouble(yMin), lengthDecimal: CPTDecimalFromDouble(yMax - yMin))
    print("graph con called")
}


func configureChart() {
    // 1 - Set up the three plots
    plot1 = CPTScatterPlot()
    plot2 = CPTScatterPlot()
    plot3 = CPTScatterPlot()

    // 2 - Set up line style
    let lineStyle1 = CPTMutableLineStyle()
    lineStyle1.lineColor = CPTColor.blueColor()
    lineStyle1.lineWidth = 0.5

    let lineStyle2 = CPTMutableLineStyle()
    lineStyle2.lineColor = CPTColor.redColor()
    lineStyle2.lineWidth = 0.5

    let lineStyle3 = CPTMutableLineStyle()
    lineStyle3.lineColor = CPTColor.greenColor()
    lineStyle3.lineWidth = 0.5

    // 3 - Add plots to graph
    guard let graph = graphView.hostedGraph else { return }

    plot1.delegate = self
    plot2.delegate = self
    plot3.delegate = self

    //let function: CPTDataSourceFunction? = cos
    let block1 = {(x: Double) -> Double in
        return sin(x)
    }
    let block2 = {(x: Double) -> Double in
        return 1/x
    }
    let block3 = {(x: Double) -> Double in
        return log(x)
    }


    //if (block != nil) {
    plotDataSource1 = CPTFunctionDataSource(forPlot: plot1, withBlock: block1)
    plot1.dataSource = plotDataSource1
    //}

    plotDataSource2 = CPTFunctionDataSource(forPlot: plot2, withBlock: block2)
    plot2.dataSource = plotDataSource2

    plotDataSource3 = CPTFunctionDataSource(forPlot: plot3, withBlock: block3)
    plot3.dataSource = plotDataSource3


    plot1.dataLineStyle = lineStyle1
    plot2.dataLineStyle = lineStyle2
    plot3.dataLineStyle = lineStyle3


    graph.addPlot(plot1, toPlotSpace: graph.defaultPlotSpace)
    graph.addPlot(plot2, toPlotSpace: graph.defaultPlotSpace)
    graph.addPlot(plot3, toPlotSpace: graph.defaultPlotSpace)

    print("chart con called")
}

func configureAxes() {
    // 1 - Configure styles
    let axisLineStyle = CPTMutableLineStyle()
    axisLineStyle.lineWidth = 2.0
    axisLineStyle.lineColor = CPTColor.blackColor()
    let majorGridLineStyle: CPTMutableLineStyle = CPTMutableLineStyle()
    majorGridLineStyle.lineWidth = 0.75
    majorGridLineStyle.lineColor = CPTColor.grayColor()
    let minorGridLineStyle: CPTMutableLineStyle = CPTMutableLineStyle()
    minorGridLineStyle.lineWidth = 0.25
    minorGridLineStyle.lineColor = CPTColor.whiteColor()

    guard let axisSet = graphView.hostedGraph?.axisSet as? CPTXYAxisSet else { return }

    // 3 - Configure the x-axis
    let axisStyle = CPTMutableTextStyle()
    axisStyle.fontSize = 6.0

    //
    let crosshair = CPTXYAxis()
    crosshair.hidden = false
    crosshair.coordinate = CPTCoordinate.Y
    crosshair.plotSpace = graphView.hostedGraph?.defaultPlotSpace
    crosshair.axisConstraints = CPTConstraints(lowerOffset: 10.0)
    crosshair.labelingPolicy = CPTAxisLabelingPolicy.None
    crosshair.separateLayers = true
    crosshair.preferredNumberOfMajorTicks = 6
    crosshair.minorTicksPerInterval = 0
    let cStyle: CPTMutableLineStyle = CPTMutableLineStyle()
    cStyle.lineWidth = 4.0
    cStyle.lineColor = CPTColor.orangeColor()
    crosshair.axisLineStyle = cStyle
    crosshair.majorTickLineStyle = nil
    //

    let x: CPTXYAxis = axisSet.xAxis!
    x.labelingPolicy = .Automatic
    x.title = ""
    x.labelTextStyle = axisStyle

    let y: CPTXYAxis = axisSet.yAxis!
    y.labelingPolicy = .Automatic
    y.title = ""
    y.labelTextStyle = axisStyle

    axisSet.axes = [x, y, crosshair]

    let hitAnnotationTextStyle: CPTMutableTextStyle = CPTMutableTextStyle()
    hitAnnotationTextStyle.color = CPTColor.blackColor()
    hitAnnotationTextStyle.fontName = "Helvetica-Bold"
    hitAnnotationTextStyle.fontSize = 6

    let textLayer: CPTTextLayer = CPTTextLayer(text: "Annotation", style: hitAnnotationTextStyle)
    textLayer.cornerRadius = 3.0
    textLayer.paddingLeft = 2.0
    textLayer.paddingTop = 2.0
    textLayer.paddingRight = 2.0
    textLayer.paddingBottom = 2.0
    textLayer.hidden = false

    let graph = CPTXYGraph(frame: graphView.bounds)
    let plotSpace = graph.defaultPlotSpace as? CPTXYPlotSpace
    let annotation: CPTPlotSpaceAnnotation = CPTPlotSpaceAnnotation(plotSpace: plotSpace!, anchorPlotPoint: [0, 0])
    annotation.contentLayer = textLayer
    graph.addAnnotation(annotation)
    self.markerAnnotation = annotation

    print("axes con called")

}

}

extension viewController: CPTPlotSpaceDelegate, CPTPlotDataSource, CPTScatterPlotDelegate {

func numberOfRecordsForPlot(plot: CPTPlot) -> UInt {
    print("1")
    return (self.plotDataSource1?.dataPlot.cachedDataCount)!
}

func numbersForPlot(plot: CPTPlot, field fieldEnum: UInt, recordIndex index: UInt) -> AnyObject {
    print("2")
    return (self.plotDataSource1?.dataPlot.cachedDoubleForField(UInt(fieldEnum), recordIndex: UInt(index)))!
}

func plotSpace(space: CPTPlotSpace, willDisplaceBy displacement: CGPoint) -> CGPoint {
    print("3")
    return CGPointMake(0.0, 0.0)
}

func plotSpace(space: CPTPlotSpace, willChangePlotRangeTo newRange: CPTPlotRange, forCoordinate coordinate: CPTCoordinate) -> CPTPlotRange? {
    print("4")
    var updatedRange: CPTPlotRange? = nil
    let xySpace: CPTXYPlotSpace = (space as! CPTXYPlotSpace)
    switch coordinate {
    case CPTCoordinate.X:
        updatedRange = xySpace.xRange
    case CPTCoordinate.Y:
        updatedRange = xySpace.yRange
    default:
        break
    }

    return updatedRange!
}

func plotSpace(space: CPTPlotSpace, shouldHandlePointingDeviceDownEvent event: UIEvent, atPoint point: CGPoint) -> Bool {
    print("5")
    let xySpace: CPTXYPlotSpace = (space as! CPTXYPlotSpace)
    let graphy = xySpace.graph!
    let crosshair = graphy.axisSet!.axes![2] as? CPTXYAxis
    var plotPoint = space.plotPointForEvent(event)
    let annotation: CPTPlotSpaceAnnotation = self.markerAnnotation!
    let textLayer: CPTTextLayer = (annotation.contentLayer as! CPTTextLayer)
    var xNumber = plotPoint![CPTCoordinate.X.rawValue]
    var yNumber = plotPoint![CPTCoordinate.Y.rawValue]

    if xySpace.xRange.containsNumber(xNumber) {

        let x: Int = Int(Double(xNumber))
        let y: Int = Int(Double(yNumber))
        xNumber = x
        yNumber = y
        let xValue: String = (graphView.hostedGraph!.axisSet?.axes?[0].labelFormatter!.stringForObjectValue(xNumber)!)!
        let yValue: String = (graphView.hostedGraph!.axisSet?.axes?[1].labelFormatter!.stringForObjectValue(yNumber)!)!
        textLayer.text = "\(xValue), \(yValue)"
        textLayer.hidden = false
        annotation.anchorPlotPoint = [xNumber, yNumber]
        crosshair!.orthogonalPosition = xNumber
        crosshair!.hidden = false

    } else {

        textLayer.hidden = true
        crosshair!.hidden = true

    }

    return false
}

func plotSpace(space: CPTPlotSpace, shouldHandlePointingDeviceDraggedEvent event: UIEvent, atPoint point: CGPoint) -> Bool {
    print("6")
    return self.plotSpace(space, shouldHandlePointingDeviceDraggedEvent: event, atPoint: point)
}

func plotSpace(space: CPTPlotSpace, shouldHandlePointingDeviceUpEvent event: UIEvent, atPoint point: CGPoint) -> Bool {
    print("7")
    return false
}


}

我试图索引的数据是从CPTFunctionDataSource创建的,所以我想要做的可能会更复杂。任何帮助表示赞赏......

0 个答案:

没有答案