Working with Pens

Aspose.Drawing for .NET API provides the capability to draw graphics elements. Pens are one of the key elements of working with graphics and are used to draw different line objects such as an ellipse, circle, etc with the specified color.

Set Pen Width to Draw Graphics in C#

To draw graphics with a certain pen width, the following steps can be used.

  1. Create an object of the Bitmap class
  2. Initialize the Graphics object from the created bitmap
  3. Create a new Pen with the desired width
  4. Use the DrawLine method to draw a line with the desired width
  5. Save the output to any desired output image format
// For complete examples and data files, please go to https://github.com/aspose-drawing/Aspose.Drawing-for-.NET
using System.Drawing;
Bitmap bitmap = new Bitmap(1000, 800, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);
Graphics graphics = Graphics.FromImage(bitmap);
for (int i = 1; i < 8; ++i)
{
Pen pen = new Pen(Color.Blue, i);
graphics.DrawLine(pen, 100, i * 100, 900, i * 100);
}
bitmap.Save("Width.png");

Pen width

Set Pen Color to Draw Graphics in C#

To draw graphics with a certain pen color, the following steps can be used.

  1. Create an object of the Bitmap class
  2. Initialize the Graphics object from the bitmap
  3. Create a new Pen with the desired color
  4. Use the DrawLine method to draw a line
  5. Save the output to any desired output image format
// For complete examples and data files, please go to https://github.com/aspose-drawing/Aspose.Drawing-for-.NET
using System.Drawing;
Bitmap bitmap = new Bitmap(1000, 800, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);
Graphics graphics = Graphics.FromImage(bitmap);
Pen bluePen = new Pen(Color.Blue, 2);
graphics.DrawLine(bluePen, 100, 100, 900, 100);
Pen redPen = new Pen(Color.FromArgb(255, 255, 0, 0), 2);
graphics.DrawLine(redPen, 100, 200, 900, 200);
bitmap.Save("Colors.png");

Pen color

Join lines to create Path in C#

Multiple lines can be joined to create a path. To join lines using C#, the following steps can be used.

  1. Create an object of the Bitmap class
  2. Initialize the Graphics object from the bitmap
  3. Create a GraphicsPath object to establish a path
  4. Use the LineJoin to join lines
// For complete examples and data files, please go to https://github.com/aspose-drawing/Aspose.Drawing-for-.NET
using System.Drawing;
using System.Drawing.Drawing2D;
Bitmap bitmap = new Bitmap(1000, 800, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);
Graphics graphics = Graphics.FromImage(bitmap);
DrawPath(graphics, LineJoin.Bevel, 200);
DrawPath(graphics, LineJoin.Round, 400);
bitmap.Save("Join.png");
void DrawPath(Graphics graphics, LineJoin join, int y)
{
Pen pen = new Pen(Color.Blue, 30);
GraphicsPath path = new GraphicsPath();
path.StartFigure();
path.AddLine(100, y, 200, y);
path.AddLine(200, y, 200, y + 100);
pen.LineJoin = join;
graphics.DrawPath(pen, path);
}

Join lines