关闭

怎样判断一个坐标是否在已知三角形内?

967人阅读 评论(0) 收藏 举报

       根据直线Ax+By+C=0和点P的关系知识可知,把点P代入式子Ax+By+C的值的正负,来判断点P在直线的位置。

又知三角形的内心必在三角形内部,所以我们可以把测试点和内心比较,即可得出该点是否在三角形内部。

源代码:(在BCB6.0测试通过)

void __fastcall TForm1::Button1Click(TObject *Sender)
{
    float fPointX1,fPointY1;
    float fPointX2,fPointY2;
    float fPointX3,fPointY3;
    float k1,b1,k2,b2,k3,b3;

    char cFlag1 = 0;
    char cFlag2 = 0;

    float fTestPX =232,fTestPY = 192;
    float fInX,fInY;

    fPointX1 = 72;
    fPointY1 = 56;

    fPointX2 = 104;
    fPointY2 = 208;

    fPointX3 = 280;
    fPointY3 = 136;

    float temp1 =  sqrt( Power(fPointX3-fPointX2,2)+Power(fPointY3-fPointY2,2) );
    float temp2 =  sqrt( Power(fPointX3-fPointX1,2)+Power(fPointY3-fPointY1,2) );
    float temp3 =  sqrt( Power(fPointX2-fPointX1,2)+Power(fPointY2-fPointY1,2) );

    //得到该三角形的内心,内心必在三角形内部
    fInX = ((temp1*fPointX1)+(temp2*fPointX2)+(temp3*fPointX3))/(temp1+temp2+temp3);
    fInY = ((temp1*fPointY1)+(temp2*fPointY2)+(temp3*fPointY3))/(temp1+temp2+temp3);


    //得到三角形 三个边的直线方程系数
    k1 = (fPointY2-fPointY1)/(fPointX2-fPointX1);
    b1 = fPointY1-k1*fPointX1;

    k2 = (fPointY3-fPointY2)/(fPointX3-fPointX2);
    b2 = fPointY2-k2*fPointX2;

    k3 = (fPointY3-fPointY1)/(fPointX3-fPointX1);
    b3 = fPointY3-k3*fPointX3;

    //得到内心的 对应数的值
    if (k1*fInX-fInY+b1 > 1e-6)
        cFlag1 = cFlag1 | 0200;
    else
        cFlag1 = cFlag1 | 0100;

    if (k2*fInX-fInY+b2 > 1e-6)
        cFlag1 = cFlag1 | 0020;
    else
        cFlag1 = cFlag1 | 0010;

    if (k3*fInX-fInY+b3 > 1e-6)
        cFlag1 = cFlag1 | 0002;
    else
        cFlag1 = cFlag1 | 0001;

    //检验对应点

    if (k1*fTestPX-fTestPY+b1 > 1e-6)
        cFlag2 = cFlag2 | 0200;
    else
        cFlag2 = cFlag2 | 0100;

    if (k2*fTestPX-fTestPY+b2 > 1e-6)
        cFlag2 = cFlag2 | 0020;
    else
        cFlag2 = cFlag2 | 0010;

    if (k3*fTestPX-fTestPY+b3 > 1e-6)
        cFlag2 = cFlag2 | 0002;
    else
        cFlag2 = cFlag2 | 0001;

    if (cFlag1 == cFlag2)
        ShowMessage("inside");
    else
        ShowMessage("outside");

}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:781340次
    • 积分:8976
    • 等级:
    • 排名:第2228名
    • 原创:135篇
    • 转载:160篇
    • 译文:1篇
    • 评论:308条
    最新评论