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

       根据直线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");

}

阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/bat603/article/details/749957
文章标签: float button 测试 c
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

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

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭