Here's an example of a simple graphics program in C# using Windows Forms:
using System;
using System.Drawing;
using System.Windows.Forms;
namespace GraphicsProgram
{
public class MyForm : Form
{
public MyForm()
{
// Set the size of the form
Size = new Size(400, 400);
}
protected override void OnPaint(PaintEventArgs e)
{
// Call the base class OnPaint method first
base.OnPaint(e);
// Create a Graphics object from the PaintEventArgs
Graphics g = e.Graphics;
// Draw a rectangle
Pen pen = new Pen(Color.Red, 2);
Rectangle rect = new Rectangle(50, 50, 200, 100);
g.DrawRectangle(pen, rect);
// Draw a line
Point startPoint = new Point(50, 50);
Point endPoint = new Point(250, 150);
g.DrawLine(pen, startPoint, endPoint);
// Draw text
Font font = new Font("Arial", 14);
Brush brush = new SolidBrush(Color.Blue);
g.DrawString("Hello, C#!", font, brush, 50, 200);
}
public static void Main()
{
// Create an instance of the form
Application.Run(new MyForm());
}
}
}
In this example, we create a custom `MyForm` class that inherits from `Form`. We override the `OnPaint` method to perform custom painting on the form's surface. Inside the `OnPaint` method, we use a `Graphics` object to draw a rectangle, a line, and text on the form.
The `Main` method creates an instance of the `MyForm` class and runs it using the `Application.Run` method.
When you run this program, it will display a window with a rectangle, a line, and some text drawn on it. You can customize the drawing parameters and add more shapes or elements as per your requirements.
Note that this example uses Windows Forms for basic graphics programming. For more advanced or interactive graphics applications, you may consider using frameworks like WPF, DirectX, or OpenGL, depending on your specific needs.
No comments:
Post a Comment