Draw the polygon rather than a rect.
authorPat Thoyts <patthoyts@users.sourceforge.net>
Mon, 21 Sep 2020 07:47:13 +0000 (08:47 +0100)
committerPat Thoyts <patthoyts@users.sourceforge.net>
Mon, 21 Sep 2020 07:47:13 +0000 (08:47 +0100)
PolyButton.cpp

index 65d693209d501f934e599b7816440482fcaaad0d..122e972ed2f2a774d1f03fa87e7b2b0856164ff7 100644 (file)
@@ -1,8 +1,12 @@
+#define _USE_MATH_DEFINES
+
 #include "PolyButton.h"
 #include "ButtonProvider.h"
 #include <gdiplus.h>
+#include <math.h>
 #include <new>
 #include <string>
+#include <vector>
 
 static LRESULT CALLBACK WndProc(HWND hwnd, UINT messageId, WPARAM wparam, LPARAM lparam);
 
@@ -128,6 +132,24 @@ inline Gdiplus::RectF RectItoF (const Gdiplus::Rect &rc)
     return Gdiplus::RectF(float(rc.X), float(rc.Y), float(rc.Width), float(rc.Height));
 }
 
+std::vector<Gdiplus::Point> CalculatePoints(Gdiplus::Rect rc, int sidesCount)
+{
+    std::vector<Gdiplus::Point> points;
+    Gdiplus::Point center(rc.Width / 2, rc.Height / 2);
+    Gdiplus::Size radius(rc.Width / 2, rc.Height / 2);
+    double angle = 3 * M_PI_2;
+    double delta = 2 * M_PI / sidesCount;
+    for (int n = 0; n < sidesCount; ++n)
+    {
+        Gdiplus::Point pt;
+        pt.X = static_cast<int>(radius.Width * cos(angle) + center.X + 0.5);
+        pt.Y = static_cast<int>(radius.Height * sin(angle) + center.Y + 0.5);
+        points.push_back(pt);
+        angle += delta;
+    }
+    return points;
+}
+
 void PolyButton::OnPaint()
 {
     PAINTSTRUCT ps = {0};
@@ -141,9 +163,10 @@ void PolyButton::OnPaint()
         Gdiplus::SolidBrush redBrush(Gdiplus::Color::Red);
         Gdiplus::SolidBrush greenBrush(Gdiplus::Color::Green);
         Gdiplus::Brush *brush = IsChecked() ? &redBrush : &greenBrush;
-        g.FillRectangle(brush, clientRect);
-        g.DrawRectangle(&pen, clientRect);
-        
+        std::vector<Gdiplus::Point> points = CalculatePoints(clientRect, _sides);
+        g.FillPolygon(brush, points.data(), static_cast<int>(points.size()));
+        g.DrawPolygon(&pen, points.data(), static_cast<int>(points.size()));
+
         Gdiplus::SolidBrush textBrush(Gdiplus::Color::Black);
         Gdiplus::Font font(L"Segoe UI", 10);
         Gdiplus::RectF layoutRect(float(clientRect.X), float(clientRect.Y), float(clientRect.Width), float(clientRect.Height));