使用Raylib C++的DrawTexturePro居中绘制纹理不显示问题
解决DrawTexturePro纹理不显示的问题
核心问题及修复方案
1. 目标矩形未指定尺寸
你当前的DrawTexturePro调用中,目标矩形仅设置了位置坐标,未定义宽度和高度,导致渲染区域尺寸为0,自然无法显示纹理。
修复后的调用需明确目标矩形的完整参数(位置+尺寸):
DrawTexturePro( texture, { 0.0f, 0.0f, static_cast<float>(texture.width), static_cast<float>(texture.height) }, // 源矩形 { screenWidth / 2.0f - center.x, screenHeight / 2.0f - center.y, static_cast<float>(texture.width), static_cast<float>(texture.height) }, // 目标矩形(包含位置与尺寸) center, 0.0f, WHITE // 使用WHITE保留纹理原色彩,BLACK会将纹理覆盖为黑色(仅适用于带透明通道的白色纹理) );
2. 验证纹理加载状态
添加加载失败判断,避免使用无效纹理:
Texture2D texture = LoadTexture("/Users/stavanmukherjee./Downloads/raylib-master 2/build/raylib-cpp/projects/VSCode/raylib-cpp-starter/src/triangle.png"); if (texture.id == 0) { TraceLog(LOG_ERROR, "纹理加载失败!"); CloseWindow(); return 1; }
3. 排查路径问题
- 路径中的空格(
raylib-master 2)和末尾冗余点(stavanmukherjee.)可能导致加载失败,建议核对路径是否准确,或改用相对路径简化配置。 - 确认图片文件存在且格式为raylib支持类型(PNG、JPG等)。
4. 修正头文件引用
代码中#include "string"不符合C++标准写法,应改为:
#include <string>
完整修复后的代码示例
#include "raylib.h" #include <string> int main() { const int screenWidth = 800; const int screenHeight = 450; InitWindow(screenWidth, screenHeight, "Texture Location Example"); Texture2D texture = LoadTexture("/Users/stavanmukherjee./Downloads/raylib-master 2/build/raylib-cpp/projects/VSCode/raylib-cpp-starter/src/triangle.png"); // 检查纹理加载是否成功 if (texture.id == 0) { TraceLog(LOG_ERROR, "纹理加载失败!"); CloseWindow(); return 1; } Vector2 center = { static_cast<float>(texture.width) / 2.0f, static_cast<float>(texture.height) / 2.0f }; while (!WindowShouldClose()) { BeginDrawing(); ClearBackground(RAYWHITE); DrawTexturePro(texture, { 0.0f, 0.0f, static_cast<float>(texture.width), static_cast<float>(texture.height) }, { screenWidth / 2.0f - center.x, screenHeight / 2.0f - center.y, static_cast<float>(texture.width), static_cast<float>(texture.height) }, center, 0.0f, WHITE); std::string text = "Texture Location: (" + std::to_string(screenWidth / 2.0f - center.x) + ", " + std::to_string(screenHeight / 2.0f - center.y) + ")"; DrawText(text.c_str(), 10, 10, 20, BLACK); EndDrawing(); } UnloadTexture(texture); CloseWindow(); return 0; }
内容的提问来源于stack exchange,提问作者Lets talk games
相关产品推荐
相关产品推荐

