Friday, October 24, 2008

Drawing objects in .NET (C#)

Here is a little example of using some available objects for drawing in .NET (namespace System.Drawing):

private void Form1_Paint(object sender, PaintEventArgs e)
{
    // Create a graphics object from the form
    Graphics g = this.CreateGraphics();
    
    // Create a pen object
    Pen p = new Pen(Color.Red, 7);
    
    // Draw one horizontal line line
    g.DrawLine(p, new Point(10, 10), new Point(100, 10));

    // Drawing an image
    Image img = Image.FromFile("C:\\MyPicture.jpg");
    g.DrawImage(img, 120, 20, img.Width, img.Height); 

    // Array of points for some polygon
    Point[] points = new Point[]
    {
        new Point(20, 20),
        new Point(20, 100),
        new Point(50, 65),
        new Point(100, 100),
        new Point(85, 40)
    };

    Brush bs = new SolidBrush(Color.Aquamarine);

    // Fill a shape
    g.FillPolygon(bs, points);

    // Draw a shape defined by the array of points
    g.DrawPolygon(new Pen(Color.Black, 2), points);

    // Draw a text
    Font f = new Font("Arial", 40, FontStyle.Bold);
    g.DrawString("Hello, World!", f, Brushes.Blue, 10, 200);

    // Draw a icon
    g.DrawIcon(SystemIcons.Question, 260, 40);
    g.DrawIcon(SystemIcons.Shield, 260, 80);
}

Another way for drawing a picture is using the Bitmap object that provides methods for save it:

private void Form1_Paint(object sender, PaintEventArgs e)
{
    // Create a graphics object from the form
    Graphics g = this.CreateGraphics();

    // Read and draw the bitmap
    Bitmap bmp = new Bitmap("C:\\MyPicture.jpg");

    g.DrawImage(bmp, 10, 10, bmp.Width, bmp.Height);
}

Saving a modified bitmap:

private void button3_Click(object sender, EventArgs e)
{
    // Read the bitmap
    Bitmap bmp = new Bitmap("C:\\MyPicture.jpg");

    // Create a graphics from this bitmap
    Graphics g = Graphics.FromImage(bmp);

    // Draw a watermark
    Font f = new Font("Arial", 2, FontStyle.Bold);
    g.DrawString("That's me", f, Brushes.White, 10, 10);

    // Finally, save the bitmap in any available format from ImageFormat
    bmp.Save("c:\\MyPicture2.jpg", ImageFormat.Jpeg);
}

Or you can create a new bitmap for drawing inside it:

private void button3_Click(object sender, EventArgs e)
{
    // Create a new bitmap of 100x140 pixels
    Bitmap bmp = new Bitmap(100, 140);

    // Create a graphics from this bitmap
    Graphics g = Graphics.FromImage(bmp);
    
    // Fill its background with white color
    g.FillRectangle(new SolidBrush(Color.White), 0, 0, bmp.Width, bmp.Height);
    
    // Draw some objects
    Pen p = new Pen(Color.Blue, 8);
    g.DrawLine(p, 10, 10, 10, 80);
    g.DrawIcon(SystemIcons.Shield, 40, 40);
    
    // Save the bitmap
    bmp.Save("c:\\MyPicture3.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
}

Anyway, there are a lot of objects and techniques for drawing in .NET, please refer to MSDN for more samples and documentation.

0 comments:


View My Stats