1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
|
#include <algorithm>
#include <iostream>
#include <random>
#include <string>
#include <vector>
#include <cstdint>
void putpixel(std::vector<uint32_t>& canvas, int width,
int x, int y, uint32_t color) {
canvas[y * width + x] = color;
}
void draw_line(std::vector<uint32_t>& canvas, int width,
int x1, int y1, int x2, int y2, uint32_t color) {
float dx = x2 - x1, dy = y2 - y1;
int step = abs(dx) >= abs(dy) ? abs(dx) : abs(dy);
dx /= step;
dy /= step;
float x = x1, y = y1;
for (int i = 0; i < step; i++) {
putpixel(canvas, width, int(x), int(y), color);
x += dx;
y += dy;
}
}
void to_png(std::vector<uint32_t>& canvas, int width, const char *filename) {
std::string s {"convert -depth 8 -size "};
s += std::to_string(width) + 'x' + std::to_string(canvas.size() / width);
s += " rgba:- ";
s += filename;
FILE *p = popen(s.c_str(), "w");
fwrite(reinterpret_cast<char *>(canvas.data()), 1, canvas.size() * 4, p);
pclose(p);
}
int main() {
const int width = 300, height = 200;
std::vector<uint32_t> canvas(width * height);
std::fill(canvas.begin(), canvas.end(), 0xff000000);
std::default_random_engine rng(std::random_device{}());
int x = rng() % width, y = rng() % height;
for (int i = 0; i < 30; i++) {
int x2 = rng() % width, y2 = rng() % height;
draw_line(canvas, width, x, y, x2, y2, 0xff000000 + rng() % 0x1000000);
x = x2; y = y2;
}
to_png(canvas, width, "out.png");
}
|