views:

118

answers:

3

I have a method that draws a line between two points. This works pretty well, but now I want to make this line into a rectangle.

How can I get the points on the left and right side of each of the line points to make it into a rectangle that I can draw?

It is almost as though I need to somehow figure out how to get perpendicular lines programatically....

A: 

drawRect(x,y,w,h)

tl = (x,y) tr = (x+w, y) br = (x+w, y+h) bl = (x, y+h)

jspcal
A: 

Since you've asked this question with OpenGL taged I'll assume that you wish for a solution that is close to OpenGL.

As you know you have two points that make up a line. Lets call them x1,y1 and x2, y2

Lets also assume that x1, y1 is the top left point and x2, y2 is the bottom right.

Your 4 points to plot will be [you need to perserve order to make a rectangle with GL_LINES)

Height:y1-y1   
Width: x2-x1 

(x1, y1)
(x1+width, y1)
(x2, y2)
(x2-width, y2)
monksy
+1  A: 

I'm guessing you basically want fat lines? Lets assume the line is specified by two points (x0, y0) and (x1, y1) we then have:

float dx = x1 - x0; //delta x
float dy = y1 - y1; //delta y
float linelength = sqrtf(dx * dx + dy * dy);
dx /= linelength;
dy /= linelength;
//Ok, (dx, dy) is now a unit vector pointing in the direction of the line
//A perpendicular vector is given by (-dy, dx)
const float thickness = 5.0f; //Some number
const float px = 0.5f * thickness * (-dy); //perpendicular vector with lenght thickness * 0.5
const float py = 0.5f * thickness * dx;
glBegin(GL_QUADS);
glVertex2f(x0 - px, y0 + py);
glVertex2f(x1 - px, y1 + py);
glVertex2f(x1 + px, y1 - py);
glVertex2f(x0 + px, y0 - py);
glEnd();

Since you're using OpenGL ES I guess you'll have to convert the immediate mode rendering (glBegin, glEnd, etc) to glDrawElements. You'll also have to convert the quad into two triangles.

One final thing, I'm a little tired and uncertain if the resulting quad is counterclockwise or clockwise so turn of backface culling when you try this out (glDisable(GL_CULL)).

Andreas Brinck