Delphi中OpenGL绘图,改变窗体大小出错
代码如下,每次改变窗体大小的时候,绘出的图形就乱了,请大神指教怎么回事,unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, OPENGL;
type
TfrmMain = class(TForm)
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormPaint(Sender: TObject);
procedure FormResize(Sender: TObject);
private
{ Private declarations }
hrc:HGLRC;
w,h:glFloat;
Sphere:GLUquadricObj;
public
{ Public declarations }
procedure MyDraw;
end;
var
frmMain: TfrmMain;
implementation
{$R *.dfm}
procedure TfrmMain.FormCreate(Sender: TObject);
var
pfd:TPixelFormatDescriptor; //设置描述表
PixelFormat:Integer;
begin
ControlStyle:=ControlStyle+[csOpaque];
FillChar(pfd,sizeof(pfd),0); //
with pfd do
begin
nSize:=sizeof(TPixelFormatDescriptor);
nVersion:=1;
dwFlags:=PFD_DRAW_TO_WINDOW or PFD_SUPPORT_GDI or PFD_SUPPORT_OPENGL or PFD_DOUBLEBUFFER;
iPixelType:=PFD_TYPE_RGBA;
cColorBits:=24;
cDepthBits:=32;
iLayerType:=PFD_MAIN_PLANE;
end;
PixelFormat:=ChoosePixelFormat(Canvas.Handle,@pfd);
SetPixelFormat(Canvas.Handle,PixelFormat,@pfd);
hrc:=wglCreateContext(Canvas.Handle);
w:=ClientWidth;
h:=ClientHeight;
end;
procedure TfrmMain.FormDestroy(Sender: TObject);
begin
wglMakeCurrent(Canvas.Handle,HRC);
wglDeleteContext(hRc);
ReleaseDC(Handle,Canvas.Handle);
end;
procedure TfrmMain.FormPaint(Sender: TObject);
begin
wglMakeCurrent(Canvas.Handle,hrc);
MyDraw;
end;
procedure TfrmMain.FormResize(Sender: TObject);
begin
glMatrixMode(GL_PROJECTION);
glLoadIdentity;
glFrustum(-1.0,1.0,-1.0,1.0,3.0,7.0);
glViewport(0,0,ClientWidth,ClientHeight);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
MyDraw;
end;
procedure TfrmMain.MyDraw;
begin
glClearColor(0.8,1,1,1);
glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT);
glLineWidth(3.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glRotatef(45,0,0,1);
glColor3f(1.0,0.0,0.0); //画红色的x轴
glBegin(GL_LINES);
glVertex3f(0.0, 0.0, 0.0);
glVertex3f(1.0, 0.0, 0.0);
glEnd();
glColor3f(0.0,1.0,0.0); //画绿色的y轴
glBegin(GL_LINES);
glVertex3f(0.0, 0.0, 0.0);
glVertex3f(0.0, 1.0, 0.0);
glEnd();
glColor3f(0.0,0.0,1.0); //画蓝色的z轴
glBegin(GL_LINES);
glVertex3f(0.0, 0.0, 0.0);
glVertex3f(0.0, 0.0, 1.0);
glEnd();
glFlush;
SwapBuffers(Canvas.handle);
end;
end.