SDL小作业在屏幕上显示BITMAP

439

运行结果

SDL2Hello!

代码

#include <iostream>
#include "SDL.h"
const int SCREEN_WIDTH = 141;
const int SCREEN_HEIGHT = 135;
bool initWindow();

bool loadMedia();

bool deallocate();

SDL_Window* window;
SDL_Surface* screenSurface;
SDL_Surface* media;
int main(int argc, char* argv[])
{
	if (!initWindow())
	{
		printf("Failed to initialize!\n");
	}
	else
	{
		if (!loadMedia())
		{
			printf("Failed to load the media!\n");
		}
		else
		{
			SDL_BlitSurface(media, NULL, screenSurface, NULL);
			SDL_UpdateWindowSurface(window);
			SDL_Delay(5000);
		}
	}
	deallocate();
    return 0;
}

bool initWindow() {
    bool flag = true;
	if (SDL_Init(SDL_INIT_VIDEO) < 0)
	{
		flag = false;
		printf("Init Failed:%s", SDL_GetError());
	}
	else
	{
		window = SDL_CreateWindow("SDLSample", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
		if (window ==NULL)
		{
			flag = false;
			printf("windowcreate Failed:%s", SDL_GetError());
		}
		else
		{
			screenSurface = SDL_GetWindowSurface(window);
		}
	}
	return flag;
}

bool loadMedia() {
	bool flag = true;
	media = SDL_LoadBMP("D:/Code/CppCode/SDLgame/SDLgame/bitmap3.bmp");
	if (media==NULL)
	{
		flag = false;
		printf("Init Failed:%s", SDL_GetError());
		return flag;
	}
	return flag;
}

bool deallocate() {
	SDL_FreeSurface(media);
	media = NULL;

	SDL_DestroyWindow(window);
	window = NULL;

	SDL_Quit();
	return true;
}

TIPS

SDL_BlitSurface()
函数功能:将SDL_Surface A复制到B表面

int SDL_BlitSurface(SDL_Surface*    src,
                    const SDL_Rect* srcrect,
                    SDL_Surface*    dst,
                    SDL_Rect*       dstrect)

SDL_UpdateWindowSurface()
函数功能:更新Windows上的surface

SDL_GetWindowSurface()
获取窗口表面,获取后可在窗口绘图。