C++模拟OpenGL库——图片处理及纹理系统(一):相关类初始设置

创建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);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值