SDL2和Xcode

时间:2018-10-17 06:53:51

标签: c xcode sdl

我尝试使用SDL2在C语言中编写某些内容,但是渲染器出现了一些麻烦。

我的代码是:

#include <stdbool.h>
#include "main.h"

#define WND_WIDTH   800
#define WND_HEIGHT  600

void displayText(SDL_Renderer *rdr,TTF_Font *font,char *str,SDL_Color *color,SDL_Rect *text_coo) 

{
SDL_Surface *text=TTF_RenderText_Blended(font,str,*color);
SDL_Texture *tx_text=SDL_CreateTextureFromSurface(rdr,text);
SDL_QueryTexture(tx_text,NULL,NULL,&text_coo->w,&text_coo->h);
text_coo->x=(WND_WIDTH-text_coo->w)/2;
text_coo->y=(WND_HEIGHT-text_coo->h)/2;
SDL_RenderCopy(rdr,tx_text,NULL,text_coo);
SDL_RenderPresent(rdr);
SDL_DestroyTexture(tx_text);
SDL_FreeSurface(text);
}

int main(int argc,char *argv[]) 
{
  SDL_Window *wnd;
  SDL_Renderer *rdr;
  SDL_Rect text_coo;

  SDL_Init(SDL_INIT_VIDEO);
  TTF_Init();
  TTF_Font *font=TTF_OpenFont("/Users/coldpe/Documents/SDLProject2/SDLProject/Batang.ttf",24);
         wnd=SDL_CreateWindow("Noname",SDL_WINDOWPOS_CENTERED,SDL_WINDOWPOS_CENTERED,WND_WIDTH,WND_HEIGHT,SDL_WINDOW_HIDDEN);

rdr=SDL_CreateRenderer(wnd,-1,SDL_RENDERER_ACCELERATED);
SDL_ShowWindow(wnd);
SDL_SetRenderDrawColor(rdr,64,64,64,0xff);
SDL_RenderClear(rdr);
SDL_SetRenderDrawColor(rdr,128,128,128,0xff);
SDL_Rect r={WND_WIDTH/2-100,WND_HEIGHT/2-100,200,200};
SDL_RenderFillRect(rdr,&r);
SDL_SetRenderDrawColor(rdr,64,64,64,0xff);

SDL_Color normal_color={0,0,255,0xff};
SDL_Color selected_color={0,255,0,0xff};
SDL_Color *pc=&normal_color;
displayText(rdr,font,"Hello",pc,&text_coo);
bool done=false;

while(!done) {
    SDL_Event event;
    if(SDL_PollEvent(&event)) {

        if(event.type==SDL_QUIT)
            done=true;

        if(event.type==SDL_MOUSEMOTION) 
{
            if(event.motion.x>=text_coo.x && event.motion.x<=text_coo.x+text_coo.w &&
               event.motion.y>=text_coo.y && event.motion.y<=text_coo.y+text_coo.h) {
                if(pc!=&selected_color) {
                    pc=&selected_color;
                    displayText(rdr,font,"Hello",pc,&text_coo);
                }
            }
            else
                if(pc!=&normal_color) {
                    pc=&normal_color;
                    displayText(rdr,font,"Hello",pc,&text_coo);
                }
        }
    }
}

SDL_DestroyRenderer(rdr);
SDL_DestroyWindow(wnd);
TTF_CloseFont(font);
TTF_Quit();
SDL_Quit();

return(0);
}

我已经试图在其他论坛的网站上寻求帮助,并且我应该用鼠标而不是文本来获取此图像:

Mouse not on the text

此图像用鼠标放在文本上:

Mouse on the text

但是,由于我不知道的原因,这是我真正用鼠标获得的图像,而不是文字:

Mouse not on the text

这是我用鼠标在文本上获得的结果:

Mouse on the text

为什么当鼠标放在文本上时,“背景”是黑色的?

我确定这不是代码的麻烦,因为此代码可与其他人一起使用... 供您参考,我使用的是Xcode 9(Xcode 10在OpenGL中有一些错误)。

有人有答案吗?

1 个答案:

答案 0 :(得分:0)

我认为这里的问题是,只清除一次具有所需颜色的后缓冲。渲染下一帧时,旧的后缓冲内容消失了,因此您需要再次重画它。也就是说displayText应该以

开头
SDL_SetRenderDrawColor(rdr,64,64,64,0xff);
SDL_RenderClear(rdr);
SDL_SetRenderDrawColor(rdr,128,128,128,0xff);
SDL_Rect r={WND_WIDTH/2-100,WND_HEIGHT/2-100,200,200};
SDL_RenderFillRect(rdr,&r);
SDL_SetRenderDrawColor(rdr,64,64,64,0xff);