计算顶部三角形坐标方法:
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 /// <summary> 2 /// 获取顶三角形坐标 3 /// </summary> 4 /// <param name="r">外接圆半径(顶点到中心的距离)</param> 5 /// <param name="n">N角星</param> 6 /// <param name="x1">左横坐标</param> 7 /// <param name="y1">纵坐标</param> 8 /// <param name="x2">又横坐标</param> 9 private void GetCoordinate(double r, int n, out double x1, out double y1, out double x2) 10 { 11 double unitAngle = 0; 12 if(n < 5) 13 { 14 //奇数角星锐角30,偶数角星锐角和为45 15 unitAngle = n % 2 == 1 ? 30 : 45; 16 } 17 else 18 { 19 //奇数角星锐角和为180,偶数角星锐角和为360 20 unitAngle = n % 2 == 1 ? 180 / n : 360 / n; 21 } 22 double l = Math.PI / 180; //弧度单位 23 double a = Math.Sin(360 / (2 * n) * l), //多角芒星各角连中心分割所得的夹角的一半 24 b = Math.Sin(unitAngle/2 * l), //芒星内角锐角的一半 25 c = Math.Sin((180 - 360 / (2 * n) - unitAngle/2) * l), //芒星除了内锐角的其他内角与中心点连线的夹角 26 d = Math.Cos((360 / (2 * n)) * l); 27 x1 = (a * r * b) / c; //正弦定理 28 y1 = (d * r * b) / c; 29 x2 = r - x1; //x2与x1关于中心点垂线对称,右移r个长度 30 x1 += r; //右移r个长度 31 y1 -= r; //下移r个长度 32 //取正数 33 x1 = x1 < 0 ? x1 * (-1) : x1; 34 y1 = y1 < 0 ? y1 * (-1) : y1; 35 x2 = x2 < 0 ? x2 * (-1) : x2; 36 }
1、画空心正N角星
思路:通过计算得到顶部一个三角形的坐标,画出三角形,再画出三角形顺时针旋转一周的其他N-1个三角形。组合起来得到一个伪的多角芒星。
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 /// <summary> 2 /// 画多角芒星,正多角星 3 /// </summary> 4 /// <param name="r">外接圆半径</param> 5 /// <param name="n">角数量</param> 6 /// <returns>返回包含正多角星的Canvas</returns> 7 private Canvas DrawingPentacle(double r, int n) 8 { 9 double x1, x2, y1; 10 GetCoordinate(r, n, out x1, out y1, out x2); 11 Canvas canvas = new Canvas() { Width = 100, Height = 100 }; 12 //重复N次画出N个三角形斜边 13 for (int i = 1; i <= n; i++) 14 { 15 DrawingVisual dv = new DrawingVisual(); 16 using (DrawingContext dc = dv.RenderOpen()) 17 { 18 dc.DrawGeometry(Brushes.LightBlue, new Pen(Brushes.BlueViolet, 1), Geometry.Parse(string.Format("M {0},0 L{1},{2} M 50,0 L{3},{2}", r, x1, y1, x2))); 19 } 20 //顺时针旋转 21 dv.Transform = new RotateTransform(i * 360 / n, 50, 50); 22 23 //作为图片资源放到图片控件中 24 RenderTargetBitmap rtb = new RenderTargetBitmap(100, 100, 0, 0, PixelFormats.Default); 25 rtb.Render(dv); 26 Image image = new Image() { Source = rtb }; 27 canvas.Children.Add(image); 28 } 29 return canvas; 30 }