`
kevin_hust
  • 浏览: 12275 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
最近访客 更多访客>>
文章分类
社区版块
存档分类
最新评论

SDL编程二(视频)

阅读更多
1.初始SDL视频库

if (SDL_Init(SDL_INIT_VIDEO)<0)
{
   printf("can not init SDL.\n");
   exit(1);
}

2.屏幕像素的操作

下面的函数是在屏幕的(x,y)坐标位置,绘制一个颜色为R,G,B的像素点。

void DrawPixel(SDL_Surface *screen, int x, int y, Uint8 R, Uint8 G, Uint8 B)
{
Uint32 color = SDL_MapRGB(screen->format, R, G, B);

if (SDL_MUSTLOCK(screen))//锁屏幕数据
{
   if (SDL_LockSurface(screen) < 0)
   {
    return;
   }
}

switch (screen->format->BytesPerPixel)//屏幕像素颜色的位深
{
case 1:
   {
    Uint8 *bufp;
    bufp = (Uint8 *)screen->pixels + y*screen->pitch + x;
    *bufp = color;
   }
   break;
case 2:
   {
    Uint16 *bufp;
    bufp = (Uint16 *)screen->pixels + y*screen->pitch/2 + x;
    *bufp = color;
   }
   break;
case 3:
   {
    Uint8 *bufp;
    bufp = (Uint8 *)screen->pixels + y*screen->pitch + x;
    *(bufp+screen->format->Rshift/8) = R;
    *(bufp+screen->format->Gshift/8) = G;
    *(bufp+screen->format->Bshift/8) = B;
   }
   break;
case 4:
   {
    Uint32 *bufp;
    bufp = (Uint32 *)screen->pixels + y*screen->pitch/4 + x;
    *bufp = color;
   }
   break;
}

if (SDL_MUSTLOCK(screen))//操作之后对屏幕数据“开锁”
{
   SDL_UnlockSurface(screen);
}
SDL_UpdateRect(screen, x, y, 1, 1);
}
3.显示bmp图像

SDL只提供了加载bmp图像的函数SDL_LoadBMP,但通过其它SDL扩展库也可以操作JPG、PNG等其它格式的图片。

void ShowBMP(char *file, SDL_Surface *screen, int x, int y)
{
SDL_Surface *image;
SDL_Rect dest;

image = SDL_LoadBMP(file);//加载位图图像文件
if (image == NULL)
{
   printf("cannot load %s: %s\n", file, SDL_GetError());
   return;
}

dest.x = x;//设置显示的位置及大小
dest.y = y;
dest.w = image->w;
dest.h = image->h;
SDL_BlitSurface(image, NULL, screen, &dest);//绘制图像

SDL_UpdateRects(screen, 1, &dest);//更新屏幕

SDL_FreeSurface(image);
}

显示位图示例:

#include <stdlib.h>
#include <stdio.h>
#include "SDL.h"

int main(int argc, char *argv[])
{
if (SDL_Init(SDL_INIT_VIDEO)<0)//初始化SDL视频库
{
   printf("can not init SDL.\n");
   exit(1);
}
printf("successful init SDL.\n");

SDL_Surface *screen;
screen = SDL_SetVideoMode(640, 480, 32, SDL_SWSURFACE);//创建窗口
if (screen == NULL)
   return;

while(1)
{
   ShowBMP("apple.bmp", screen, 0, 0);//显示位图
   SDL_Delay(100);
}
}

该示例没有消息处理,只是循环地显示一幅图像,不能与用户进行交互。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics