2016-08-13 3 views
0

코어 플롯을 실험 중입니다. x : 2.0, y : 50.0에서 그래프 위에 맞춤 '목표'라벨을 추가하려고합니다. 기본적으로 y == 50에 라벨을 붙이고 별도의보기로 표시합니다. 이는 코어 플롯에서 내 플롯으로 변환해야 함을 의미합니다. 내 UIView 범위. 나는 모든 iPhones 화면 크기에서 작동하는 레이어/뷰에서 포인트 변환의 ​​조합을 찾지 못했습니다. 아이폰 6s 아래 내 사진에서 가장 가까운 것입니다.iOS CorePlot 포인트 변환

아이폰 기가 + : iphone 6s+

아이폰 기가 : iphone 6s

아이폰 5S : iphone 5s

내보기 레이아웃 :

class BarChartViewController: UIViewController, CPTBarPlotDataSource 
{ 
    private var barGraph : CPTXYGraph? = nil 
    @IBOutlet weak var textBox: UILabel! 
    @IBOutlet weak var graphHostingView: CPTGraphHostingView! 
    @IBOutlet weak var textBoxView: UIView! 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     self.navigationController?.setNavigationBarHidden(false, animated: false) 

     self.title = "My results" 

     let newGraph = CPTXYGraph(frame: CGRectZero) 
     let theme = CPTTheme(named: kCPTPlainWhiteTheme) 

     newGraph.applyTheme(theme) 

     let hostingView = graphHostingView 
     hostingView.hostedGraph = newGraph 
     if let frameLayer = newGraph.plotAreaFrame 
     { 
      // Border 
      frameLayer.borderLineStyle = nil 
      frameLayer.cornerRadius = 0.0 
      frameLayer.masksToBorder = false 

      // Paddings 
      newGraph.paddingLeft = 0.0 
      newGraph.paddingRight = 0.0 
      newGraph.paddingTop = 0.0 
      newGraph.paddingBottom = 0.0 

      frameLayer.paddingLeft = 70.0 
      frameLayer.paddingTop = 20.0 
      frameLayer.paddingRight = 20.0 
      frameLayer.paddingBottom = 80.0 
     } 

     // Plot space 
     let plotSpace = newGraph.defaultPlotSpace as? CPTXYPlotSpace 
     plotSpace?.yRange = CPTPlotRange(location: 0.0, length: 100.0) 
     plotSpace?.xRange = CPTPlotRange(location: 0.0, length: 4.0) 

     let axisSet = newGraph.axisSet as? CPTXYAxisSet 

     if let x = axisSet?.xAxis { 
      x.axisLineStyle = nil 
      x.majorTickLineStyle = nil 
      x.minorTickLineStyle = nil 
      x.majorIntervalLength = 5.0 
      x.orthogonalPosition = 0.0 
      x.title = "X Axis" 
      x.titleLocation = 7.5 
      x.titleOffset = 55.0 

      // Custom labels 
      x.labelRotation = CGFloat(M_PI_4) 
      x.labelingPolicy = .None 

      let customTickLocations = [0.5, 1.5, 2.5] 
      let xAxisLabels = ["Label A", "Label B", "Label C"] 

      var labelLocation = 0 
      var customLabels = Set<CPTAxisLabel>() 
      for tickLocation in customTickLocations 
      { 
       let newLabel = CPTAxisLabel(text: xAxisLabels[labelLocation], textStyle: x.labelTextStyle) 
       labelLocation += 1 
       newLabel.tickLocation = tickLocation 
       newLabel.offset = x.labelOffset + x.majorTickLength 
       newLabel.rotation = 0 //CGFloat(M_PI_4) 
       customLabels.insert(newLabel) 
      } 

      x.axisLabels = customLabels 
     } 

     if let y = axisSet?.yAxis 
     { 
      y.axisLineStyle = nil 
      y.majorGridLineStyle = CPTMutableLineStyle() 
      var style = y.majorTickLineStyle?.mutableCopy() as? CPTMutableLineStyle 
      //style!.lineColor = CPTColor(CGColor: UIColor.blackColor()) //UIColor.blackColor()) 
      style!.lineWidth = 10.0 
      y.minorGridLineStyle = CPTMutableLineStyle() 
      style = y.minorTickLineStyle?.mutableCopy() as? CPTMutableLineStyle 
      //style.lineColor = UIColor.redColor() 
      style!.lineWidth = 10.0 
      style!.lineCap = .Round 
      y.majorTickLength = 10.0 
      y.majorIntervalLength = 50.0 
      y.orthogonalPosition = 0.0 
      y.title = "Y Axis" 
      y.titleOffset = 45.0 
      y.titleLocation = 150.0 

      y.labelRotation = 0 
      y.labelingPolicy = .None 


      let customTickLocations = [50, 100] 
      let yAxisLabels = ["50", "100"] 

      var labelLocation = 0 
      var customLabels = Set<CPTAxisLabel>() 
      for tickLocation in customTickLocations 
      { 
       let newLabel = CPTAxisLabel(text: yAxisLabels[labelLocation], textStyle: y.labelTextStyle) 
       labelLocation += 1 
       newLabel.tickLocation = tickLocation 
       newLabel.offset = y.labelOffset + y.majorTickLength 
       newLabel.rotation = 0 //CGFloat(M_PI_4) 
       customLabels.insert(newLabel) 
      } 

      y.axisLabels = customLabels 
      var nums = Set<NSNumber>() 
      nums.insert(NSNumber(double: 50.0)) 
      y.majorTickLocations = nums 
     } 

     // First bar plot 
     let barPlot1 = CPTBarPlot.tubularBarPlotWithColor(CPTColor.yellowColor(), horizontalBars: false) 
     barPlot1.baseValue = 0.0 
     barPlot1.dataSource = self 
     //barPlot1.barOffset = 0.5 
     barPlot1.identifier = "Bar Plot 1" 
     let textStyle = CPTMutableTextStyle() 
     textStyle.color = CPTColor.redColor() 
     textStyle.fontSize = 10.0 
     barPlot1.labelTextStyle = textStyle 
     newGraph.addPlot(barPlot1, toPlotSpace: plotSpace) 

     self.barGraph = newGraph 
    } 

    override func viewWillAppear(animated: Bool) { 
     super.viewWillAppear(animated) 

     self.view.layoutIfNeeded() 

     let point: [Double] = [2.0, 50.0] 
     let plotPoint = UnsafeMutablePointer<Double>(point) 
     var dataPoint = self.barGraph?.defaultPlotSpace?.plotAreaViewPointForDoublePrecisionPlotPoint(plotPoint, numberOfCoordinates: 2) 
     //dataPoint = graphHostingView.layer.convertPoint(dataPoint!, fromLayer: self.barGraph!.plotAreaFrame!.plotArea) 
     dataPoint = graphHostingView.layer.convertPoint(dataPoint!, toLayer: graphHostingView.layer.superlayer) 
     //dataPoint = barGraph?.convertPoint(dataPoint!, fromLayer: graphHostingView.layer) 
     dataPoint = self.textBoxView.convertPoint(dataPoint!, fromView: graphHostingView) 

     print(dataPoint!) 
     for item in (self.textBoxView?.constraints)! 
     { 
      if let id = item.identifier 
      { 
       if id == "goalX" 
       { 
        print(item.constant) 
        item.constant = CGFloat((dataPoint?.x)!) - item.constant 
       } 
       else if id == "goalY" 
       { 
        print(item.constant) 
        item.constant = CGFloat((dataPoint?.y)!) - item.constant 
       } 
      } 
     } 
     barGraph?.titleDisplacement = CGPoint(x: dataPoint!.x * -1, y: dataPoint!.y * -1) 
     barGraph?.titlePlotAreaFrameAnchor = .TopLeft 
     self.textBoxView?.layoutIfNeeded() 
    } 
} 
: 여기 View layout

내 클래스

CorePlot에 대한 몇 가지 다른 질문을 토대로 CorePlot 레이어를 새로운보기로 변환해야한다는 것을 알고 있습니다. viewWillAppear()에서 일부 실험을 끝내고 내가 무엇을 시도했는지 확인합니다. SO에 대한 해결책 중 어느 것도 작동하지 않는 것처럼 보였고 iOS에 익숙하지 않았으므로 아마 뭔가 빠졌을 것입니다. 내 라벨이 모든 화면 크기에서 제대로 표시 되려면 어떤 전환이 필요합니까?

+0

그래프 제목이 전혀 표시되지 않습니다. 왜 당신은'titleDisplacement'와'titlePlotAreaFrameAnchor'를 업데이트하고 있습니까? –

+0

잘 들어, 필자는 예제 코드에서이 코드를 꺼내는 것을 잊어 버렸고, 나는 그것을 나의 실험에서 사용했다. – Brad

답변

1

올바른 전환점을 얻었습니다. 이것이 내가하는 방법입니다 :

// Update layer layout if needed 
self.view.layoutIfNeeded() 
graphHostingView.layer.layoutIfNeeded() 

// Point in data coordinates 
let point: [Double] = [2.0, 50.0] 

// Data point in plot area layer coordinates 
var dataPoint = self.barGraph?.defaultPlotSpace?.plotAreaViewPointForPlotPoint(point) 

// Convert data point to graph hosting view coordinates 
dataPoint = graphHostingView.layer.convertPoint(dataPoint!, fromLayer: self.barGraph!.plotAreaFrame!.plotArea) 

그래프 호스팅보기를 기준으로 텍스트 상자의 제약 조건을 업데이트하려면이 방법을 사용하십시오.

+0

난 이걸 시도하고 아이폰 5s, 6s, 6s +에서 모두 동일한 좌표 x : 325, y : 256을 반환한다. 5s에서 목표는 화면을 벗어남, 6s : y는 맞지만 x는 직접적이지 않다. x = 2.0 이상에서 오른쪽, 6s + : y는 너무 작아서 x는 너무 커서 - 선 위로 그리고 오른쪽으로 멀리 밀었습니다. 나는 좌표가 모두 달라야한다고 잘못 생각하고 있는가? – Brad

+0

단계를 잊어 버렸습니다. 레이어의 레이아웃도 업데이트해야합니다. (나는 나의 대답을 편집했다.) –

+0

마지막으로 코멘트를 한 후 높이/너비가 정확하지 않아 layoutIfNeeded가 viewWillAppear에서 작동하지 않는다는 것을 알게되었다. viewDidLayoutSubviews로 업데이트 코드를 변경하고 마지막으로 올바른 값을 제공하는 dataPoint를 갖게되었습니다. layoutIfNeeded가 viewWillAppear에서 작동하지 않는 이유는 아직 확실하지 않습니까? 대답 해줘서 고마워. – Brad