#include <stdlib.h>
#include <SDL/SDL.h>
/* 无字序无关的颜色掩码,用于跨平台 */
#if SDL_BYTEORDER != SDL_BIG_ENDIAN
Uint32 g_rmask = 0x00ff0000;
Uint32 g_gmask = 0x0000ff00;
Uint32 g_bmask = 0x000000ff;
Uint32 g_amask = 0x00000000;
#else
Uint32 g_rmask = 0x000000ff;
Uint32 g_gmask = 0x0000ff00;
Uint32 g_bmask = 0x00ff0000;
Uint32 g_amask = 0xff000000;
#endif
/* 程序的分辨率和色深 */
const int SCREEN_W = 640;
const int SCREEN_H = 480;
const int SCREEN_BPP = 32;
/* 用于组合颜色分量成一个颜色值 */
#define XRGB(r, g, b) SDL_MapRGB(screen->format, r, g, b)
/* 全局屏幕表面 */
SDL_Surface *screen = NULL;
void DrawPixel(SDL_Surface *, int, int, Uint32);
void PutPixel(int, int, Uint32);
/* 向表面上的(x, y)画一个颜色为color的点 */
void DrawPixel(SDL_Surface *surface, int x, int y, Uint32 color)
{
int bpp = surface->format->BytesPerPixel;
SDL_Surface *pixel = SDL_CreateRGBSurface(SDL_HWSURFACE, 1, 1, bpp << 3, g_rmask,
g_gmask, g_bmask, g_amask);
SDL_Rect rect;
rect.x = x;
rect.y = y;
rect.w = rect.h = 1;
SDL_FillRect(pixel, NULL, color);
SDL_BlitSurface(pixel, NULL, surface, &rect);
SDL_FreeSurface(pixel);
}
/* 将DrawPixel封装成类似于TC的 putpixel 函数,即直接向屏幕指定位置画点 */
void PutPixel(int x, int y, Uint32 color)
{
DrawPixel(screen, x, y, color);
}
/* 测试函数 */
int main (int argc, char *argv[])
{
SDL_Event event;
int done = 0; /* 主循环退出标志 */
/* 初始化 SDL */
if (SDL_Init (SDL_INIT_VIDEO) < 0)
{
exit (1);
}
atexit (SDL_Quit);
/* 设置图形模式 */
screen = SDL_SetVideoMode (SCREEN_W, SCREEN_H, SCREEN_BPP, SDL_HWSURFACE | SDL_DOUBLEBUF);
if (screen == NULL)
{
exit (2);
}
SDL_WM_SetCaption ("SDL Put Pixel", NULL); /* 设置窗口标题 */
while (!done) /* 主循环 */
{
/* 检查事件 */
while (SDL_PollEvent (&event))
{
switch (event.type)
{
case SDL_KEYDOWN: /* 按任意键退出 */
done = 1;
break;
case SDL_QUIT:
done = 1;
break;
default:break;
}
}
/* 在屏幕上的随机位置画白色的点 */
PutPixel(rand() & 511, rand() & 511, XRGB(255, 255, 255));
/* 将后台页显示到前台页 */
SDL_Flip (screen);
/* 延时 */
SDL_Delay (1);
}
return 0;
}
/* 初始化 SDL */
if (SDL_Init (SDL_INIT_VIDEO) < 0)
{
printf("SDL_Init is failed"); //加了一条打印
exit (1);
}
编译通过了。
调试时,初始化的过程出现了一个问题。
我加了这条打印。发现是SDL初始化过程失败了。
(在编译过程中,我确实加了-lSDL的参数)
。。。
/* 初始化 SDL */
if (SDL_Init (SDL_INIT_VIDEO) < 0)
{
printf("could not initialize SDL: %s\n",SDL_GetError()); //修改一次提示信息
exit (1);
}
。。。。
root\> gcc main.c -o main -lSDL
root\> ./main
root\> could not initialize SDL: No available video device
初始化失败,不能找到可用的视频设备。
我又从google找了一个最简单初始化SDL的例子来调试SDL初始化过程,结果是仍然不能初始化。那么这个视频设备到底是指什么呢?是不是我的显示器。为何我在本地不能初始化呢.
测试初始化SDL的例子附下:
#include <SDL/SDL.h>
#include <stdio.h>
int main() {
printf("Initializing SDL.\n");
/* Initialize defaults, Video and Audio */
if((SDL_Init(SDL_INIT_VIDEO|SDL_INIT_AUDIO)==-1)) {
printf("Could not initialize SDL: %s.\n", SDL_GetError());
exit(-1);
}
printf("SDL initialized.\n");
printf("Quiting SDL.\n");
/* Shutdown all subsystems */
SDL_Quit();
printf("Quiting....\n");
exit(0);
}