使用mouseDown C ++ / CLI在图像上创建矩形

时间:2011-03-22 16:03:36

标签: c++-cli mouseevent drag onmousedown drawrectangle

我在调试此程序时遇到困难。我试图模仿微软桌面上的功能,你可以拖动到一个矩形。
我们想要这样做:
1.要开始绘制矩形,请按下鼠标。
2.通过向下拖动mosue,您可以创建矩形的形状和大小 3.通过松开鼠标,您将结束矩形的绘图 4.我们希望能够跟踪起点和终点。


到目前为止,我们已经

 private: System::Void pictureBox1_Paint(System::Object^  sender, System::Windows::Forms::PaintEventArgs^  e) {

        // e->Graphics;
        //put pen where it belongs..
        Pen^ blackPen = gcnew Pen( Color::Black,3.0f );

        if(drawing)
        {
        e->Graphics->DrawRectangle( blackPen, *getRect(ROIlocation1->X, ROIlocation1->Y, ROIlocation2->X, ROIlocation2->Y ));
        }   
        //pictureBox1->Invalidate();
     }
 private: System::Void pictureBox1_MouseDown(System::Object^  sender, System::Windows::Forms::MouseEventArgs^  e) {

        currentPos = startPos = e->Location;
        ROIlocation1 = startPos;
        drawing = true;
        pictureBox1->Invalidate();
     }

 private: System::Void pictureBox1_MouseUp(System::Object^  sender, System::Windows::Forms::MouseEventArgs^  e) {


         //NEW
         if (drawing){
             drawing = false;
             //getRect(startPos->X, startPos->Y, currentPos->X, currentPos->Y);
             pictureBox1->Invalidate();
        }

     }

private: System::Void pictureBox1_MouseMove(System::Object^  sender, System::Windows::Forms::MouseEventArgs^  e) {


         //NEW
         currentPos=e->Location;
         ROIlocation2=currentPos;
         if(drawing) pictureBox1->Invalidate();



     }



这是getRect函数:

System::Drawing::Rectangle^ getRect(int xOne, int yOne, int xTwo, int yTwo){
// ms drawRect(x,y,w,h) wants the upper left corner of the rectangle, and the width and height.
// we are given two sets of coordinates. the user can draw the rectangle in four ways,
// not necessarily starting with the upper right hand corner of the rectangle. 
// this function will return a rectangle with the appropriate attributes 
// that the user expects.

int ulpX = std::min(xOne, xTwo); // upper left point x
int ulpY = std::max(yOne, yTwo); //upper left point y
int h = abs(xOne - xTwo); //height
int w = abs(yOne - yTwo); //width


return gcnew System::Drawing::Rectangle(ulpX, ulpY, w, h);

 }

我们遇到的问题是矩形一直在移动,好像它没有将第一次点击的位置保持在图像上作为其位置。

1 个答案:

答案 0 :(得分:0)

弄清楚问题是什么:

int w = abs(xOne - xTwo); //width
int h = abs(yOne - yTwo); //height