通过鼠标方向绘制一条长度恒定的线

时间:2013-06-01 17:47:19

标签: c++ directx

正如问题所说,我想画一条从X,Y位置开始的线,例如,鼠标方向上的10个像素......我已经有的功能画了2点之间的一条线,但我无法想象如何在鼠标方向上保持恒定长度

这是功能:

    void D3DGraphics::DrawLine( int x1,int y1,int x2,int y2,int r,int g,int blu )
{
    int dx = x2 - x1;
    int dy = y2 - y1;

    if( dy == 0 && dx == 0 )
    {
        PutPixel( x1,y1,r,g,blu );
    }
    else if( abs( dy ) > abs( dx ) )
    {
        if( dy < 0 )
        {
            int temp = x1;
            x1 = x2;
            x2 = temp;
            temp = y1;
            y1 = y2;
            y2 = temp;
        }
        float m = (float)dx / (float)dy;
        float b = x1 - m*y1;
        for( int y = y1; y <= y2; y = y + 1 )
        {
            int x = (int)(m*y + b + 0.5f);
            PutPixel( x,y,r,g,blu );
        }
    }
    else
    {
        if( dx < 0 )
        {
            int temp = x1;
            x1 = x2;
            x2 = temp;
            temp = y1;
            y1 = y2;
            y2 = temp;
        }
        float m = (float)dy / (float)dx;
        float b = y1 - m*x1;
        for( int x = x1; x <= x2; x = x + 1 )
        {
            int y = (int)(m*x + b + 0.5f);
            PutPixel( x,y,r,g,blu );
        }
    }
}

我还有一个在屏幕上获取鼠标X和Y位置的函数(getmouseX(),getmouseY())

2 个答案:

答案 0 :(得分:1)

  1. Direct3D有D3DXVECTOR2D3DXVECTOR3D3DXCOLOR和类似的结构。你应该使用它们。或者使用typedef D3DXVECTOR2 Vec2;或类似的东西。这些结构具有数学函数,因此使用它们是有意义的。哦,他们在花车上操作。
  2. 一次绘制一个像素是一个糟糕的主题 - 它很慢。您也可以使用IDirect3DDevice9->DrawPrimitive( D3DPT_LINELIST ..)
  3. 在一次通话中轻松绘制整行
  4. 即使您不想使用D3DX*结构,也应该使用strctures来存储颜色和坐标:
  5. 示例:

    struct Coord{
        int x, y;
    };
    
    struct Color{
        unsigned char a, b, g, r;
    };
    

    关于你的问题。

    typedef D3DXVECTOR2 Vec2;
    
    ....
    
    Vec2 startPos = ...;
    Vec2 endPos = getMousePos();
    const float desiredLength = ...;//whatever you need here.
    Vec2 diff = endPos - startPos; //should work. If it doesn't, use
                                   //D3DXVec2Subtract(&diff, &endPos, &startPoss);
    float currentLength = D3DXVec2Length(&diff);
    if (currentLength != 0)
        D3DXVec2Scale(&diff, &diff, desiredLength/currentLength);// diff *= desiredLength/currentLength
    else
        diff = Vec2(0.0f, 0.0f);
    endPos = startPos + diff; //if it doesn't work, use D3DXVec2Add(&endPos, &startPos, &diff);
    

    这种方式endPos不会超过desiredLength而不是startPos。除非startPos == endPos

    P.S。如果你真的想自己画线,你可能想研究bresenham line drawing algorithm

答案 1 :(得分:0)

比率=(开始位置和鼠标位置之间的长度)/ 10

x = startX +(mouseX-startX)/ ratio y = startY +(mouseY-startY)/ ratio

我觉得它是这样的