MFC 在对话框中绘制图形的方法 —— 及二叉树绘制实例

绘制图形

// 清空绘制区域
CRect rectDlg;
GetClientRect(rectDlg);		//获得窗体的大小
int pointWidth = rectDlg.Width();		//获取窗体宽度
int pointHeight = rectDlg.Height();		//获取窗体高度
RedrawWindow(CRect(0, 0, pointWidth, pointHeight));		//重绘指定区域

// 绘制
int x = 200;	// 绘制处x坐标
int y = 100;	// 绘制处y坐标
CDC* pDC = GetDC();		// 创建画笔工具
pDC->Ellipse(x - 8, y - 8, x + 8, y + 8); 	//画圆圈
CString cStr;
cStr.Format(_T("%d"), "文本以图形形式显示");
pDC->TextOut(x - 4, y - 8, cStr);  // 文本输出(图形形式输出)
pDC->MoveTo(x, y);		// 移动当前画笔位置
pDC->LineTo(x +10, y + 10); 	// 画线连接
ReleaseDC(pDC);

二叉树绘制实例

void CMFCBinaryTreeDlg::OnBnClickedButtonInsert()
{
	BinaryTree tree(root);
	
	/* 绘制二叉树 */
	
	// 1.清空绘制区域
	CRect rectDlg;
	GetClientRect(rectDlg);			//获得窗体的大小
	int pointWidth = rectDlg.Width();	//获取窗体宽度
	int pointHeight = rectDlg.Height();	//获取窗体高度
	RedrawWindow(CRect(0, 0, pointWidth, pointHeight));	//重绘指定区域
	
	// 2.获取绘图坐标
	CRect rectL;
	//获取控件相对于屏幕的位置
	GetDlgItem(IDC_PIC1)->GetWindowRect(&rectL);	
	//转化为对话框上的相对位置
	ScreenToClient(rectL);
	int height = rectL.bottom-rectL.top;	//height为button的高
	int width = rectL.right-rectL.left;		//width为button的宽
	
	// 3.绘制图形
	int depth = tree.GetHeight(tree.root);
	CDC* pDC = GetDC();
	paintTree(pDC, tree.root, 750, 250, 0, 0, depth);
	ReleaseDC(pDC);
}

/* 具体绘制函数 */
void CMFCBinaryTreeDlg::paintTree(CDC* pDC, AvlNode<int>*& node, int x, int y, int c, int d, int depth) {	//depth为树的深度
	const int width = 10;	//这个值表示最底层结点之间的距离
	const int height = 30;	//这个值是层与层之间的距离
	int interal = pow(2, double(depth) - c) * width / 2;	//interal是父节点与子节点水平方向上的距离
	int ix, iy;
	if (node != NULL) {

		pDC->Ellipse(x - 8, y - 8, x + 8, y + 8); //画圆圈
		CString cStr;
		cStr.Format(_T("%d"), node->data);
		pDC->TextOut(x - 4, y - 8, cStr);  // 写字

		if (node->left != NULL)
		{
			pDC->MoveTo(x, y); //移动当前画笔位置
			ix = x + interal; // 计算下一个节点坐标 
			iy = y + height;
			pDC->LineTo(ix, iy); // 画线连接
			paintTree(pDC, node->left, x - interal, y + height, c + 1, -1, depth);
		}

		if (node->right != NULL) {
			pDC->MoveTo(x, y); //移动当前画笔位置
			ix = x - interal; // 计算下一个节点坐标 
			iy = y + height;
			pDC->LineTo(ix, iy); // 画线连接
			paintTree(pDC, node->right, x + interal, y + height, c + 1, 1, depth); //递归调用下一层的绘图
		}
	}
}

在这里插入图片描述

  • 4
    点赞
  • 39
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Whitemeen太白

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值