一、專詞理解</span>
Gdi+:負責Windows繪圖的API。
雙緩衝:繪圖操作和顯示分開,繪製完成後,直接拷貝顯示。
二、MFC處理流程
1.準備GDI+接口
包含頭文件:
#include <gdiplus.h>
using namespace Gdiplus;
#pragma comment (lib,"Gdiplus.lib")
構造函數裏GDI+初始化(容易遺忘掉的地方):
CImageProcessingView::CImageProcessingView():
m_iImgHeight(0),
m_iImgWidth(0)
{
// TODO: 在此處添加構造代碼
// Initialize GDI+.
GdiplusStartupInput gdiplusStartupInput;
ULONG_PTR gdiplusToken;
GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);
}
</pre><pre>
2.構建雙緩衝
private:
CBitmap m_bitmapMemory;// 內存位圖
CDC m_dcMemory; // 內存dc
int m_iImgHeight;// 圖片高
int m_iImgWidth;// 圖片寬
// 操作
public:
void CreateMemoryDC(); // 創建位圖和內存dc
void ReleaseMemoryDC(); // 釋放位圖和內存dc
void CImageProcessingView::CreateMemoryDC()
{
CImageProcessingDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
if (!pDoc)
return;
wchar_t strImg[1024];
MultiByteToWideChar(CP_ACP, NULL, pDoc->GetImagePath().c_str(),\
1024, strImg, 1024);
Image img(strImg);
m_iImgWidth = img.GetWidth();
m_iImgHeight = img.GetHeight();
CClientDC dc(this);
m_dcMemory.CreateCompatibleDC(&dc);
m_bitmapMemory.CreateCompatibleBitmap(&dc, m_iImgWidth, m_iImgHeight);
SelectObject(m_dcMemory, m_bitmapMemory);
// 繪圖
Graphics graphics(m_dcMemory);
graphics.DrawImage(&img, 0, 0);
}
void CImageProcessingView::ReleaseMemoryDC()
{
m_bitmapMemory.DeleteObject();
m_dcMemory.DeleteDC();
}
3. OnDraw裏繪圖
void CImageProcessingView::OnDraw(CDC* pDC)
{
CImageProcessingDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
if (!pDoc)
return;
if (pDoc->GetImagePath() == "")
return;
// 獲取客戶區大小
CRect rect;
GetClientRect(&rect);
int nWidth = m_iImgWidth > rect.Width() ? m_iImgWidth : rect.Width();
int nHeight = m_iImgHeight > rect.Height() ? m_iImgHeight : rect.Height();
// 滾動窗口
CSize sizeTotal;
sizeTotal.cx = nWidth;
sizeTotal.cy = nHeight;
SetScrollSizes(MM_TEXT, sizeTotal);
pDC->BitBlt(0, 0, nWidth, nHeight, &m_dcMemory, 0, 0, SRCCOPY);
}
三、效果及源代碼
代碼地址:https://github.com/lk547256398/ImageProcessing