, как это работает
начала щелкать на окне, пока не достигнет суммы sepcified в m_iPolygonMaximumSides. Когда вы достигнете указанного количества точек, полигон будет закрыт, поэтому теперь вы сможете выбрать точку. Нажмите возле точки, чтобы выбрать ее, перетаскивание будет продолжаться, пока вы не нажмете еще раз. Для сброса многоугольника вам нужно будет закрыть окно.
код
в CPP файле вашего класса CChildView добавить следующее включают, так как он используется для вычисления квадратного корня
#include <math.h>
в классе CChildView добавить следующие методы и переменные
CList<CPoint> m_PointList;
CPoint m_selectedPoint;
int m_iPolygonMaximumSides;
afx_msg void OnMouseMove(UINT nFlags, CPoint point);
void DrawPolygonFromList();
на карте сообщений вашего класса CChildView добавить эти строки
ON_WM_LBUTTONDOWN()
ON_WM_MOUSEMOVE()
в конструкторе CChildView инициализации m_iPolygonMaximumSides с суммой, которую вы хотите (4) и m_selectedPoint с (-1, -1), как
m_iPolygonMaximumSides = 4;
m_selectedPoint = CPoint(-1,-1);
, то это должно быть добавлено в файл CPP CChildView, это все используемые методы
void CChildView::OnLButtonDown(UINT nFlags, CPoint point)
{
//check if we already reached the maximum point number
if (m_PointList.GetSize() == m_iPolygonMaximumSides)
{
//check if a point was already selected, and so we are in the drag mode
if (m_selectedPoint.x !=-1)
{
//if the point was already selected it means that we want to stop the dragging,
//so we just set the x to -1
m_selectedPoint.x =-1;
}
else
{
//if we didn't have a point selected we have to check if the point clicked is one of our points
//so we will use this for to search for out point
for (POSITION pos = m_PointList.GetHeadPosition();pos != NULL;m_PointList.GetNext(pos))
{
CPoint currentPoint = m_PointList.GetAt(pos);
//this is the pythagorean theorem to find a distance between two points A and B
// distance = squareRoot((A.x-B.x)^2+(A.y-B.y)^2)
int distanceBetweenPoints = floor(sqrt(pow(double(currentPoint.x-point.x),2)+pow(double(currentPoint.y-point.y),2)));
//if this distance is less than 10 pixels, then we accept it as a click on our points
//this is just a tollerance, so we can reduce or increment it as we like
//the smaller the tollerance nearer you will have to click to be able to select the point
if (distanceBetweenPoints <= 10)
{
//if the tollerance is met then we set the point as our selected point
m_selectedPoint = currentPoint;
//interrupt the iteration, because we don't need to look further
break;
}
}
}
}
//if we didn't reach the maximum point amount it means that we still have to keep going on getting the points
else if (m_PointList.GetSize() > 0)
{
CDC* pDC= GetDC();
CPoint lastPoint = m_PointList.GetTail();
//draw a line from the previous (last) point to the new one
pDC->MoveTo(lastPoint.x,lastPoint.y);
pDC->LineTo(point.x,point.y);
//if we are going to reach the maximum amount of points then we will have to close the polygon
if (m_PointList.GetSize()==m_iPolygonMaximumSides-1)
{
CPoint firstPoint = m_PointList.GetHead();
//draw a line from the current point to the first point
pDC->MoveTo(point.x,point.y);
pDC->LineTo(firstPoint.x,firstPoint.y);
}
}
//add the point to the list only after you have done everything, only if we didn't reachthe maximum amount
if (m_PointList.GetSize() < m_iPolygonMaximumSides)
m_PointList.AddTail(point);
}
void CChildView::OnMouseMove(UINT nFlags, CPoint point)
{
//check if we already have the maximum number of points
if (m_PointList.GetSize()==m_iPolygonMaximumSides)
{
//check i
if (m_selectedPoint.x != -1)
{
//check if we actually find the point
POSITION posFound = m_PointList.Find(m_selectedPoint);
if (posFound != NULL)
{
//update the selected point with the new one
m_selectedPoint=point;
//now also update the list
m_PointList.SetAt(posFound,point);
//draw the polygon
DrawPolygonFromList();
}
}
}
}
void CChildView::DrawPolygonFromList()
{
//this is checked again because we might want to use this function in another place
if (m_PointList.GetSize()==m_iPolygonMaximumSides)
{
//use this to clear the window
RedrawWindow();
//this will be used to draw
CDC* pDC= GetDC();
POSITION pos = m_PointList.GetHeadPosition();
//load the first and second point
CPoint pointBefore = m_PointList.GetNext(pos);
CPoint currentPoint = m_PointList.GetNext(pos);
//draw the line connecting the first and the second point
pDC->MoveTo(pointBefore.x,pointBefore.y);
pDC->LineTo(currentPoint.x,currentPoint.y);
//draw the intermediary points
while (pos != NULL)
{
pointBefore = currentPoint;
currentPoint = m_PointList.GetNext(pos);
pDC->MoveTo(pointBefore.x,pointBefore.y);
pDC->LineTo(currentPoint.x,currentPoint.y);
}
//now close the poligon
pointBefore = currentPoint;
currentPoint = m_PointList.GetHead();
pDC->MoveTo(pointBefore.x,pointBefore.y);
pDC->LineTo(currentPoint.x,currentPoint.y);
}
}
=) здесь я снова. «m_iPointAmount <6» заставит вас иметь 5 очков, но вам нужно 4, как вы сказали. На самом деле вам нужен замкнутый многоугольник с четырьмя сторонами, поэтому на самом деле у вас должна быть другая переменная, которая хранит первую точку, поэтому, когда вы доберетесь до 4-го пункта, вы соедините четвертую точку с первой, чтобы «закрыть» многоугольник – Robson
, чтобы сделать другие вещи, которые вы должны использовать OnMouseMove https://msdn.microsoft.com/en-us/library/3158baat.aspx, и внутри этого вам нужно будет проверить, нажата ли мышь, а затем делать то, что вам нужно. но ясно здесь вы также хотите, чтобы иметь возможность «выбрать» точку. Поскольку ваше имя пользователя говорит, что вы «начинающий», поэтому я думаю, что сначала вы должны немного изучить основы работы MFC C++, как работает GDI, проверить доступные функции и функции, а затем попытаться что-то реализовать. Идя таким образом в темноту, действительно тяжело. – Robson
Как сохранить первую точку? Также как выбрать точку, когда клик сделан? Любой пример кода? Pls ........ – BeginnerWin32