我在调试这个程序时遇到了困难。我试图模仿微软桌面上可以拖入矩形的功能。
我们想让它:
1. 为了开始绘制你按下鼠标的矩形。
2. 通过向下拖动鼠标来创建矩形的形状和大小。
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);
}
我们遇到的问题是矩形一直在移动,就好像它没有将第一次单击图像的位置作为其位置一样。