I am trying to render my image, however it instead creates a black square instead of an image. I am unsure what the cause is as I have created a texture for the image as well. I am using visual studio 2019 on windows. here is my code
//header file
#pragma once
#include “window.h”
class Rect : public Window {
public:
Rect(const Window &window, int w, int h, int x, int y, int r, int g, int b, int a);
Rect(const Window& window, int w, int h, int x, int y, const std::string &image_path);
~Rect();
void draw() const;
void pollEvents(SDL_Event& event);
private:
int _w, _h;
int _x, _y;
int _r, _g, _b, _a;
SDL_Texture* _texture = nullptr;
};
//file to create image and texture.
#include “rect.h”
#include
Rect::Rect(const Window &window, int w, int h, int x, int y, int r, int g, int b, int a) :
Window(window), _w(w), _h(h), _x(x), _y(y), _r®, _g(g), _b(b), _a(a)
{
}
Rect::Rect(const Window &window, int w, int h, int x, int y, const std::string& image_path) :
Window(window), _w(w), _h(h), _x(x), _y(y)
{
auto surface = IMG_Load(image_path.c_str());
if (!surface) {
std::cerr << “Failed to load image\n”;
}
_texture = SDL_CreateTextureFromSurface(_renderer, surface);
if (!_texture) {
std::cerr << “Failed to load image\n”;
}
SDL_FreeSurface(surface);
}
Rect::~Rect() {
SDL_DestroyTexture(_texture);
}
void Rect::draw() const {
SDL_Rect rect = { _x, _y, _w, _h };
if (_texture) {
SDL_RenderCopy(_renderer, _texture, nullptr, &rect);
}
else {
SDL_SetRenderDrawColor(_renderer, _r, _g, _r, _a);
SDL_RenderFillRect(_renderer, &rect);
}
}
void Rect::pollEvents(SDL_Event &event) {
if (event.type == SDL_KEYDOWN) {
switch (event.key.keysym.sym) {
case SDLK_LEFT:
_x -= 10;
break;
case SDLK_RIGHT:
_x += 10;
break;
case SDLK_UP:
_y -= 10;
break;
case SDLK_DOWN:
_y += 10;
break;
}
}
}
//Main file
#include “window.h”
#include “rect.h”
void pollEvents(Window& window, Rect& rect) {
SDL_Event event;
if (SDL_PollEvent(&event)) {
rect.pollEvents(event);
window.pollEvents(event);
}
}
int main(int argc, char* argv[]) {
Window window(“Window”, 800, 600);
Rect rect(window, 120, 120, 100, 100, “res/hello.png”);
while (!window.isClosed()) {
pollEvents(window, rect);
rect.draw();
window.clear();
}
return 0;
}
the renderer is built on another fie. It first presents the renderer, then clears the renderer.