#include <stdio.h>
#include <unistd.h>
#include <directfb/directfb.h>
static IDirectFB *dfb = NULL;
static IDirectFBSurface *primary = NULL;
static IDirectFBSurface *tux = NULL;
static int screen_width = 0;
static int screen_height = 0;
//全局变量
static IDirectFBInputDevice *keyboard = NULL;
int main (int argc, char **argv)
{
DFBSurfaceDescription dsc;
IDirectFBImageProvider *provider;
DFBInputDeviceKeyState escape = DIKS_UP;//先声明一个DFBInputDeviceKeyState枚举变量,
//并将其值定为DIKS_UP,即默认没有按下
int sprite_x, sprite_y, max_x, max_y;//定义四个整形值,其中max_x, max_y用于记录前面坐标允许的最大值,
//sprite_x, sprite_y用于记录图片左上角的坐标值,
//sprite_x在[0, max_x],sprite_y在[0, max_y]范围内
DirectFBInit (&argc, &argv);
DirectFBCreate (&dfb);
dfb->SetCooperativeLevel (dfb, DFSCL_FULLSCREEN);
dsc.flags = DSDESC_CAPS;
dsc.caps = DSCAPS_PRIMARY | DSCAPS_FLIPPING;
dfb->CreateSurface( dfb, &dsc, &primary );
primary->GetSize (primary, &screen_width, &screen_height);
dfb->GetInputDevice (dfb, DIDID_KEYBOARD, &keyboard);
dfb->CreateImageProvider (dfb, "./my.jpg", &provider);
provider->GetSurfaceDescription (provider, &dsc);
dfb->CreateSurface (dfb, &dsc, &tux);//创建一个平面tux,此平面的大小即为图片的大小,信息记录在dsc中
provider->RenderTo (provider, tux, NULL);//将图片Render到tux上,而图片与tux大小一致,则即便使用了NULL,也不会有缩放发生
provider->Release (provider);
//设定4个int变量的值,以保证图片显示在屏幕正中心
max_x = screen_width - dsc.width;
max_y = screen_height - dsc.height;
sprite_x = (screen_width - dsc.width) / 2;
sprite_y = (screen_height - dsc.height) / 2;
DFBInputDeviceKeyState state;
//primary->SetColor(primary, 0x0, 0x0, 0x0, 0xff);
//primary->FillRectangle(primary, 0, 0, screen_width, screen_height);
while (escape == DIKS_UP){
//将tux显示在primary上面
primary->FillRectangle (primary, 0, 0, screen_width, screen_height);
primary->Blit (primary, tux, NULL, sprite_x, sprite_y);
primary->Flip (primary, NULL, DSFLIP_WAITFORSYNC);
//开始图片移动策略,如果想改变移动速度,可调整步进值
keyboard->GetKeyState (keyboard, DIKI_LEFT, &state);
if (state == DIKS_DOWN){
printf("DIKI_LEFT-----------------/n");
sprite_x--;
}
keyboard->GetKeyState (keyboard, DIKI_RIGHT, &state);
if (state == DIKS_DOWN){
printf("DIKI_RIGHT-----------------/n");
sprite_x++;
}
keyboard->GetKeyState (keyboard, DIKI_UP, &state);
if (state == DIKS_DOWN){
printf("DIKI_UP-----------------/n");
sprite_y--;
}
keyboard->GetKeyState (keyboard, DIKI_DOWN, &state);
if (state == DIKS_DOWN){
printf("DIKI_DOWN-----------------/n");
sprite_y++;
}
//开始定义策略使图片始终在屏幕范围内
if (sprite_x < 0)
sprite_x = 0;
else if (sprite_x > max_x)
sprite_x = max_x;
if (sprite_y < 0)
sprite_y = 0;
else if (sprite_y > max_y)
sprite_y = max_y;
keyboard->GetKeyState (keyboard, DIKI_ESCAPE, &escape);//检查DIKI_ESCAPE状态,为下一次循环做准备
//sleep(1);
}
//由小到大的释放资源
keyboard->Release (keyboard);
tux->Release (tux);
primary->Release (primary);
dfb->Release (dfb);
return 0;
}