我已经开始研究SDL了。我有一个基本程序的麻烦,每次我编译它我没有错误,但程序是完全空白的。 Build Succeeds,应用程序图标弹出到我的Dock中,但在没有窗口的情况下保持打开状态5秒。代码如下:
//
// main.cpp
// HelloSDL
//
// Created by Liam Tan
// Copyright 2014 Liam Tan. All rights reserved.
//
#include <stdlib.h>
#include <SDL/SDL.h>
#include <string>
#include <iostream>
const int SCREEN_WIDTH = 640;
const int SCREEN_HEIGHT = 480;
const int SCREEN_BPP = 32;
//Declares surfaces
SDL_Surface* message = NULL;
SDL_Surface* background = NULL;
SDL_Surface* screen = NULL;
SDL_Surface *load_image( std::string filename) {
//declaration
SDL_Surface* loadedImage = NULL;
SDL_Surface* optimizedImage = NULL;
//takes arguement and loads that BMP
loadedImage = SDL_LoadBMP(filename.c_str() );
//Checks, swaps opti with loaded then frees loaded
if (loadedImage!= NULL) {
optimizedImage = SDL_DisplayFormat (loadedImage);
SDL_FreeSurface(loadedImage);
}
return optimizedImage;
}
void apply_surface(int x, int y, SDL_Surface* source, SDL_Surface* destination) {
//temporary rectangle to hold offsets
SDL_Rect offset;
offset.x = x;
offset.y = y;
SDL_BlitSurface(source, NULL, destination, NULL);
}
int SDL_main (int argc, char **argv) {
const std::string errorMsg = "failed to initialize. ";
//Initialise
if( SDL_Init(SDL_INIT_EVERYTHING) == -1 ) {
std::cout << "SDL " << errorMsg << std::endl;
SDL_GetError();
return 1;
}
screen = SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, SDL_SWSURFACE);
if (screen == NULL) {
std::cout << "Video mode " << errorMsg << std::endl;
SDL_GetError();
return 1;
}
SDL_WM_SetCaption("Programming", NULL);
//loads message
message = load_image("textures/hello.bmp");
//loads background
background = load_image("textures/background.bmp");
//blits 4 times!
apply_surface(0,0,background,screen);
apply_surface( 320, 0, background, screen );
apply_surface( 0, 240, background, screen );
apply_surface( 320, 240, background, screen );
SDL_Delay(5000);
SDL_Quit();
return 0;
}
我正在使用Xcode 5和SDL 1.2。
答案 0 :(得分:0)
我在您的代码中看到了一些问题。它们可能不是全部错误。
1)当您对图像进行blit时,它不会直接进入屏幕。它会保留在缓冲区中,直到您拨打SDL_Flip(screen);
所以最后几行应该是那样的
...
apply_surface( 320, 240, background, screen );
SDL_Flip(screen);//Display the results of the blits
SDL_Delay(5000);
SDL_Quit();
return 0;
2)当您对图像进行blit时,不要使用Rect offset
。它将始终显示在0,0位置。
//temporary rectangle to hold offsets
SDL_Rect offset;
offset.x = x;
offset.y = y;
SDL_BlitSurface(source, NULL, destination, NULL);
3)你永远不会释放你加载的图像。你需要在SDL_Quit之前添加一些SDL_FreeSurface(...);
。
4)您加载但从不使用hello.bmp
另外,我不明白为什么你将表面声明为全局。但也许你有充分的理由。
您也可以尝试将SDL_Delay(5000);
替换为
bool done = false;
while (!done)//we wait until done == true
{
SDL_Event event;
while (SDL_WaitEvent(&event))//we get all the events
{
switch (event.type) //we look what type of event we received
{
case SDL_QUIT: //We received a quit event
done = true;//we want to exit the loop
break;
}
}
}
因为SDL_Delay告诉您的计算机您的应用程序不需要更新一段时间。