创建Image类,功能都很通俗易懂,不多赘述。
Image.h:
namespace GT {
class Image {
private:
int m_width;
int m_height;
RGBA* m_data;
public:
Image(int _width=0, int _height=0, byte* _data=nullptr) {
m_width = _width;
m_height = _height;
if (_data) {
m_data = new RGBA[m_width * m_height];
memcpy(m_data, _data, sizeof(RGBA) * m_width * m_height);
}
}
~Image() {
if (m_data) {
delete[]m_data;
}
}
int getWidth() const{ return m_width; }
int getHeight() const{ return m_height; }
RGBA getColor(int x, int y) {
if (x < 0 || x >= m_width - 1 || y < 0 || y >= m_height - 1)return RGBA(0, 0, 0, 0);
return m_data[y * m_width + x];
}
public:
static Image* readFromFile(const char* _filename);
};
}
Image.cpp
这里需要注意调换RGBA的值,因为windows中是RBGA
#include "Image.h"
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
namespace GT {
Image* Image::readFromFile(const char* _filename)
{
int _picType = 0;
int _width = 0;
int _height = 0;
//stbimage读入的图片是反过来的
stbi_set_flip_vertically_on_load(true);
unsigned char* bits = stbi_load(_filename, &_width, &_height, &_picType, STBI_rgb_alpha);
for (int i = 0; i < _width * _height * 4; i += 4) {
byte temp = bits[i];
bits[i] = bits[i + 2];
bits[i + 2] = temp;
}
Image* _image = new Image(_width, _height, bits);
stbi_image_free(bits);
return _image;
}
}
Canvas画布类中的drawImage:
void Canvas::drawImage(int _x, int _y, Image* _image){
for (int u = 0; u < _image->getWidth(); ++u) {
for (int v = 0; v < _image->getHeight(); ++v) {
RGBA _color = _image->getColor(u, v);
drawPoint(_x + u, _y + v, _color);
}
}
}
最后测试:
void Render() {
_canvas->clear();
_canvas->drawImage(100, 100, _image);
//在这里画到设备上,hMem相当于缓冲区
BitBlt(hDC, 0, 0, wWidth, wHeight, hMem, 0, 0, SRCCOPY);
}