使用 C# 绘制五边形

本文指导如何使用 C# 绘制五边形。它详细介绍了如何使用 C# 构建正五边形,特别是在非 Windows 环境(例如 macOS,其中 System.Drawing 库不可用)中。您将学习如何计算坐标并根据您的要求自定义输出 PNG 图像文件。

使用 C# 绘制五边形的步骤

  1. 设置 IDE 使用 Aspose.Drawing for .NET 创建五边形图像
  2. 定义所需五边形的中心坐标和边长
  3. 声明一个包含 5 个点的数组,并使用数学库填充适当的坐标
  4. 创建一个 bitmap,其输出图像具有所需的五边形大小
  5. 使用位图创建 Graphics 对象并使用 Clear 方法设置背景
  6. 通过设置五边形背景和顶点来调用 FillPolygon() 方法
  7. 使用 Save() 方法将结果图像保存为 PNG

这些步骤描述了如何使用 C# 绘制完美的五边形。执行计算以创建一个点数组,该数组描绘了围绕中心点的五边形的顶点,并创建所需大小的位图。从位图创建一个 Graphics 对象并执行诸如填充输出图像背景和多边形颜色等操作。

使用 C# 绘制正五边形的代码

using System;
using Aspose.Drawing;
class PentagonDrawer
{
static void Main()
{
var drawingLicense = new License();
drawingLicense.SetLicense("license.lic"); // Set the Aspose license
// Define the pentagon's parameters
int len = 100;
double circumcircleRadius = len / (2 * Math.Sin(Math.PI / 5));
int canvasCenterX = 100;
int canvasCenterY = 100;
// Calculate the vertices of the pentagon
PointF[] vertices = new PointF[5];
for (int vertexIndex = 0; vertexIndex < 5; vertexIndex++)
{
double angleRadians = 2 * Math.PI * vertexIndex / 5 - Math.PI / 2; // Rotate to start from top
float xCoordinate = (float)(canvasCenterX + circumcircleRadius * Math.Cos(angleRadians));
float yCoordinate = (float)(canvasCenterY + circumcircleRadius * Math.Sin(angleRadians));
vertices[vertexIndex] = new PointF(xCoordinate, yCoordinate);
}
// Create and save the pentagon image
using (Bitmap canvas = new Bitmap(200, 200))
using (Graphics graphicsContext = Graphics.FromImage(canvas))
{
graphicsContext.Clear(Color.Blue); // Set background color
graphicsContext.FillPolygon(Brushes.Cyan, vertices); // Fill pentagon with color
// graphicsContext.DrawPolygon(Pens.Black, vertices); // Optional outline
canvas.Save("pentagon.png"); // Save the image to file
}
}
}

此代码演示了如何使用 C# 绘制完美五边形。如果要绘制空心五边形,请使用 DrawPolygon() 方法而不是 FillPolygon() 方法。您可以设置各种属性,例如设置Clip”来定义绘图区域、插值模式、页面比例、页面单位和平滑模式。

本文教我们使用 C# 绘制五边形。要缩放图像,请参阅 在 C# 中缩放图像 上的文章。

 简体中文