用SDL2写一个绘图工具
时间: 2024-05-06 07:17:01 浏览: 14
好的,以下是一个使用SDL2编写的简单的绘图工具示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <SDL2/SDL.h>
#define SCREEN_WIDTH 640
#define SCREEN_HEIGHT 480
// 颜色定义
const SDL_Color WHITE = {255, 255, 255, 255};
const SDL_Color BLACK = {0, 0, 0, 255};
const SDL_Color RED = {255, 0, 0, 255};
const SDL_Color GREEN = {0, 255, 0, 255};
const SDL_Color BLUE = {0, 0, 255, 255};
// 工具函数
void put_pixel(SDL_Surface* surface, int x, int y, SDL_Color color) {
Uint32* pixels = (Uint32*)surface->pixels;
int index = y * surface->w + x;
pixels[index] = SDL_MapRGBA(surface->format, color.r, color.g, color.b, color.a);
}
void draw_line(SDL_Surface* surface, int x1, int y1, int x2, int y2, SDL_Color color) {
int dx = abs(x2 - x1);
int dy = abs(y2 - y1);
int sx = (x1 < x2) ? 1 : -1;
int sy = (y1 < y2) ? 1 : -1;
int err = dx - dy;
int x = x1;
int y = y1;
while (1) {
put_pixel(surface, x, y, color);
if (x == x2 && y == y2) {
break;
}
int e2 = 2 * err;
if (e2 > -dy) {
err -= dy;
x += sx;
}
if (e2 < dx) {
err += dx;
y += sy;
}
}
}
void draw_rect(SDL_Surface* surface, int x, int y, int w, int h, SDL_Color color) {
draw_line(surface, x, y, x + w, y, color);
draw_line(surface, x, y, x, y + h, color);
draw_line(surface, x + w, y, x + w, y + h, color);
draw_line(surface, x, y + h, x + w, y + h, color);
}
int main(int argc, char* argv[]) {
SDL_Window* window = NULL;
SDL_Surface* surface = NULL;
// 初始化SDL
if (SDL_Init(SDL_INIT_VIDEO) < 0) {
printf("SDL初始化失败: %s\n", SDL_GetError());
return 1;
}
// 创建窗口
window = SDL_CreateWindow("绘图工具",
SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
SCREEN_WIDTH,
SCREEN_HEIGHT,
SDL_WINDOW_SHOWN);
if (window == NULL) {
printf("创建窗口失败: %s\n", SDL_GetError());
return 1;
}
// 创建渲染表面
surface = SDL_GetWindowSurface(window);
if (surface == NULL) {
printf("创建表面失败: %s\n", SDL_GetError());
return 1;
}
// 绘制背景
SDL_FillRect(surface, NULL, SDL_MapRGBA(surface->format, 255, 255, 255, 255));
// 绘制一个矩形
draw_rect(surface, 100, 100, 200, 150, BLUE);
// 更新表面
SDL_UpdateWindowSurface(window);
// 等待事件
SDL_Event event;
int quit = 0;
while (!quit) {
while (SDL_PollEvent(&event)) {
switch (event.type) {
case SDL_QUIT:
quit = 1;
break;
}
}
}
// 清理并退出
SDL_FreeSurface(surface);
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}
```
这个绘图工具支持绘制直线和矩形,可以在这个基础上添加更多的绘图功能。