1、绘制矩形
创建一个绘制矩形的函数,本次是用绘制多边形的函数定义的,定义绘制四条变的矩形区域。
先进行函数声明:
void DrawRectangle1(Gdiplus::Point rectangle_points[], CPoint oript, CPoint detpt)
然后定义函数(selected_rect_是之前定义了一个矩形框,使画的东西在框的区域内):
void CdrawtestDlg::DrawRectangle1Gdiplus(Gdiplus::Point rectangle_points[], CPoint oript, CPoint detpt){ if (!(oript.x >= selected_rect_.left && oript.x <= selected_rect_.right && oript.y > selected_rect_.top && oript.y < selected_rect_.bottom)) { return; } if (!(detpt.x >= selected_rect_.left && detpt.x <= selected_rect_.right && detpt.y > selected_rect_.top && detpt.y < selected_rect_.bottom)) { return; } if (drawing_mode_ == deawingrectangle) { rectangle_points[0] = Gdiplus::Point(oript.x, oript.y); rectangle_points[1] = Gdiplus::Point(detpt.x, oript.y); rectangle_points[2] = Gdiplus::Point(detpt.x, detpt.y); rectangle_points[3] = Gdiplus::Point(oript.x, detpt.y); InvalidateRect(selected_rect_, false); } }
定义变量:
/*矩形定义*/ BOOL is_selected;//是否选中 BOOL is_select;//是否选中 BOOL is_scale;//是否缩放 BOOL is_move;//是否移动
并初始化为FALSE,在对话框点击绘制按钮那响应为TURE。
在ONPaint函数中添加以下代码:
if (drawing_mode_==deawingrectangle||is_move||is_scale)
{
g.DrawPolygon(&pen3,rectangle_point_,4);
}
添加消息响应函数鼠标左键按下的响应,并添加以下代码:
if (draw_mode_ == rectangle) { drawing_mode_ = deawingrectangle; rectangle_point_[0].X = point.x; rectangle_point_[0].Y = point.y; rectangle_point_[1].X = point.x; rectangle_point_[1].Y = point.y; rectangle_point_[2].X = point.x; rectangle_point_[2].Y = point.y; rectangle_point_[3].X = point.x; rectangle_point_[3].Y = point.y; }
添加鼠标移动的响应函数并编辑:
if (drawing_mode_ == deawingrectangle) { SetCursor(h_cur_); DrawRectangle1Gdiplus(rectangle_point_, CPoint(rectangle_point_[0].X, rectangle_point_[0].Y), point); }
添加鼠标抬起响应函数:
if (drawing_mode_ == deawingrectangle) { Gdiplus::GraphicsPath gpath_rectangle; temp_path.AddPolygon(rectangle_point_, 4); temp_path.AddPath(&gpath_rectangle, FALSE); gpath_rectangle.Reset(); InvalidateRect(selected_rect_, false); drawing_mode_ = invalid; }
这样就可以画矩形了,效果如下:
2、添加旋转、缩放并且移动
主要是要跟随鼠标移动进行旋转
首先我们要绘制标志点,当选中标志点的时候矩形旋转
所以在鼠标左键按下的响应函数添加以下代码:
void CdrawtestDlg::OnLButtonDown(UINT nFlags, CPoint point) { // TODO: 在此添加消息处理程序代码和/或调用默认值 if (is_draw) { if (draw_mode_==arrow) { drawing_mode_=drawingarrow; arrow_points_[0].X = point.x; arrow_points_[0].Y = point.y; arrow_points_[1].X = point.x; arrow_points_[1].Y = point.y; arrow_points_[2].X = point.x; arrow_points_[2].Y = point.y; arrow_points_[3].X = point.x; arrow_points_[3].Y = point.y; arrow_points_[4].X = point.x; arrow_points_[4].Y = point.y; arrow_points_[5].X = point.x; arrow_points_[5].Y = point.y; } if (draw_mode_ == line) { start_pt_ = point; drawing_mode_ = drawingline; } if (draw_mode_ == rectangle) { drawing_mode_ = deawingrectangle; rectangle_point_[0].X = point.x; rectangle_point_[0].Y =