我们在使用c++ easyX库中函数作图时,经常使用setorigin()和setaspectratio()函数将作图原点选在方便之处,并将Y轴正方向调整为向上。图画好后如果需要与鼠标动作关联,但关于鼠标GetMouseMsg() 函数返回的坐标是窗口原始坐标,而图的原始坐标换算起来比较麻烦。如何简单地把窗口的某一位置(如一圆)与鼠标点击位置的原始坐标数值关联起来呢?
这里介绍一个小经验,举例如下:
1、初始化一个窗口760*480
2、在窗口中心画出一个半径为10圆
3、尽量在圆心位置单击鼠标
4、控制台窗口显示x=378 y=238
5、鼠标是否单击在圆区域的判定条件可写成:
378/760*getwidth()-r < x < 378/760*getwidth()+r (r圆半径)
238/480*getheight()-r < y < 238/480*getheight()+r
这里使用getwidth()、getheight()是为了窗口大小有变化时,不用修改代码,仍然可用。
6、这个方法简单实用,精度一般情况下足够
//代码如下:
#include<iostream>
using namespace std;
#include<string>
#include<math.h>
#include<graphics.h>
int main()
{
initgraph(760,480,1);
setorigin(getwidth()/2,getheight()/2);
setaspectratio(1,-1);
circle(0,0,20);
while(1)
{
if(MouseHit())
{
MOUSEMSG msg=GetMouseMsg();
switch(msg.uMsg)
{
case WM_LBUTTONDOWN:
printf("左键按下,当前坐标为(%d,%d)\n",msg.x,msg.y); //这一句在开始确定坐标时使用
if(
(msg.x > getwidth()*378/760-10)&&
(msg.x < getwidth()*378/760+10)&&
(msg.y > getheight()*238/480-10)&&
(msg.y <getheight()*238/480+10)
)
{cout<<"窗口上圆被点击了。。。\n";}
break;
}
}
}
system("pause");
return 0;
}