2

Followed is a small code to show text along a line. The "bar" is what I want. My question is how I can get the "bar" case no matter from "A to B" or "B to A'.

Generally, I want to draw a line and text along the line. To be convenient (no need of thinking about which point is the start point or end point), the text's angle is same to that of the line, no relating to from -- to.Thank you.

outputtemplate := "%j-%c.eps";
prologues := 1 ;

beginfig(1)
  pair A, B;
  A = (0,0);
  B = (3cm,3cm);
  draw A -- B;
  label.top ("foo", origin) rotated angle(A-B) shifted 1/2[A, B];
  label.top ("bar", origin) rotated angle(B-A) shifted 1/2[A, B];
endfig;

enter image description here

2
  • Can you explain better what you want. You need to know the start and end in the correct order to specify which direction to write along the line. Are you perhaps looking to force the angles to be between -90 and +90 degrees (so the text is roughly left to right)? Commented Oct 25, 2017 at 10:03
  • @ Andrew, I know the start and end point determine the direction. In my case, the "bar" is the only I want. Is it possible? On the other hand, the degree could be -180~+180 degrees. But you are right that the text is roughly left to right.
    – warem
    Commented Oct 25, 2017 at 10:22

1 Answer 1

4

To get the text to go roughly left to right, you can add 180 degrees to the angle when it is not in the interval -90 to 90. (As far as I can tell the output of angle lies in the interval -180 to 180.)

Sample output

outputtemplate := "%j-%c.eps";
prologues := 3 ;

beginfig(1)
  pair A, B, X, Y;
  numeric ang;
  def angletoright(expr P, Q) =
    begingroup save ang;
      ang := angle(P-Q);
      if (ang <=-90) or (ang > 90): ang+180 else: ang fi
    endgroup
  enddef;
  A = (0,0);
  B = (3cm,3cm);
  draw A -- B;
  label.top ("bar", origin) rotated angletoright(B,A) shifted 1/2[A,B];
  X = A shifted (.5cm,0);
  Y = B shifted (.5cm,0);
  draw X -- Y;
  label.top ("foo", origin) rotated angletoright(X,Y) shifted 1/2[X,Y];
endfig;

end

An alternative definition for angletoright is to take the difference vector and ensure that its xpart is positive and then compute the angle:

  def lefttoright(expr P, Q) =
    begingroup save Z; pair Z;
      Z := P-Q;
      if (xpart Z) < 0: -Z else: Z fi
    endgroup
  enddef;
  def angletoright(expr P, Q) =
    angle(lefttoright(P,Q))
  enddef;
1
  • Thanks a lot. It worked. Glad to know the scope of angle function.
    – warem
    Commented Oct 25, 2017 at 19:07

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .