SDL2 - 应该返回 True 的函数评估为 False

Posted

技术标签:

【中文标题】SDL2 - 应该返回 True 的函数评估为 False【英文标题】:SDL2 - function supposed to return True evaluates to False 【发布时间】:2019-12-17 15:25:48 【问题描述】:

我正在使用 SDL2,遵循 LazyFoo 的教程。我已经到了加载 TTF 字体部分,而且我似乎遵循了他所做的一切,除了添加两个额外的 TTF_Font 和 SDL_Renderer 参数

bool LTexture::loadFromRenderedText(TTF_Font *&gFont, std::string textureText, SDL_Color textColor, SDL_Renderer *&gRenderer)

    //Get rid of preexisting texture
    free();

    //Render text surface
    SDL_Surface* textSurface = TTF_RenderText_Solid( gFont, textureText.c_str(), textColor );
    if( textSurface == NULL )
    
        printf( "Unable to render text surface! SDL_ttf Error: %s\n", TTF_GetError() );
    
    else
    
        //Create texture from surface pixels
        mTexture = SDL_CreateTextureFromSurface( gRenderer, textSurface );
        if( mTexture == NULL )
        
            printf( "Unable to create texture from rendered text! SDL Error: %s\n", SDL_GetError() );
        
        else
        
            //Get image dimensions
            mWidth = textSurface->w;
            mHeight = textSurface->h;
        

        //Get rid of old surface
        SDL_FreeSurface( textSurface );
    

    return 1;

这是函数,也是它的调用位置:

    gFont = TTF_OpenFont( "Font/comicSans.ttf", 28 );
    if( gFont == NULL )
    
        printf( "Failed to load COMIC_SANS font! SDL_ttf Error: %s\n", TTF_GetError() );
        success = false;
    
    else
    
        //Render text
        SDL_Color textColor =  0, 0, 0 ;
        if( !gTextTexture.loadFromRenderedText(gFont, "Hello I am hot", textColor, gRenderer));
        
            printf( "Failed to render text texture!\n" );
            success = false;
        
    

如果succes 为假,程序会打印“加载媒体失败”

这是我从运行程序得到的输出,注意没有实际的 SDL 或 TTF 错误,只有当loadFromRendereredText 返回 false 时出现的错误,它没有,因为我已将其设置为返回1:

Failed to render text texture!
Failed to load media!

我的文件和 LazyFoo 的文件的唯一实际区别是我的 LTexture 类与主文件位于一个单独的文件中,这就是为什么由于某种原因我不能使用 gFontgRenderer(全局变量) 知道是什么原因造成的吗?

完整代码:

main.cpp:

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

//Using SDL and standard IO
#include <SDL.h>
#include <SDL_image.h>
#include <SDL_ttf.h>
#include <stdio.h>
#include <string>
#include "LTexture.h"

bool init();
bool loadMedia();
void close();


//The window we'll be rendering to
SDL_Window* gWindow = NULL;

SDL_Renderer* gRenderer = NULL;

//The surface contained by the window
SDL_Surface* gScreenSurface = NULL;

TTF_Font *gFont = NULL;

LTexture gTextTexture;

//Screen dimension constants
const int SCREEN_WIDTH = 500;
const int SCREEN_HEIGHT = 500;

int main(int argc, char* args[])

    //Start up SDL and create window
    if( !init() )
    
        printf( "Failed to initialize!\n" );
    
    else
    
        //Load media
        if( !loadMedia() )
        
            printf( "Failed to load media!\n" );
        
        else
        
            //Main loop flag
            bool quit = false;

            //Event handler
            SDL_Event event;

            //While application is running
            while( !quit )
            
                //Handle events on queue
                while( SDL_PollEvent( &event ) != 0 )
                
                    //User requests quit
                    if( event.type == SDL_QUIT )
                    
                        quit = true;
                    
                

                //Clear screen
                SDL_SetRenderDrawColor(gRenderer, 0xFF, 0xFF, 0xFF, 0xFF);
                SDL_RenderClear( gRenderer );

                gTextTexture.render(gRenderer, (SCREEN_WIDTH - gTextTexture.getWidth()) / 2, (SCREEN_HEIGHT - gTextTexture.getHeight()) / 2);
                //Update screen
                SDL_RenderPresent( gRenderer );
            
        
    

    //Free resources and close SDL
    close();

    return 0;



bool init()

    //Initialization flag
    bool success = true;

    //Initialize SDL
    if( SDL_Init( SDL_INIT_VIDEO ) < 0 )
    
        printf( "SDL could not initialize! SDL_Error: %s\n", SDL_GetError() );
        success = false;
    
    else
    
        //Create window
        gWindow = SDL_CreateWindow( "SDL Tutorial", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
        if( gWindow == NULL )
        
            printf( "Window could not be created! SDL Error: %s\n", SDL_GetError() );
            success = false;
        
        else
        
            //Create renderer for window
            gRenderer = SDL_CreateRenderer( gWindow, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
            if( gRenderer == NULL )
            
                printf( "Renderer could not be created! SDL Error: %s\n", SDL_GetError() );
                success = false;
            
            else
            
                //Initialize renderer color
                SDL_SetRenderDrawColor( gRenderer, 0xFF, 0xFF, 0xFF, 0xFF );

                //Initialize PNG loading
                int imgFlags = IMG_INIT_PNG;
                if( !( IMG_Init( imgFlags ) & imgFlags ) )
                
                    printf( "SDL_image could not initialize! SDL_image Error: %s\n", IMG_GetError() );
                    success = false;
                
                //Initialize SDL_ttf
                if( TTF_Init() == -1 )
                
                    printf( "SDL_ttf could not initialize! SDL_ttf Error: %s\n", TTF_GetError() );
                    success = false;
                
            
        
    

    return success;


bool loadMedia()

    //Loading success flag
    bool success = true;

    //Open the font
    gFont = TTF_OpenFont( "Font/comicSans.ttf", 28 );
    if( gFont == NULL )
    
        printf( "Failed to load COMIC_SANS font! SDL_ttf Error: %s\n", TTF_GetError() );
        success = false;
    
    else
    
        //Render text
        SDL_Color textColor =  0, 0, 0 ;
        if( !gTextTexture.loadFromRenderedText(gFont, "Hello I am hot", textColor, gRenderer));
        
            printf( "Failed to render text texture!\n" );
            success = false;
        
    


    return success;


void close()


    //Free loaded images
    gTextTexture.free();

    //Destroy window
    SDL_DestroyRenderer( gRenderer );
    SDL_DestroyWindow( gWindow );
    TTF_CloseFont(gFont);
    gWindow = NULL;
    gRenderer = NULL;
    gFont = NULL;

    //Quit SDL subsystems
    TTF_Quit();
    IMG_Quit();
    SDL_Quit();

LTexture.h:

#ifndef LTEXTURE_INCLUDED
#define LTEXTURE_INCLUDED


#include <SDL.h>
#include <SDL_image.h>
#include <SDL_ttf.h>
#include <stdio.h>
#include <string>

//Texture wrapper class
class LTexture

    public:
        //Initializes variables
        LTexture();

        //Deallocates memory
        ~LTexture();

        //Loads image at specified path
        bool loadFromFile( std::string path, SDL_Renderer *&gRenderer);

        //Loads image from string text
        bool loadFromRenderedText(TTF_Font *&gFont, std::string textureText, SDL_Color textColor, SDL_Renderer *&gRenderer);

        //Deallocates texture
        void free();

        //Set color modulation
        void setColor( Uint8 red, Uint8 green, Uint8 blue );

        //Set blending
        void setBlendMode( SDL_BlendMode blending );

        //Set alpha modulation
        void setAlpha( Uint8 alpha );

        //Renders texture at given point
        void render(SDL_Renderer *&gRenderer, int x, int y, SDL_Rect *clip = NULL, double angle = 0.0, SDL_Point* center = NULL, SDL_RendererFlip flip = SDL_FLIP_NONE );

        //Gets image dimensions
        int getWidth()return mWidth;
        int getHeight()return mHeight;

    private:
        //The actual hardware texture
        SDL_Texture* mTexture;

        //Image dimensions
        int mWidth;
        int mHeight;
;
#endif // LTEXTURE_INCLUDED

LTexture.cpp:

#include "LTexture.h"

LTexture::LTexture()

    mTexture = NULL;
    mWidth = 0;
    mHeight = 0;


LTexture::~LTexture()

    //Deallocate resources
    free();



bool LTexture::loadFromFile(std::string path, SDL_Renderer *&gRenderer)

    free();

    SDL_Texture* newTexture = NULL;

    SDL_Surface *loadedSurface = IMG_Load(path.c_str());
    if(loadedSurface == NULL)
    
        printf("Unable to load image %s! SDL_image Error: %s\n", path.c_str(), IMG_GetError());
    
    else
    
        //Color key image
        SDL_SetColorKey( loadedSurface, SDL_TRUE, SDL_MapRGB( loadedSurface->format, 0, 0xFF, 0xFF ) );

        newTexture = SDL_CreateTextureFromSurface(gRenderer, loadedSurface);
        if(newTexture == NULL)
        
            printf( "Unable to create texture from %s! SDL Error: %s\n", path.c_str(), SDL_GetError() );
        
        else
        
            mWidth = loadedSurface->w;
            mHeight = loadedSurface->h;
        
        SDL_FreeSurface( loadedSurface );
    

    mTexture = newTexture;
    return mTexture != NULL;


bool LTexture::loadFromRenderedText(TTF_Font *&gFont, std::string textureText, SDL_Color textColor, SDL_Renderer *&gRenderer)

    //Get rid of preexisting texture
    free();

    //Render text surface
    SDL_Surface* textSurface = TTF_RenderText_Solid( gFont, textureText.c_str(), textColor );
    if( textSurface == NULL )
    
        printf( "Unable to render text surface! SDL_ttf Error: %s\n", TTF_GetError() );
    
    else
    
        //Create texture from surface pixels
        mTexture = SDL_CreateTextureFromSurface( gRenderer, textSurface );
        if( mTexture == NULL )
        
            printf( "Unable to create texture from rendered text! SDL Error: %s\n", SDL_GetError() );
        
        else
        
            //Get image dimensions
            mWidth = textSurface->w;
            mHeight = textSurface->h;
        

        //Get rid of old surface
        SDL_FreeSurface( textSurface );
    

    return 1;


void LTexture::free()

    if(mTexture != NULL)
        SDL_DestroyTexture(mTexture);
        mTexture = NULL;
        mWidth = 0;
        mHeight = 0;
    


void LTexture::setColor( Uint8 red, Uint8 green, Uint8 blue )

    //Modulate texture
    SDL_SetTextureColorMod( mTexture, red, green, blue );


void LTexture::setBlendMode( SDL_BlendMode blending )

    //Set blending function
    SDL_SetTextureBlendMode( mTexture, blending );


void LTexture::setAlpha( Uint8 alpha )

    //Modulate texture alpha
    SDL_SetTextureAlphaMod( mTexture, alpha );


void LTexture::render(SDL_Renderer *&gRenderer, int x, int y, SDL_Rect *clip, double angle, SDL_Point *center, SDL_RendererFlip flip)

    //Set rendering space and render to screen
    SDL_Rect renderQuad =  x, y, mWidth, mHeight ;

    if( clip != NULL )
    
        renderQuad.w = clip->w;
        renderQuad.h = clip->h;
    


    SDL_RenderCopyEx( gRenderer, mTexture, clip, &renderQuad, angle, center, flip );

【问题讨论】:

【参考方案1】:

问题在于 if 语句末尾的分号。

if( !gTextTexture.loadFromRenderedText(gFont, "Hello I am hot", textColor, gRenderer));
    
        printf( "Failed to render text texture!\n" );
        success = false;
    

该分号将为该 if 块创建一个空语句,它将导致您的


        printf( "Failed to render text texture!\n" );
        success = false;

始终执行。是这样的,

if(.....)
   ;


   ....

【讨论】:

如果返回 true,则输出“无法渲染文本纹理”。这就是它的作用,它不会返回 false。 天啊,我没看到!太感谢了!我知道那个 if 语句有问题,该死的,非常感谢!

以上是关于SDL2 - 应该返回 True 的函数评估为 False的主要内容,如果未能解决你的问题,请参考以下文章

修复 PHP 空函数

空?:未绑定的标识符

在 bool 函数中返回 true 或其他内容

评估字符串的布尔函数

python bool

Fmod函数显然输出一个预期的double,但是if(fmod == expected double)不能评估为true [duplicate]