1
Graphics / Re: Scroll a text with bitmap font
« on: February 06, 2023, 12:01:52 am »
I use this code but there is maybe a better way in sfml.
#include <iostream>
#include <algorithm>
#include <opencv2/opencv.hpp>
const int SCREEN_WIDTH = 80;
const int SCREEN_HEIGHT = 25;
const int FONT_HEIGHT = 8;
const int NUM_CHARS = 256;
const int TEXT_WIDTH = 320;
const int TEXT_HEIGHT = FONT_HEIGHT;
int main() {
// Load bitmap font
cv::Mat font = cv::imread("myFont.png", cv::IMREAD_GRAYSCALE);
int FONT_WIDTH = font.cols / NUM_CHARS;
// Render text to off-screen bitmap
cv::Mat text = cv::Mat::zeros(TEXT_HEIGHT, TEXT_WIDTH, CV_8UC1);
std::string text_str = "Hi, my name is scroller";
int pos = 0;
for (const char& c : text_str) {
for (int i = 0; i < FONT_HEIGHT; i++) {
for (int j = 0; j < FONT_WIDTH; j++) {
text.at<uchar>(i, pos + j) = font.at<uchar>(i, (c + 32) * FONT_WIDTH + j);
}
}
pos += FONT_WIDTH;
}
int offset = 0;
while (true) {
// Clear screen
for (int i = 0; i < SCREEN_HEIGHT; i++) {
for (int j = 0; j < SCREEN_WIDTH; j++) {
std::cout << ' ';
}
std::cout << std::endl;
}
// Copy portion of off-screen bitmap to screen
for (int i = 0; i < SCREEN_HEIGHT; i++) {
for (int j = 0; j < SCREEN_WIDTH; j++) {
int x = j + offset;
if (x >= 0 && x < TEXT_WIDTH) {
std::cout << (text.at<uchar>(i, x) > 128 ? '#' : ' ');
} else {
std::cout << ' ';
}
}
std::cout << std::endl;
}
// Update offset
offset--;
if (offset < -TEXT_WIDTH + SCREEN_WIDTH) {
offset = 0;
}
// Wait for a while
std::this_thread::sleep_for(std::chrono::milliseconds(50));
}
return 0;
}
#include <iostream>
#include <algorithm>
#include <opencv2/opencv.hpp>
const int SCREEN_WIDTH = 80;
const int SCREEN_HEIGHT = 25;
const int FONT_HEIGHT = 8;
const int NUM_CHARS = 256;
const int TEXT_WIDTH = 320;
const int TEXT_HEIGHT = FONT_HEIGHT;
int main() {
// Load bitmap font
cv::Mat font = cv::imread("myFont.png", cv::IMREAD_GRAYSCALE);
int FONT_WIDTH = font.cols / NUM_CHARS;
// Render text to off-screen bitmap
cv::Mat text = cv::Mat::zeros(TEXT_HEIGHT, TEXT_WIDTH, CV_8UC1);
std::string text_str = "Hi, my name is scroller";
int pos = 0;
for (const char& c : text_str) {
for (int i = 0; i < FONT_HEIGHT; i++) {
for (int j = 0; j < FONT_WIDTH; j++) {
text.at<uchar>(i, pos + j) = font.at<uchar>(i, (c + 32) * FONT_WIDTH + j);
}
}
pos += FONT_WIDTH;
}
int offset = 0;
while (true) {
// Clear screen
for (int i = 0; i < SCREEN_HEIGHT; i++) {
for (int j = 0; j < SCREEN_WIDTH; j++) {
std::cout << ' ';
}
std::cout << std::endl;
}
// Copy portion of off-screen bitmap to screen
for (int i = 0; i < SCREEN_HEIGHT; i++) {
for (int j = 0; j < SCREEN_WIDTH; j++) {
int x = j + offset;
if (x >= 0 && x < TEXT_WIDTH) {
std::cout << (text.at<uchar>(i, x) > 128 ? '#' : ' ');
} else {
std::cout << ' ';
}
}
std::cout << std::endl;
}
// Update offset
offset--;
if (offset < -TEXT_WIDTH + SCREEN_WIDTH) {
offset = 0;
}
// Wait for a while
std::this_thread::sleep_for(std::chrono::milliseconds(50));
}
return 0;
}