首先在某一个位置初始化对应的数组:
BOOL CCPUJuliaSetDlg::OnInitDialog()
{
CDialogEx::OnInitDialog();
…………..
//为对话框添加关闭按钮
LONG lStyle= GetWindowLong(this->m_hWnd, GWL_STYLE);
lStyle |=WS_SYSMENU;
SetWindowLong(this->m_hWnd,GWL_STYLE, lStyle);
CRect rc;
GetClientRect(&rc);
// m_ImageDim是成员变量,类型是int
m_ImageDim= min(rc.Width(), rc.Height());
//生成对应的数组,m_pBuffer是成员变量
m_pBuffer = new BYTE[m_ImageDim *m_ImageDim * 4];
for(int y =0; y < m_ImageDim; ++y){
for(intx = 0; x < m_ImageDim; ++x){
m_pBuffer[y* m_ImageDim*4 + x*4] = 0;//Blue
m_pBuffer[y* m_ImageDim*4 + x*4 + 1] = 0;//Green
m_pBuffer[y* m_ImageDim*4 + x*4 + 2] = 255 * CalculateJuliaSet(x, y);//Red
m_pBuffer[y* m_ImageDim*4 + x*4 + 3] = 255;//Alpha
}
}
returnTRUE; // 除非将焦点设置到控件,否则返回 TRUE
}
然后在OnPaint函数中利用Gdiplus::Bitmap的一个构造函数:
Bitmap(INT width, INT height, INT stride, PixelFormatformat, BYTE *scan0);
注意:在MSDN的解释中,stride也就是一幅图像一行的byte的数量(也就是图像宽度×每一像素的位平面数)必须是4的整数倍,我试了一下,如果不使用四通道,而采用3或者1通道,图像不会显示出来(很奇怪!!!)。下面的代码使用了Gdiplus,为了使Gdiplus生效,必须在构造函数中调用GdiplusStartup,在析构函数中GdiplusShutdown。
在OnPaint函数中的代码:
void CCPUJuliaSetDlg::OnPaint()
{
if(IsIconic())
{
CPaintDCdc(this); // 用于绘制的设备上下文
SendMessage(WM_ICONERASEBKGND,
reinterpret_cast<WPARAM>(dc.GetSafeHdc()),0);
// 使图标在工作区矩形中居中
intcxIcon = GetSystemMetrics(SM_CXICON);
intcyIcon = GetSystemMetrics(SM_CYICON);
CRectrect;
GetClientRect(&rect);
intx = (rect.Width() - cxIcon + 1) / 2;
inty = (rect.Height() - cyIcon + 1) / 2;
// 绘制图标
dc.DrawIcon(x,y, m_hIcon);
}
else
{
//CDialogEx::OnPaint();
CPaintDCdc(this);
Graphicsg(dc.GetSafeHdc());
//BitmapmemBitmap(m_ImageDim, m_ImageDim, 1*m_ImageDim,
//PixelFormat8bppIndexed,m_pBuffer);
//BitmapmemBitmap(m_ImageDim, m_ImageDim, 3*m_ImageDim,
//PixelFormat24bppRGB, m_pBuffer);
BitmapmemBitmap(m_ImageDim, m_ImageDim, 4*m_ImageDim,
PixelFormat32bppARGB,m_pBuffer);
g.DrawImage(&memBitmap,0.0f, 0.0f, 0.0f, 0.0f,
(float)m_ImageDim, (float)m_ImageDim,UnitPixel);
}
}