I'm using Java AWT to draw lines on a panel (Line2D
and Graphics2D.drawLine()
) and I'm wondering how I can draw a line with tick marks, similar to:
|----|----|----|----|----|
I know the positions I'd like to draw the ticks at in advance.
The lines could be in any position, so the ticks must be drawn at an angle releative to the line itself.
My basic geometry & ability to apply it in Java is failing me. :)
I suggest you
Math.atan2
.AffineTransform
with translation and rotation before invoking the ruler-drawing-method.Here is a complete test-program. (The
Graphics.create
method is used to create a copy of the original graphics object, so we don't mess up the original transform.)Note, that you could just as easily draw numbers above the ticks. The drawString-calls would go through the same transformation and get nicely "tilted" along the line.
I hope you know matrix multiplication. In order to rotate a line you need to multiple it by rotation matrix. (I coudln't draw a proper matrix but assume both line are not separated)
The old points are x,y and the new is x',y'. Let us illustrate by an example, lets say you have a vertical line from (0,0) to (0,1), now you want to rotate it by 90 degrees. (0,0) will remain zero so lets just see what happens to (0,1)
==
==
you get to horizontal line
(0,0),(0,1)
like you would expect.Hope it helps,
Roni
Things that need noting:
newdx=dy; newdy=-1*dx
.<dx, dy>
is a unit vector (sqrt(dx*dx+dy+dy)==1
, ordx==cos(theta); dy=sin(theta)
for some theta), you then just need to know how far apart you want the tick marks.Thus,
<sx,sy>
(start x,y) to<sx+dx*length,sy+dy*length>
<sx+dx*i-newdx*seglength/2,sy+dy*i-newdy*seglength/2>
to<sx+dx*i+newdx*seglength/2,sy+dy*i+newdy*seglength/2>