在开始之前,我使用的IDE是Code :: Blocks。
我打算在另一个与我的学习项目分开的项目中练习我在网上学到的关于SDL的事情。我想在背景上加载一个球的图像。它在我的学习项目中运作良好。我将代码复制到我的测试项目中,球消失了。只有背景可见。
我删除了涉及背景的代码并且工作正常。
我的代码:
#include <iostream>
#include <cstdlib>
#include <SDL.h>
#include <SDL_image.h>
#undef main
using namespace std;
SDL_Texture *LoadTexture (string filepath, SDL_Renderer *renderTarget){
SDL_Texture *texture = 0;
SDL_Surface *surface = IMG_Load(filepath.c_str());
texture = SDL_CreateTextureFromSurface(renderTarget, surface);
SDL_FreeSurface(surface);
return texture;
}
int main () {
SDL_Window *window = 0;
SDL_Texture *ball = 0;
SDL_Texture *background_sky = 0;
SDL_Renderer *renderTarget = 0;
int frameW, frameH;
int textureW, textureH;
//--Crop Instructions--//
frameW = textureW / 1; //row division
frameH = textureH / 1; //column division
SDL_Rect ballcrop;
ballcrop.x = ballcrop.y = 0;
ballcrop.w = frameW; //length of selected area
ballcrop.h = frameH; //height of selected area
SDL_Rect ballpos;
ballpos.x = ballpos.y = 10; //ball position
ballpos.w = ballpos.h = 64; //size of crop
//---------------------//
SDL_Init(SDL_INIT_EVERYTHING);
IMG_Init(IMG_INIT_PNG);
window = SDL_CreateWindow("Ball", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 500, 500, SDL_WINDOW_SHOWN);
renderTarget = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
ball = LoadTexture("ball.png", renderTarget);
background_sky = LoadTexture("bg_sky.png", renderTarget);
SDL_QueryTexture(ball, NULL, NULL, &textureW, &textureH); //crop action
bool Active = true;
SDL_Event ev;
while (Active) {
while (SDL_PollEvent(&ev)!=0) {
if (ev.type == SDL_QUIT)
Active = false;
else if (ev.type == SDL_KEYDOWN) {
switch (ev.key.keysym.sym) {
case SDLK_UP:
ballpos.y -= 5;
break;
case SDLK_DOWN:
ballpos.y += 5;
break;
}
}
}
SDL_RenderClear(renderTarget);
SDL_RenderCopy(renderTarget, background_sky, NULL, NULL);
SDL_RenderCopy(renderTarget, ball, &ballcrop, &ballpos);
SDL_RenderPresent(renderTarget);
}
SDL_DestroyWindow(window);
SDL_DestroyTexture(background_sky);
SDL_DestroyTexture(ball);
SDL_DestroyRenderer(renderTarget);
window = 0;
ball = background_sky = 0;
renderTarget = 0;
IMG_Quit();
SDL_Quit();
return 0;
}
我不认为我想展示我的学习项目的源代码,因为它的非常凌乱。
任何帮助将不胜感激:)
答案 0 :(得分:0)
您在计算frameW
和frameH
时出错;计算的代码
//--Crop Instructions--//
frameW = textureW / 1; //row division
frameH = textureH / 1; //column division
在初始化之前使用textureW
和textureH
。移动整个“裁剪说明”块,直到您调用SDL_QueryTexture
。