如何用 DevC++ 实现动态爱心动画效果 C++ 图形编程教程
时间: 2025-06-29 11:04:52 浏览: 11
### DevC++ 动态爱心动画教程
#### 使用 `graphics.h` 库创建动态爱心动画
为了在 DevC++ 中实现动态爱心动画,可以利用 `graphics.h` 库来处理图形操作。下面是一个完整的例子,展示了如何通过该库绘制并使爱心形状逐渐显现。
```cpp
#include <iostream>
#include <conio.h> // For _kbhit()
#include <dos.h> // For delay()
#include <graphics.h> // Graphics library functions
using namespace std;
void drawHeart(int x, int y, int size);
int main() {
int gd = DETECT, gm;
initgraph(&gd, &gm, NULL); // Initialize graphics mode
setbkcolor(WHITE);
cleardevice();
for (int i = 0; i <= 100; ++i) {
setfillstyle(SOLID_FILL, RED);
bar(0, 0, getmaxx(), getmaxy());
setcolor(BLACK);
drawHeart(getmaxx()/2, getmaxy()/2, i * 5);
delay(50); // Delay between frames
if (_kbhit()) break; // Exit loop on key press
}
getch(); // Wait until a key is pressed before closing the window
closegraph(); // Close the graph device and restore screen to text mode
return 0;
}
// Function to plot points around an ellipse centered at cx,cy with radii rx,ry.
void putEllipsePixel(int cx, int cy, double t, int rx, int ry){
int px=(int)(cx+rx*cos(t));
int py=(int)(cy-ry*sin(t)); // Note negative sign because positive Y axis goes down in computer screens
putpixel(px,py,BLUE);
}
// Draw heart shape using parametric equations of two ellipses joined together.
void drawHeart(int x, int y, int size){
const double PI=3.14159265358979323846;
for(double angle=-PI/2;angle<=3*PI/2;angle+=PI/18){ // Loop over angles from -pi/2 to pi*(3/2)
int topX=x+(size/2)*cos(angle)*(sin(abs(cos(angle)))+abs(sin(angle))); // Top half equation
int topY=y-abs(sin(angle)));
putpixel(topX,topY,YELLOW);
int bottomX=x-size*cos(angle)/sqrt(2)+(size/2)*pow((double)sin(angle),2)/(sqrt(2)); // Bottom part equation
int bottomY=y+size*sin(angle)/sqrt(2)-(size/2)*pow((double)sin(angle),2)/(sqrt(2));
putpixel(bottomX,bottomY,GREEN);
}
}
```
此程序首先初始化图形模式,并设置背景颜色为白色。接着在一个循环里逐步增加爱心大小直到完全显示出来,在每次迭代之间加入短暂延时以形成动画效果。当按下任意键时会提前结束动画播放[^1]。
需要注意的是,上述代码依赖于特定平台下的图形库 (`graphics.h`) ,这可能不是跨平台的最佳实践方式。对于更复杂的项目或希望保持良好的移植性的开发者来说,考虑采用其他现代GUI框架可能是更好的选择[^2]。
阅读全文
相关推荐



















