在C語言中繪制折線圖通常需要使用圖形庫,例如OpenGL或者SDL。下面是一個(gè)使用SDL庫繪制簡單折線圖的示例代碼:
#include <SDL2/SDL.h>
#define WIDTH 800
#define HEIGHT 600
void drawLine(SDL_Renderer *renderer, int x1, int y1, int x2, int y2) {
SDL_RenderDrawLine(renderer, x1, HEIGHT - y1, x2, HEIGHT - y2); // SDL坐標(biāo)原點(diǎn)在左上角,y軸朝下,需要轉(zhuǎn)換坐標(biāo)
}
int main() {
if (SDL_Init(SDL_INIT_VIDEO) != 0) {
SDL_Log("Unable to initialize SDL: %s", SDL_GetError());
return 1;
}
SDL_Window *window = SDL_CreateWindow("Line Chart", SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED, WIDTH, HEIGHT, 0);
if (window == NULL) {
SDL_Log("Unable to create window: %s", SDL_GetError());
return 1;
}
SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
if (renderer == NULL) {
SDL_Log("Unable to create renderer: %s", SDL_GetError());
return 1;
}
SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255); // 設(shè)置畫布顏色為白色
SDL_RenderClear(renderer);
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255); // 設(shè)置畫筆顏色為黑色
drawLine(renderer, 100, 100, 200, 200); // 繪制折線
SDL_RenderPresent(renderer);
SDL_Delay(3000); // 延遲3秒
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}
這段代碼使用SDL庫繪制了一個(gè)簡單的折線圖,包括設(shè)置窗口大小,創(chuàng)建窗口和渲染器,繪制折線,以及銷毀窗口和渲染器等操作。你可以根據(jù)自己的需求修改繪制的折線圖的坐標(biāo)和樣式。