代码中使用了 SDL2 库,需要先安装并正确配置相关的开发环境。还需要添加字体加载和处理的代码,为图方便,省略。
标签:浏览,int,c++,0xFF,renderer,selectedFileIndex,SDL,include,图形化 From: https://blog.csdn.net/weixin_55357256/article/details/140184595#include <iostream>
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include <vector>
#include <string>
#include <filesystem>const int SCREEN_WIDTH = 640;
const int SCREEN_HEIGHT = 480;class FileBrowser {
private:
SDL_Window* window;
SDL_Renderer* renderer;
std::vector<std::string> fileList;
int selectedFileIndex;void loadFileList() {
for (const auto& entry : std::filesystem::directory_iterator(".")) {
fileList.push_back(entry.path().string());
}
}public:
FileBrowser() {
if (SDL_Init(SDL_INIT_VIDEO) < 0) {
std::cerr << "SDL could not initialize! SDL_Error: " << SDL_GetError() << std::endl;
return;
}window = SDL_CreateWindow("File Browser", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
if (window == NULL) {
std::cerr << "Window could not be created! SDL_Error: " << SDL_GetError() << std::endl;
return;
}renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
if (renderer == NULL) {
std::cerr << "Renderer could not be created! SDL_Error: " << SDL_GetError() << std::endl;
return;
}loadFileList();
selectedFileIndex = 0;
}~FileBrowser() {
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
}void handleEvents() {
SDL_Event e;
while (SDL_PollEvent(&e)) {
if (e.type == SDL_QUIT) {
exit(0);
} else if (e.type == SDL_KEYDOWN) {
switch (e.key.keysym.sym) {
case SDLK_UP:
if (selectedFileIndex > 0) {
selectedFileIndex--;
}
break;
case SDLK_DOWN:
if (selectedFileIndex < fileList.size() - 1) {
selectedFileIndex++;
}
break;
}
}
}
}void render() {
SDL_SetRenderDrawColor(renderer, 0xFF, 0xFF, 0xFF, 0xFF);
SDL_RenderClear(renderer);int y = 50;
for (size_t i = 0; i < fileList.size(); ++i) {
SDL_Color color = {0x00, 0x00, 0x00, 0xFF};
if (i == selectedFileIndex) {
color = {0xFF, 0x00, 0x00, 0xFF};
}
SDL_Surface* surface = TTF_RenderText_Solid(/* Your font here */, fileList[i].c_str(), color);
SDL_Texture* texture = SDL_CreateTextureFromSurface(renderer, surface);SDL_Rect rect = {50, y, surface->w, surface->h};
SDL_RenderCopy(renderer, texture, NULL, &rect);SDL_FreeSurface(surface);
SDL_DestroyTexture(texture);y += surface->h + 10;
}SDL_RenderPresent(renderer);
}void run() {
bool quit = false;
while (!quit) {
handleEvents();
render();
}
}
};int main(int argc, char* args[]) {
FileBrowser fb;
fb.run();return 0;
}