Reputation: 147
#include<SFML/Window.hpp>
#include<SFML/Graphics.hpp>
#include<cstdint>
#include<iostream>
const int width = 500;
const int height = 500;
int main(){
sf::RenderWindow window(sf::VideoMode(width, height), "Window", sf::Style::Close);
window.setVerticalSyncEnabled(true);
sf::Event event;
uint8_t *pixels = new uint8_t[height *width *4];
for(int i = 0; i < height * width; i+= 4){
pixels[i] = 00; //r
pixels[i + 1] = 00;//g
pixels[i + 2] = 00;//b
pixels[i + 3] = 255;//a
}
sf::Texture texture;
texture.create(width, height);
sf::Sprite sprite;
while(window.isOpen()){
while(window.pollEvent(event)){
if(event.type == sf::Event::Closed){
window.close();
}
}
window.clear(sf::Color::White);
texture.update(pixels);
sprite.setTexture(texture);
window.draw(sprite);
window.display();
}
delete pixels;
return 0;
}
The output I am getting for following program is :
I don't understand why only some part of the window is actually drawn. Since the program is very small I would normnally guess that the problem is created by switching the height and width variable but that is not the case here since both are equal.
The SFML documentation says that if I don't explicitly put the size of texture in sprite.setTexture()
it will default to the size of the texture.
Why is this weird behaviour ? Am I missing something ?
Upvotes: 0
Views: 81
Reputation: 103751
for(int i = 0; i < height * width; i+= 4)
Your pixel buffer is of size height * width * 4
, but you are only looping while i < height * width
. Change the condition in your for loop to i < height * width * 4
. Actually, it would make your code much clearer if you declared another variable to store that value. i.e.
int pixel_buffer_size = width * height * 4;
uint8_t *pixels = new uint8_t[pixel_buffer_size];
for(int i = 0; i < pixel_buffer_size; i+= 4) {
etc...
Upvotes: 2