David Brunelle
David Brunelle

Reputation: 6450

Draw rotated text in c#

I have a radar chart in chart.js in which I want to draw the labels as rotated. As I could see inthe doc, it is not possible, so I am trying to do it myself using basic drawing in c#. Here is the code I use :

Bitmap objBmpImage = new Bitmap(1000, 1000);
System.Drawing.Font objFont = new System.Drawing.Font("Arial", 12,
    System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel);

Graphics objGraphics = Graphics.FromImage(objBmpImage);
objGraphics.Clear(Color.Transparent);

float angle = (float)360.0 / (float)competences.Count();

objGraphics.TranslateTransform(500, 450);

objGraphics.RotateTransform(-90 - (angle / 3));
foreach (T_Ref_Competence competence in competences)
{
    byte r, g, b;
    HexToInt(competence.T_Ref_CompetenceNiveau2.T_Ref_CompetenceNiveau1.Couleur,
        out r, out g, out b);
    Brush brush = new System.Drawing.SolidBrush(Color.FromArgb(255,r,g,b));
    objGraphics.DrawString(competence.Nom,objFont, brush, 255,0);
    objGraphics.RotateTransform(angle);
}

string filename = Server.MapPath("..\\TempImage\\") + NomUtilisateur + ".png";
objBmpImage.Save(filename,System.Drawing.Imaging.ImageFormat.Png);

HexToInt is just a simple function that takes a #FF0000 and convert it to 3 bytes variables (255,0 and 0 for this exemple).

Here is the result so far :

enter image description here

As you can see, I can get something quite nice. However, I have one last request, which I am pretty sure is possible, but I'm not certain how.

How can I rotate the text 180 degrees for label on the left section ? In this exemple, from "Organisation" to "Vérification qualité et inspection". Mind you, I know how to decide which one I have to turn around, I don't know how to do it.

Thanks.

Upvotes: 1

Views: 192

Answers (1)

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112762

Idea:

  • Add 180 degrees to the angle.
  • Now the labels appear on the wrong side but have the right orientation. Move them by the diameter + textLength to the left. You can do so by providing a negative X to the DrawString call. No need for another transformation.

You can calculate the text length with the Graphics.MeasureString Method.

Upvotes: 2

Related Questions