用C#绘制正弦函数图像
时间: 2023-06-27 10:08:26 浏览: 201
以下是使用C#绘制正弦函数图像的示例代码:
```csharp
using System;
using System.Drawing;
using System.Windows.Forms;
public class SineFunction : Form
{
private const int WIDTH = 800;
private const int HEIGHT = 600;
private const float X_SCALE = 4.0f;
private const float Y_SCALE = 100.0f;
private Pen pen = new Pen(Color.Blue, 2);
private Graphics graphics;
private Bitmap bitmap;
public SineFunction()
{
bitmap = new Bitmap(WIDTH, HEIGHT);
graphics = Graphics.FromImage(bitmap);
// 设置窗口标题和大小
Text = "正弦函数";
Size = new Size(WIDTH, HEIGHT);
}
protected override void OnPaint(PaintEventArgs e)
{
graphics.Clear(Color.White);
// 绘制坐标轴
graphics.DrawLine(Pens.Black, 0, HEIGHT / 2, WIDTH, HEIGHT / 2);
graphics.DrawLine(Pens.Black, WIDTH / 2, 0, WIDTH / 2, HEIGHT);
// 绘制正弦函数曲线
for (int x = 0; x < WIDTH; x++)
{
float y = (float)(Math.Sin((x - WIDTH / 2) / X_SCALE) * Y_SCALE) + HEIGHT / 2;
graphics.DrawRectangle(pen, x, y, 1, 1);
}
// 将绘制结果显示在窗口中
e.Graphics.DrawImage(bitmap, 0, 0);
}
public static void Main()
{
Application.Run(new SineFunction());
}
}
```
运行程序后会显示一个窗口,窗口中绘制了正弦函数的图像。可以通过修改代码中的常量来调整图像的大小和比例。
阅读全文