tags:

views:

38

answers:

2

I have two points that draw a line when connected. The line can be both vertical horizontal, vertical, or (most commonly) diagonal.

I would like to try text along this path. I'm using C# and WinForms, but I think that isn't as important as some simple psuedo-code that may include some math (trig?) needed to find the angle of the path to align the text to.

+1  A: 

If you are drawing the text in an OnPaint() method, you can try this (reference):

Graphics g = e.Graphics;  // your graphics object.
float deg = 45F;  // an angle, this one is 45 degrees

g.RotateTransform(deg);
g.DrawString("slopey text is fun");
kbrimington
Thanks, this seems to work. The only problem I have currently is that it rotates all the lines and stuff I draw too- though I think I can just create a new graphics object instead.
DMan
You could probably un-rotate the text after drawing the string with `g.RotateTransform(-deg)`.
kbrimington
That works, thanks. I multiplied by -1, but to the same effect as you posted.
DMan
+1  A: 

Use Math.Atan2() to calculate the angle. Convert from radians to degrees by multiplying by 180 / Math.Pi. Getting the center of rotation for RotateTransform() is the critical step to get the text aligned properly with the line. r * Math.Cos(angle) for the X-offset from the line start point, r * Sin(angle) for the Y-offset where r is the offset from the line start point. Adjust by the font's Height to get it above the line.

Hans Passant
What does 'r' represent? Rotation?
DMan
How far away from the line start point you draw the text.
Hans Passant
I currently have ` e.Graphics.TranslateTransform(point.X, point.Y);` as the place for the start point. This seems to work without using Math.Cos/Sin, however, it is now under the line in some cases. What would you suggest I do to get it always above the line, no matter what angle I draw?
DMan
I marked this as the best answer because it covers most of what I'm looking for. I found this order-of-magnitudes easier in WPF, so I decided to do that instead.
DMan