mfc如何用代码创建图片控件?
我用以下代码创建控件无法显示图片
CStatic* pstaDis = new CStatic;
pstaDis->Create(_T(""), WS_CHILD | WS_VISIBLE | SS_BITMAP | SS_CENTERIMAGE|WS_BORDER, CRect(50, 50, 300, 300), this, 12345);
显示代码如下
```c++
void CsoftwareDlg::DrawPicToHdc(Mat p, CWnd* pWnd)
{//显示函数
Mat p1; //opencv中的图像
CImage img;
CRect rect; //定义矩形类
//CWnd* pWnd = GetDlgItem(IDC); //获取控件句柄
pWnd->GetClientRect(&rect); //获取句柄指向控件区域的大小
CDC* pDc = pWnd->GetDC(); //获取picture控件的DC
int win_w = rect.Width(), win_h = rect.Height(); //获取控件窗口宽高
pDc->SetStretchBltMode(COLORONCOLOR);
resize(p, p1, Size(win_w, win_h)); //调整图片大小。
MatToCImage(p1, img); //将mat转变为cimage
img.Draw(pDc->m_hDC, 0, 0, win_w, win_h, 0, 0, win_w, win_h); //画出图片
ReleaseDC(pDc);
}
void MatToCImage(Mat& mat, CImage& cimage)
{
if (0 == mat.total())
{
return;
}
int nChannels = mat.channels();
if ((1 != nChannels) && (3 != nChannels))
{
return;
}
int nWidth = mat.cols;
int nHeight = mat.rows;
//重建cimage
cimage.Destroy();
cimage.Create(nWidth, nHeight, 8 * nChannels);
//拷贝数据
uchar* pucRow; //指向数据区的行指针
uchar* pucImage = (uchar*)cimage.GetBits(); //指向数据区的指针
int nStep = cimage.GetPitch(); //每行的字节数,注意这个返回值有正有负
if (1 == nChannels) //对于单通道的图像需要初始化调色板
{
RGBQUAD* rgbquadColorTable;
int nMaxColors = 256;
rgbquadColorTable = new RGBQUAD[nMaxColors];
cimage.GetColorTable(0, nMaxColors, rgbquadColorTable);
for (int nColor = 0; nColor < nMaxColors; nColor++)
{
rgbquadColorTable[nColor].rgbBlue = (uchar)nColor;
rgbquadColorTable[nColor].rgbGreen = (uchar)nColor;
rgbquadColorTable[nColor].rgbRed = (uchar)nColor;
}
cimage.SetColorTable(0, nMaxColors, rgbquadColorTable);
delete[]rgbquadColorTable;
}
for (int nRow = 0; nRow < nHeight; nRow++)
{
pucRow = (mat.ptr<uchar>(nRow));
for (int nCol = 0; nCol < nWidth; nCol++)
{
if (1 == nChannels)
{
*(pucImage + nRow * nStep + nCol) = pucRow[nCol];
}
else if (3 == nChannels)
{
for (int nCha = 0; nCha < 3; nCha++)
{
*(pucImage + nRow * nStep + nCol * 3 + nCha) = pucRow[nCol * 3 + nCha];
}
}
}
}
}
但是使用以下代码却可以显示
void CsoftwareDlg::CodeShowImg(Mat mat, CStatic* pPicControll)
{
CImage img;
CRect rect; //定义矩形类
Mat p1;
pPicControll->GetClientRect(&rect); //获取句柄指向控件区域的大小
int win_w = rect.Width(), win_h = rect.Height(); //获取控件窗口宽高
resize(mat, p1, Size(win_w, win_h)); //调整图片大小。
MatToCImage(p1, img); //将mat转变为cimage
HBITMAP hbitmap = img.Detach();
pPicControll->SetBitmap(hbitmap);
}
自我排查后猜测原因出在 img.Draw(pDc->m_hDC, 0, 0, win_w, win_h, 0, 0, win_w, win_h);
他画出的画面在控件之下被遮住了
不大理解
DrawPicToHdc在哪里调用?