Python 使用 turtle 库
Python 的 turtle 库是一个很好的入门级绘图工具。以下是一个简单的示例代码,用于绘制一个正方形:
```python
import turtle
创建一个画布和一个海龟
window = turtle.Screen()
t = turtle.Turtle()
绘制正方形
for _ in range(4):
t.forward(100) 向前移动100个像素
t.right(90) 向右转90度
关闭画布
window.mainloop()
```
C 使用 Microsoft Foundation Classes (MFC)
MFC 提供了一个绘图程序,允许用户通过鼠标操作绘制直线、矩形和椭圆。以下是一个简单的 C 示例代码:
```csharp
using System;
using System.Drawing;
using System.Windows.Forms;
public class SimpleDrawingForm : Form
{
private Pen pen;
public SimpleDrawingForm()
{
pen = new Pen(Color.Black, 2);
this.MouseDown += new MouseEventHandler(SimpleDrawingForm_MouseDown);
this.MouseMove += new MouseEventHandler(SimpleDrawingForm_MouseMove);
this.MouseUp += new MouseEventHandler(SimpleDrawingForm_MouseUp);
}
private void SimpleDrawingForm_MouseDown(object sender, MouseEventArgs e)
{
pen.StartPoint = e.Location;
}
private void SimpleDrawingForm_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
pen.EndPoint = e.Location;
this.Invalidate();
}
}
private void SimpleDrawingForm_MouseUp(object sender, MouseEventArgs e)
{
pen.StopPoint = e.Location;
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
e.Graphics.DrawLine(pen, pen.StartPoint.X, pen.StartPoint.Y, pen.EndPoint.X, pen.EndPoint.Y);
}
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new SimpleDrawingForm());
}
}
```
Python 使用 matplotlib 库
matplotlib 是一个强大的绘图库,可以用于绘制各种复杂的图形。以下是一个简单的示例代码,用于绘制一个余弦和正弦函数的图像:
```python
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-np.pi, np.pi, 512, endpoint=True)
c = np.cos(x)
s = np.sin(x)
plt.figure(figsize=(8, 6))
plt.plot(x, c, color='red', linewidth=1.0, label='COS', linestyle='-', alpha=0.5)
plt.plot(x, s, 'b--', label="SIN")
plt.title("COS & SIN")
plt.xlabel("x")
plt.ylabel("y")
plt.legend()
plt.show()
```
λ-2D
λ-2D 是一种基于网格系统的编程语言,专门用于函数式编程。用户可以通过在画布上画图来创建函数和定义变量。以下是一个简单的示例代码:
```lambda
定义一个函数,表示 y = sin(x)
sin_x = function x { sin(x) }
在画布上绘制函数 y = sin(x)
plot sin_x, from -pi to pi, with color red, line width 1, label "sin(x)"
```
这些示例展示了如何使用不同的编程语言和库进行简单的编程画图。选择哪种方法取决于你的编程语言偏好和具体需求。对于初学者,Python 的 turtle 库是一个很好的起点,因为它简单直观,易于上手。