2

Dears,

I want to achive rotating an x-axis label on a bar chart by 45 degree. That's currently possible with using like this:

chartView.xAxis.labelRotationAngle = -45

And the result is: Bar chart labels

As you see, the rotating anchor point is exactly the center points of the labels.

But i need to rotate them around their very right corner. So, it prevents overlapping each other.

Nostromo
  • 959
  • 2
  • 7
  • 25

1 Answers1

2

We don't have an easy way to change the rotating anchor point of the labels. But you can define your own custom XAxisRenderer class and override renderAxisLabels function. I have made a simple example and hope this will help you to move in the right direction. I have removed all unnecessary code from renderAxisLabels function and changed anchor point from (x: 0.5, y: 0.0) to (x: 0.8, y: 0.0)

Define custom renderer

class MyXAxisRenderer: XAxisRenderer {
    override func renderAxisLabels(context: CGContext)
    {
        guard let xAxis = self.axis as? XAxis else { return }

        if !xAxis.isEnabled || !xAxis.isDrawLabelsEnabled
        {
            return
        }

        let yOffset = xAxis.yOffset

        guard xAxis.labelPosition == .bottom else { return  }

        let customAnchorPoint = CGPoint(x: 0.8, y: 0.0)  // custom anchor point, default value is (x: 0.5, y: 0.0)

        drawLabels(context: context, pos: viewPortHandler.contentBottom + yOffset, anchor: customAnchorPoint)
    }
}

and use it.

chartView.xAxis.labelRotationAngle = -45
chartView.xAxis.labelPosition = .bottom      
chartView.xAxisRenderer = MyXAxisRenderer(viewPortHandler: chartView.viewPortHandler, xAxis: chartView.xAxis, transformer: chartView.getTransformer(forAxis: .left))
AlexSmet
  • 2,141
  • 1
  • 13
  • 18
  • This is exactly what i need. Solved elegantly! Many thanks. I am just curious about how CGPoint(x:0.8,y:0.0) means the right end side of a label. I will do my own research, but if there is a short explanation, i would like to hear about it. – Nostromo Sep 25 '18 at 07:39
  • 1
    @nostromo821 Actually CGPoint(x:0.8,y:0.0) doesn't mean the right end side of a label. I have used this solution to avoid deep diving into details of labels drawing implementation. – AlexSmet Sep 25 '18 at 09:21