Search code examples
iosswiftchartsmpandroidchart

danielgindi/Charts: possible to rotate label of ChartLimitLine by 90 degrees?


I am using the amazing Charts library to plot some data. My chart contains a set of ChartLimitLines, and the distance between two of these lines may be small. As a result, the label of one limit line may overlap the following limit line. To avoid this, I would like to rotate the label such that the text is displayed vertically instead of horizontally. I know that I can use limitLine.labelPosition = .leftBottom to move the label to a different position, but I also need to rotate the label. I have browsed the source code of both ChartLimitLine and its Android counterpart (the iOS library is a clone of the MPAndroidChart library), and it appears that there is no API function to achieve this. How do I achieve this on my own? I'm guessing I will have to build a custom view of some sort, but I'm relatively new to the iOS SDK, so any suggestions as to how to approach this would be greatly appreciated.

Thanks!


Solution

  • rotating label text's key point is knowing where the anchor point is.

    Then you just need to use CoreGraphics API like CGContextRotateCTM()

    The rotation's center is the anchor point, so depends on how you want to achieve 90 degree rotation, there are several ways, like:

    1. move the anchor point to the center of your text rect, and rotate there;
    2. move the anchor point to the left corner of your text rect, and rotate there

    depending on where the anchor point is, the final position of your rotated text is uncertain, so you have to think about how do you want to rotate, and then do the math (sin, cos, etc) to properly move your anchor point to your location and then rotate.

    To move the anchor point, you can use CGContextTranslateCTM() and other translate APIs.

    You have to understand the affine transform matrix first (if you don't know what a b c d tx ty mean right now)

    I would highly suggest you create a sample project, make a single view with red background color, and then try rotate, and fill yellow background color, so you can see how is your view rotated from red rect to yellow one.