Draw Jittery Lines in OpenGL
Suppose I drew some simple lines in OpenGL like this:
glBegin(GL_LINES);
glVertex2f(1, 5);
glVertex2f(0, 1);
glEnd();
How 开发者_C百科do I make the line look jittery, like it was being sketched or drawn with hand?
You could try breaking your line up into segments then adding some random noise with rand().
Here's some ugly but hopefully somewhat useful code. You can refactor this as needed:
const float X1= 1.0f, Y1 = 5.0f, X2 = 0.0f, Y2 = 1.0f;
const int NUM_PTS = 10; //however many points in between
//you will need to call srand() to seed your random numbers
glBegin(GL_LINES);
glVertex2f(START_X, START_Y);
for(unsigned i = 0; i < NUM_PTS; i += 2)
{
float t = (float)i/NUM_PTS;
float rx = (rand() % 200 - 100)/100.0f; //random perturbation in x
float ry = (rand() % 200 - 100)/100.0f; //random perturbation in y
glVertex2f( t * (END_X - START_X) + r, t * (END_Y - START_Y) + r);
glVertex2f((t + 1) * (END_X - START_X), (t + 1) * (END_Y - START_Y));
}
glVertex2f(END_X, END_Y);
glEnd();
I increment the loop by 2 and draw every other point without random perturbation so that the line segments are all joined together.
You might want to be aware of the fact that the glBegin/glEnd style is called "immediate mode" and is not very efficient. It's not even supported on some mobile platforms. If you find your stuff is sluggish look at using vertex arrays.
To make the line look hand-drawn and nicer you might also want to make it fatter and use anti-aliasing.
精彩评论