绘制椭圆的函数与绘制圆非常类似,只是参数不一样,所有椭圆绘制函数如下:
//椭圆左上角坐标(left, top),右下角坐标(right, bottom)
//画无填充椭圆
void ellipse( int left, int top, int right, int bottom );
//画无边框填充椭圆
void solidellipse( int left, int top, int right, int bottom );
//画填充椭圆
void fillellipse( int left, int top, int right, int bottom );
//清空椭圆
void clearellipse( int left, int top, int right, int bottom );
只要给出左上角和右下角标明的一个矩形,就按给定矩形绘制一个内切的椭圆。
函数ellipse(50,50,250,150);绘制效果如下:
红色矩形就是用同样的参数绘制的,椭圆刚好是一个内切椭圆
所以聪明的读者已经发现了,其实椭圆函数也可以绘制圆,只要给一个正方形作为外切矩形就可以了,所以绘制圆有两种方式。按给的参数选择方便的方式就可以了。
与所有有面积的图形一样,椭圆也提供四种绘制方式,在此不再赘述。
正好今天六一儿童节,那我们就来做一个彩色气球飘浮飞天的动画演示椭圆形的绘制吧。代码如下:
// Ellipse.cpp : 定义控制台应用程序的入口点。
//
#include "../import/include/CGBoard.h"
#include "math.h"
#ifdef _DEBUG
#pragma comment(lib,"../import/lib/SimpleCG_MDd.lib")
#else
#pragma comment(lib,"../import/lib/SimpleCG_MD.lib")
#endif
#define BALLOON_CNT 8
int g_nWidth = 600; //画面宽度
int g_nHeight= 800; //画面高度
#define ADDCOLOR(x,y) ((x+y)>255?255:(x+y))
//绘制气球
void DrawBalloon( int nX, int nY, int nWidth, COLORREF nColor )
{
int nLine=1;
int r=ADDCOLOR(GetRValue(nColor),50);
int g=ADDCOLOR(GetGValue(nColor),50);
int b=ADDCOLOR(GetBValue(nColor),50);
if( rand()%10==0)
{
nLine=-1;
}
setlinewidth(2);
setfillcolor(nColor);
setlinecolor(0);
_fillrectangle(nX + nWidth/2 - 7,nY + nWidth*1.2 - 10,nX + nWidth/2 + 7, nY + nWidth*1.2+10);
_fillellipse(nX,nY,nX + nWidth, nY + nWidth*1.2);
setfillcolor(RGB(r,g,b));
_solidcircle(nX + 2*nWidth/3,nY + nWidth*0.2,nWidth/15);
_curveline(nX + nWidth/2,nY + nWidth*1.2,nX + nWidth/2,nY + nWidth*1.8,nLine*nWidth*4/150);
_curveline(nX + nWidth/2,nY + nWidth*1.8,nX + nWidth/2,nY + nWidth*2.4,-nLine*nWidth*4/150);
setlinewidth(nWidth/15);
setlinecolor(RGB(r,g,b));
_curveline(nX + 11*nWidth/15,nY + nWidth/3,nX + 13*nWidth/15,nY + 2*nWidth/3,-6);
}
void DrawProcess()
{
POINT pt[BALLOON_CNT];
int nWidth[BALLOON_CNT];
COLORREF nColor[BALLOON_CNT];
int nSpeed[BALLOON_CNT];
int i=0;
bool bIsRunning = true;
float fAngle=0;
srand(GetTickCount());
for( i=0; i<BALLOON_CNT; ++i)
{
pt[i].x = rand()%g_nWidth;
pt[i].y = g_nHeight;
nWidth[i] = 50+rand()%150;
nColor[i] = RGB(rand()%255,rand()%255,rand()%255);
nSpeed[i] = 1+rand()%8;
}
while(bIsRunning)
{
setfillcolor(RGB(255,255,255));
_solidrectangle(0,0,g_nWidth,g_nHeight);
for( i=0; i<BALLOON_CNT; ++i)
{
DrawBalloon( pt[i].x, pt[i].y, nWidth[i], nColor[i] );
pt[i].y -= nSpeed[i];
if(pt[i].y<-nWidth[i]*2.4)
{
pt[i].x = rand()%g_nWidth;
pt[i].y = g_nHeight;
nWidth[i] = 50+rand()%150;
nColor[i] = RGB(rand()%255,rand()%255,rand()%255);
nSpeed[i] = 1+rand()%8;
}
}
ReflushWindow();
Sleep(100);
}
}
int _tmain(int argc, _TCHAR* argv[])
{
//初始化
if( !ShowingBoard(g_nWidth,g_nHeight, DrawProcess))
return 1;
//关闭图库
CloseBoard();
return 0;
}
代码使用了_fillrectangle加下划线是为了不进行屏幕刷新,统一用ReflushWindow刷新,避免闪烁,后续的版本可能会更改这种方式,目前还是alpha版本。
运行效果如图:
因为椭圆和矩形其实差不多,就是形状不一样而以,就不编写太多示例代码了。大家可以自行尝试绘制其他更富创造性的图片。
在此谨以此代码祝大家节日快乐,永葆童心!