c# 画一个正弦函数

在C#中,你可以使用System.Drawing命名空间来绘制图形,但这通常是在Windows Forms或WPF应用程序中。然而,为了简单起见,我将展示如何在控制台应用程序中使用字符来模拟绘制正弦函数,以及如何在Windows Forms应用程序中使用System.Drawing来绘制它。

1. 在控制台应用程序中使用字符模拟绘制

虽然这不是真正的图形绘制,但你可以使用字符在控制台中模拟正弦波的外观。

using System;  
  
class Program  
{  
    static void Main()  
    {  
        const int width = 80; // 控制台宽度  
        const int height = 20; // 正弦波的高度范围  
        const double period = 10.0; // 正弦波的周期  
        const double amplitude = 5.0; // 正弦波的振幅  
  
        for (int x = 0; x < width; x++)  
        {  
            double y = amplitude * Math.Sin((2 * Math.PI / period) * x) + height / 2; // 计算y值并调整位置  
            int yPos = (int)y; // 转换为整数位置  
            if (yPos >= 0 && yPos < height) // 确保在可见范围内  
            {  
                Console.SetCursorPosition(x, height - yPos - 1); // 设置光标位置  
                Console.Write("*"); // 绘制字符  
            }  
        }  
  
        Console.ReadLine(); // 等待用户输入  
    }  
}

2. 在Windows Forms应用程序中绘制

在Windows Forms应用程序中,你可以使用System.Drawing来绘制正弦函数。以下是一个简单的示例:

using System;  
using System.Drawing;  
using System.Windows.Forms;  
  
public class SineWaveForm : Form  
{  
    private const int Width = 800;  
    private const int Height = 600;  
    private const double Amplitude = 100.0;  
    private const double Period = 200.0;  
  
    protected override void OnPaint(PaintEventArgs e)  
    {  
        base.OnPaint(e);  
  
        Graphics g = e.Graphics;  
        Pen pen = new Pen(Color.Blue, 2);  
  
        for (double x = 0; x < Width; x += 1)  
        {  
            double y = Height / 2 - Amplitude * Math.Sin((2 * Math.PI / Period) * x);  
            int yInt = (int)y;  
  
            if (yInt >= 0 && yInt < Height)  
            {  
                // 绘制点来模拟连续的线(对于更平滑的线,使用g.DrawCurve或g.DrawBezier)  
                g.DrawEllipse(pen, (float)x, (float)yInt, 2, 2);  
            }  
        }  
  
        pen.Dispose();  
    }  
  
    public SineWaveForm()  
    {  
        this.DoubleBuffered = true; // 减少绘图时的闪烁  
        this.ClientSize = new Size(Width, Height);  
    }  
  
    [STAThread]  
    static void Main()  
    {  
        Application.EnableVisualStyles();  
        Application.SetCompatibleTextRenderingDefault(false);  
        Application.Run(new SineWaveForm());  
    }  
}

注意:上面的Windows Forms示例使用了点来模拟连续的线。对于更平滑的线条,你可以使用g.DrawCurveg.DrawBezier方法,并首先计算出一组定义曲线形状的点。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值