CM2D/inc/hgl/2d/Bitmap.h

112 lines
2.3 KiB
C
Raw Normal View History

2019-11-29 19:36:38 +08:00
#ifndef HGL_2D_BITMAP_INCLUDE
#define HGL_2D_BITMAP_INCLUDE
2023-07-05 17:23:32 +08:00
#include<hgl/type/DataType.h>
#include<hgl/math/HalfFloat.h>
2023-07-11 18:16:11 +08:00
#include<iterator>
2019-11-29 19:36:38 +08:00
namespace hgl
{
2023-07-11 18:16:11 +08:00
template<typename T>
static void FillPixels(T *p,const T &color,const int length)
{
std::fill_n(p,length,color);
}
2019-11-29 19:36:38 +08:00
/**
* 2D象素处理
*/
2023-07-11 18:16:11 +08:00
template<typename T> class Bitmap
2019-11-29 19:36:38 +08:00
{
2023-07-11 18:16:11 +08:00
int width,height;
2023-07-05 17:23:32 +08:00
T *data;
public:
Bitmap()
{
data=nullptr;
width=height=0;
}
~Bitmap()
{
delete[] data;
}
2023-07-11 18:16:11 +08:00
const int GetWidth ()const{return width;}
const int GetHeight ()const{return height;}
const uint GetTotalPixels ()const{return width*height;}
const uint GetLineBytes ()const{return width*sizeof(T);}
const uint GetTotalBytes ()const{return width*height*sizeof(T);}
T *GetData(){return data;}
2023-07-11 18:16:11 +08:00
T *GetData(int x,int y)
{
return (x<0||x>=width||y<0||y>=height)?nullptr:data+(y*width+x);
}
2023-07-05 17:23:32 +08:00
bool Create(uint w,uint h)
{
if(!w||!h)return(false);
if(data)
{
if(width==w&&height==h)return(true);
}
width=w;
height=h;
delete[] data;
2023-07-11 18:16:11 +08:00
data=new T[width*height];
2023-07-05 17:23:32 +08:00
return(true);
}
void Clear()
{
if(data)
{
delete[] data;
data=nullptr;
}
width=height=0;
}
2023-07-11 18:16:11 +08:00
void ClearColor(const T &color)
2023-07-05 17:23:32 +08:00
{
2023-07-11 18:16:11 +08:00
if(!data)return;
2023-07-05 17:23:32 +08:00
2023-07-11 18:16:11 +08:00
FillPixels<T>(data,color,width*height);
2023-07-05 17:23:32 +08:00
}
void Flip()
{
if(!data||height<=1)return;
2023-07-11 18:16:11 +08:00
const uint line_bytes=width*sizeof(T);
2023-07-05 17:23:32 +08:00
2023-07-11 18:16:11 +08:00
T *temp=new T[width];
2023-07-05 17:23:32 +08:00
T *top=data;
2023-07-11 18:16:11 +08:00
T *bottom=data+(width*(height-1));
2023-07-05 17:23:32 +08:00
while(top<bottom)
{
memcpy(temp,top,line_bytes);
memcpy(top,bottom,line_bytes);
memcpy(bottom,temp,line_bytes);
2023-07-11 18:16:11 +08:00
top+=width;
bottom-=width;
2023-07-05 17:23:32 +08:00
}
delete[] temp;
}
2023-07-11 18:16:11 +08:00
};//template<typename T> class Bitmap
2019-11-29 19:36:38 +08:00
}//namespace hgl
#endif//HGL_2D_BITMAP_INCLUDE