#include <gl/glut.h>
static GLsizei iMode=1;
int winWidth=400,winHeight=300;
int num=0,a[100],b[100],w1,h1,w2,h2;
int iPointNum=0,x1,x2,y1,y2;
void Initial(void)
{
glClearColor(1.0f,1.0f,1.0f,1.0f);
}
void ChangeSize(int w,int h)
{
winWidth=w,winHeight=h;
glViewport(0,0,w,h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0,winWidth,0.0,winHeight);
}
void Display(void)
{
GLint i;
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1.0f,0.0f,0.0f);
if(iMode==1)
{
glBegin(GL_LINE_STRIP);
for(i=0;i<num;i++)
glVertex2i(a[i],b[i]);
glEnd();
glBegin(GL_LINES);
glVertex2i(w1,h1);
glVertex2i(w2,h2);
glEnd();
}
else if(iMode==2)
{
glBegin(GL_LINES);
glVertex2i(x1,y1);
glVertex2i(x2,y1);
glEnd();
glBegin(GL_LINES);
glVertex2i(x1,y1);
glVertex2i(x1,y2);
glEnd();
glBegin(GL_LINES);
glVertex2i(x2,y1);
glVertex2i(x2,y2);
glEnd();
glBegin(GL_LINES);
glVertex2i(x1,y2);
glVertex2i(x2,y2);
glEnd();
}
glutSwapBuffers();
}
void MousePlot(GLint button,GLint action,GLint xMouse,GLint yMouse)
{
if(iMode==1)
{
if(button==GLUT_LEFT_BUTTON&&action==GLUT_DOWN)
{
if(num==0)
{
w1=xMouse;h1=winHeight-yMouse;
a[num]=w1;b[num]=h1;num++;
}
else
{
w2=xMouse;h2=winHeight-yMouse;
a[num]=w2;b[num]=h2;num++;
w1=w2;h1=h2;
glutPostRedisplay();
}
}
if(button==GLUT_RIGHT_BUTTON&&action==GLUT_DOWN)
{
num=0;
glutPostRedisplay();
}
}
else if(iMode==2)
{
if(button==GLUT_LEFT_BUTTON&&action==GLUT_DOWN)
{
if(iPointNum==0||iPointNum==2)
{
iPointNum=1;
x1=xMouse;y1=winHeight-yMouse;
}
else
{
iPointNum=2;
x2=xMouse;y2=winHeight-yMouse;
glutPostRedisplay();
}
}
if(button==GLUT_RIGHT_BUTTON&&action==GLUT_DOWN)
{
iPointNum=0;
glutPostRedisplay();
}
}
}
void PassiveMouseMove(GLint xMouse,GLint yMouse)
{
if(iMode==1)
{
if(num)
{
w2=xMouse;
h2=winHeight-yMouse;
glutPostRedisplay();
}
}
else if(iMode==2)
{
if(iPointNum==1)
{
x2=xMouse;
y2=winHeight-yMouse;
glutPostRedisplay();
}
}
}
void ProcessMenu(int value)
{
iMode=value;
glutPostRedisplay();
}
int main(int argc,char* argv[])
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGB);
glutInitWindowSize(1000,600);
glutInitWindowPosition(100,100);
glutCreateWindow("橡皮筋技术");
glutCreateMenu(ProcessMenu);
glutAddMenuEntry("折线",1);
glutAddMenuEntry("矩形",2);
glutAttachMenu(GLUT_RIGHT_BUTTON);
glutDisplayFunc(Display);
glutReshapeFunc(ChangeSize);
glutMouseFunc(MousePlot);
glutPassiveMotionFunc(PassiveMouseMove);
Initial();
glutMainLoop();
return 0;
}
橡皮筋技术画折线和矩形
最新推荐文章于 2019-09-18 12:22:00 发布
该博客介绍了如何使用OpenGL库在C++中实现橡皮筋技术,用户可以通过鼠标点击画出折线和矩形。通过GLUT库处理鼠标事件,动态更新图形,并提供了完整代码示例。
摘要由CSDN通过智能技术生成