SDL2 中使用多線程繪圖

   SDL的中文資料比較少,推薦一個英文的網站裏面講的非常詳細  點擊打開鏈接解決了我不少的疑惑。

  最近在移植ucGUI到Android上,ucGUI的windows Demo中可以實現在一個線程中繪圖,在另一個線程中刷新。在Android中使用ucGUI也是可以實現的用SDL 當畫布,在子線程中繪畫 ,在主線程中刷新。代碼如下:

/*This source code copyrighted by Lazy Foo' Productions (2004-2013)
 and may not be redistributed without written permission.*/

//Using SDL and standard IO
#include <SDL.h>
#include <stdio.h>
#include <stdbool.h>
#include "GUI.h"
//Screen dimension constants

extern int SCREEN_WIDTH;
extern int SCREEN_HEIGHT;
//Starts up SDL and creates window


//Loads media
bool loadMedia();//加載圖片

//Frees media and shuts down SDL
void close();

//The window we'll be rendering to
extern SDL_Window* g_screen_window;

//The surface contained by the window
extern SDL_Surface* g_screen_surface;

//The image we will load and show on the screen
SDL_Surface* gXOut = NULL;

bool loadMedia() {
	//Loading success flag
	bool success = true;

	//Load splash image
	gXOut = SDL_LoadBMP("x.bmp");
	if (gXOut == NULL) {
		SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
				"Unable to load image %s! SDL Error: %s\n",
				"03_event_driven_programming/x.bmp", SDL_GetError());
		success = false;
	}

	return success;
}

void close() {
	//Deallocate surface
	SDL_FreeSurface(gXOut);
	gXOut = NULL;

	//Destroy window
	SDL_DestroyWindow(g_screen_window);
	g_screen_window = NULL;

	//Quit SDL subsystems
	SDL_Quit();
}
void Thread1(void *pdata) {

	MainTask(0);//子線程中的繪畫函數都在這裏

	SDL_Log("Thread runing");
}
int SDL_main(int argc, char* args[]) {

	//Start up SDL and create window
	GUI_Init();//初始化windows 以及surface

	//Load media
	if (!loadMedia()) {
		printf("Failed to load media!\n");
	} else {
		//Main loop flag
		bool quit = false;

		//Event handler
		SDL_Event e;

		SDL_Thread *thread = SDL_CreateThread(Thread1, "TestThread",
				(void *) NULL);

		//While application is running

		while (!quit) {
			//Handle events on queue
			while (SDL_PollEvent(&e) != 0) {
				//User requests quit
				if (e.type == SDL_QUIT) {
					quit = true;
				}
				if (e.type == SDL_FINGERUP) {
					quit = true;
				}
			}

			//Apply the image

			//Update the surface
			SDL_UpdateWindowSurface(g_screen_window);
			SDL_Log("Invalidate");
		}
	}

	//Free resources and close SDL
	close();

	return 0;
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章