首先在菜单栏中加入这个工具
然后给他一个ID,注意要全大写
在类视图中右键你的view,选择属性
在消息栏添加鼠标消息,此时会自动添加一个空函数体。
在事件栏添加鼠标事件,为按下菜单栏按钮的时候添加要做的事情。此时也会生成一个空函数体叫做void CMFCApplication1View::OnBreLine()
给void CMFCApplication1View::OnBreLine()添加代码:
void CMFCApplication1View::OnBreLine()
{
// TODO: 在此添加命令处理程序代码
MenuDrawType = 3;
PressNum = 0;
}
在void CMFCApplication1View::OnLButtonDown(UINT nFlags, CPoint point)函数体中添加bresenham的算法代码:
void CMFCApplication1View::OnLButtonDown(UINT nFlags, CPoint point)
{// TODO: 在此添加消息处理程序代码和/或调用默认值
CClientDC dc(this);//定义当前绘图区
CRect rect;
if (MenuDrawType == 3) {//拿的是bre线段工具
if (PressNum == 0) {//第一次点击
startP = point;
endP = point;//使线段一直都在,终点始终是鼠标
PressNum++;
}
else {//第二次点击
endP = point;
double k, e;
int p, deltaX, deltaY, x1, y1, x2, y2;
x1 = startP.x;
y1 = startP.y;
x2 = endP.x;
y2 = endP.y;
deltaX = abs(x2 - x1);
deltaY = abs(y2 - y1);
p = 2 * deltaY - deltaX;
int twoDy = 2 * deltaY;
int twoDx = 2 * deltaX;
int twoDyDx = 2 * (deltaY - deltaX);
int twoDxDy = 2 * (deltaX - deltaY);
int x, y, xEnd, yEnd;
if (deltaX == 0) {//k不存在
if (y1 < y2) {
x = x1;
y = y1;
yEnd = y2;
}
else {
x = x2;
y = y2;
yEnd = y1;
}
for (y; y < yEnd; y++) {
SetPixel(dc, x, y, RGB(0, 0, 255));
}
}
else {//k存在
k = deltaY / (double)deltaX;
if (k <= 1.0) {//斜率绝对值k小于等于1
if (x1 > x2) {//向左
x = x2;
y = y2;
xEnd = x1;
SetPixel(dc, x, y, RGB(0, 0, 255));
while (x < xEnd) {
x++;
if (p < 0)
p += twoDy;
else {
if (y1 < y2)//左下
y--;
else//左上
y++;
p += twoDyDx;
}
SetPixel(dc, x, y, RGB(0, 0, 255));
}
}
else {//向右
x = x1;
y = y1;
xEnd = x2;
SetPixel(dc, x, y, RGB(0, 0, 255));
while (x < xEnd) {
x++;
if (p < 0)
p += twoDy;
else {
if (y1 < y2)//右下
y++;
else//右上
y--;
p += twoDyDx;
}
SetPixel(dc, x, y, RGB(0, 0, 255));
}
}
}
else {//斜率绝对值k大于1
if (y1 < x2) {//向下
x = x1;
y = y1;
yEnd = y2;
SetPixel(dc, x, y, RGB(0, 0, 255));
while (y < yEnd) {
y++;
if (p < 0)
p += twoDx;
else {
if (x1 < x2)//右下
x++;
else//左下
x--;
p += twoDxDy;
}
SetPixel(dc, x, y, RGB(0, 0, 255));
}
}
else {//向上
x = x2;
y = y2;
yEnd = y1;
SetPixel(dc, x, y, RGB(0, 0, 255));
while (y < yEnd) {
y++;
if (p < 0)
p += twoDx;
else {
if (x1 < x2)//右上
x--;
else//左上
x++;
p += twoDxDy;
}
SetPixel(dc, x, y, RGB(0, 0, 255));
}
}
}
}
PressNum = 0;
}
}
}
就可以画线了。如果要添加橡皮筋效应……就dd我让我更新橡皮筋篇。
各位加油