如果dstX = srcX + deltaX,dstY = srcY + deltaY,那么,将(dstX,dstY)的位置赋值(srcX,srcY)的像素。其余的可以暂时为白色。
即添加函数
void CDib::PingYi(int xMove, int yMove)
{
//指向原图像的指针
LPBYTE lpSrc;
LPBYTE p_data = GetData();;
//图像的宽和高
LONG width = GetWidth();
LONG height = GetHeight();;
//图像每行的字节数
LONG lLineBytes = (width*8+31)/32 * 4;
//暂时分配内存,以保存新图像
LPBYTE temp = new BYTE[lLineBytes * height];
//初始化新分配的内存,设定初始值为255
LPBYTE lpDst = (LPBYTE)temp;
memset(lpDst, (BYTE)255, lLineBytes * height);
for (int i = 0; i < width; i++)
{
for (int j = 0; j < height; j++)
{
//计算该像素在原DIB中的坐标
lpSrc = (LPBYTE)p_data + lLineBytes * (height - 1 - j) + i;
//计算新坐标
int i0 = i + xMove;
int j0 = j + yMove;
//判断是否在新图像范围内,如果不在,则直接赋值255
if ((i0 >= 0 ) && ( i0 < width) && (j0 >=0 ) && (j0 < height))
{
lpDst = (LPBYTE)temp + lLineBytes * (height - 1 - j0) + i0;
*lpDst = lpSrc;
}
else
{
((unsigned char)lpDst) = 255;
}
}
}
//复制平移后的图像
memcpy(p_data, temp, lLineBytes height);
//释放内存
delete temp;
}
在初始化时,加载后,调用即可。
CMy1_showbitmapView::CMy1_showbitmapView()
{
// TODO: add construction code here
_cdib.LoadFile (“D:/Test/DataProcess/result.bmp”);
_cdib.PingYi(100, 100);
}
onDraw()不变
void CMy1_showbitmapView::OnDraw(CDC* pDC)
{
CMy1_showbitmapDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
if (!pDoc)
return;
// TODO: add draw code for native data here
//this->StretchBitMap(pDC);
//控制缩放比例
int m_scale = 1;
//CDib类指针对象
BYTE* pBitmapData = _cdib.GetData();
LPBITMAPINFO pBitmapInfo = _cdib.GetInfo();
int bitmapHeight = _cdib.GetHeight();
int bitmapWidth = _cdib.GetWidth();
int scaledWidth = (int)(bitmapWidth * m_scale);
int scaledHeight = (int)(bitmapHeight * m_scale);
bool bGetRGB = _cdib.GetRGB();
if (!bGetRGB)
{
return;
}
CPalette* hPalette = CreateBitmapPalette(&_cdib);
//将已创建的调色板调用到设备上下文中
CPalette* hOldPalette = pDC->SelectPalette(hPalette, true);
//实现调色板
pDC->RealizePalette();
::StretchDIBits(pDC->GetSafeHdc(), 0, 0, scaledWidth, scaledHeight,
0, 0,
bitmapWidth, bitmapHeight,
pBitmapData, pBitmapInfo,
DIB_RGB_COLORS,
SRCCOPY);
pDC->SelectPalette(hOldPalette, true);
::DeleteObject(hPalette);
}
运算结果显示如下: