2022年8月18日 星期四

c++ 語言將陣列當成 bitmap 畫線方式

參考畫線演算法: https://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm
用 c++ 語言將 unsigned char arra[w * h] 陣列當灰階 bitmap, 在裏面畫線範例程式:         
// draw.cpp
#include "stdio.h"
void drawline (unsigned char *p, int w, int h, int cch, int x1, int y1, int x2, int y2, int c=0xffffff) {
        unsigned char *pixel = p + (y1 * w + x1) * cch;
        int dx = x2 - x1;
        int dy = y2 - y1;
        int sx = dx > 0 ? 1 : -1;
        int sy = dy > 0 ? 1 : -1;
        int xbytes = cch * sx;
        int ybytes = w * cch * sy;
        
        if (dx < 0) dx = -dx;// abs, positive
        if (dy > 0) dy = -dy;//-abs, negative
        int de = dx + dy;
        while (true) {
            if (0 <= x1 && x1 < w &&
                0 <= y1 && y1 < h) {                    
                if (cch == 1) *pixel = c & 0xff;
                else {
                    pixel[2] = c >> 16 & 0xff;// R
                    pixel[1] = c >> 8  & 0xff;// G
                    pixel[0] = c       & 0xff;// B                    
                }
            }
            if (x1 == x2 && y1 == y2) break;
            int ex2 = de << 1;
            if (ex2 >= dy) {
                if (x1 == x2) break;
                de += dy;
                x1 += sx;
                pixel += xbytes;
            }
            if (ex2 <= dx) {
                if (y1 == y2) break;
                de += dx;
                y1 += sy;
                pixel += ybytes;
            }
        }
    };
    int main( ){
        int w = 80;
        int h = 25;
        unsigned char bitmap[w * h] ={0};// bitmap:  width * height, gray set black color
        
        auto grayDraw= [&](int x1, int y1, int x2, int y2) {
                int cch = 1;// color channel
                int grayLevel = 0xff;// white color
                drawline(bitmap, w, h, cch, x1, y1, x2, y2, grayLevel);
        };
       
        grayDraw(    0  ,   0,      0, h-1);
        grayDraw(    0,     0, w-1,     0);
        grayDraw(    0, h-1, w-1, h-1);
        grayDraw(w-1,    0, w-1, h-1);
        
        grayDraw(  0,   0, w-1, h-1);
        grayDraw(  0, h-1, w-1,   0);
       
        unsigned char *pixel = bitmap;
        for(int y = 0; y < h; y++) {
            for(int x = 0; x < w; x ++){
                *pixel ++ > 0 ? printf("O") : printf("."); // 文字模式         
            }           
            printf("\n");
        }
    }
編譯並執行  g++  draw.cpp && ./a.out

沒有留言:

張貼留言

使用 pcie 轉接器連接 nvme SSD

之前 AM4 主機板使用 pcie ssd, 但主機板故障了沒辦法上網, 只好翻出以前買的 FM2 舊主機板, 想辦法讓老主機復活, 但舊主機板沒有 nvme 的界面, 因此上網買了 pcie 轉接器用來連接 nvme ssd, 遺憾的是 grub2 bootloader 無法識...