最近陷入了sdl的学习中,发现许多函数sdl库本身并没有提供,所以还需我们自己编写,下面便来分享一下自己编写的几个函数。
首先是绘制线条,说白了就是画点,下面给出代码:
void drawline(SDL_Surface *screen, Uint8 R, Uint8 G, Uint8 B,int x,int y,int xx,int yy){
int x1,y1;
for(x1=x,y1=y;x1<=xx && y1<=yy;x1++,y1++){
DrawPixel(screen,100,100,100,x1,y1);
}
}
然后是绘制矩形,那也是在绘制线条的基础上:
void drawrect(SDL_Surface *screen, Uint8 R, Uint8 G, Uint8 B,int x,int y,int width,int heigth){
int x1,y1;
for(x1=x,y1=y;x1<x+width;x1++){
DrawPixel(screen,100,100,100,x1,y1);
}
for(x1=x+width,y1=y;y1<y+heigth;y1++){
DrawPixel(screen,100,100,100,x1,y1);
}
for(x1=x,y1=y+heigth;x1<x+width;x1++){
DrawPixel(screen,100,100,100,x1,y1);
}
for( x1=x,y1=y;y1<y+heigth;y1++){
DrawPixel(screen,100,100,100,x1,y1);
}
}
上面代码中的DrawPixel函数就是来画点的,也就是绘制像素。下面看下代码:
void DrawPixel(SDL_Surface *screen, Uint8 R, Uint8 G, Uint8 B,int x,int y)
{
Uint32 color = SDL_MapRGB(screen->format, R, G, B);
if ( SDL_MUSTLOCK(screen) ) {
if ( SDL_LockSurface(screen) < 0 ) {
return;
}
}
Uint32 *bufp;
bufp = (Uint32 *)screen->pixels + y*screen->pitch/4 + x;
*bufp = color;
if ( SDL_MUSTLOCK(screen) ) {
SDL_UnlockSurface(screen);
}
SDL_Delay(5);
// SDL_Flip(screen);
SDL_UpdateRect(screen, x, y, 1, 1);
}
上面加了SDL_Delay,也就是延迟5秒,所以你能看到绘制过程,去掉的话绘制的最终结果便会直接显示了。
下面给出个例子:
#include <iostream>
#include "SDL/SDL.h"
using namespace std;
SDL_Surface* screen;
int main(int argc, char *argv[]) {
SDL_Init(SDL_INIT_EVERYTHING);
atexit(SDL_Quit);
screen=SDL_SetVideoMode(640,480,32,SDL_SWSURFACE);
drawline(screen,200,200,200,100,100,200,280);
// SDL_Flip(screen);
while(1){
SDL_Event e;
while(SDL_PollEvent(&e)){
switch(e.type){
case SDL_KEYDOWN:
if(e.key.keysym.sym==SDLK_ESCAPE){
return 0;
}
break;
case SDL_QUIT:
return 0;
}
}
}
return 0;
}
本文有什么不足之处,还望大家多多指正。