Draw Polygon


   

/*
C# Programming Tips & Techniques
by Charles Wright, Kris Jamsa

Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

namespace Poly
{
  /// <summary>
  /// Summary description for Form1.
  /// </summary>
  public class PolyclsMain : System.Windows.Forms.Form
  {
    private System.Windows.Forms.MainMenu mainMenu1;
    private System.Windows.Forms.MenuItem menuItem1;
    private System.Windows.Forms.MenuItem mnuFileExit;
    private System.Windows.Forms.Label label1;
    /// <summary>
    /// Required designer variable.
    /// </summary>
    private System.ComponentModel.Container components = null;

    public PolyclsMain()
    {
      //
      // Required for Windows Form Designer support
      //
      InitializeComponent();
      InitForm ();

      //
      // TODO: Add any constructor code after InitializeComponent call
      //
    }
    clsPoint pt = new clsPoint (50, 50);
    clsEllipse ellipse = new clsEllipse (200, 150, 150, 75, 450);
    clsCircle circle = new clsCircle (400, 150, 150);
    clsLine line = new clsLine (400, 150, 150, 450);
//    clsShape [] Shapes;
    private void InitForm ()
    {
//    Shapes = new clsShape [] {pt, ellipse, circle, line};
      pt.color = Color.Red;
      this.MaximumSize = new Size (this.Bounds.Width, this.Bounds.Height);
      this.MinimumSize = this.MaximumSize;
      ellipse.color = Color.DarkOrange;
      line.color = Color.Blue;
    }
    /// <summary>
    /// Clean up any resources being used.
    /// </summary>
    protected override void Dispose( bool disposing )
    {
      if( disposing )
      {
        if (components != null) 
        {
          components.Dispose();
        }
      }
      base.Dispose( disposing );
    }

    #region Windows Form Designer generated code
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.label1 = new System.Windows.Forms.Label();
            this.mnuFileExit = new System.Windows.Forms.MenuItem();
            this.menuItem1 = new System.Windows.Forms.MenuItem();
            this.mainMenu1 = new System.Windows.Forms.MainMenu();
            this.SuspendLayout();
            // 
            // label1
            // 
            this.label1.BackColor = System.Drawing.SystemColors.Window;
            this.label1.Dock = System.Windows.Forms.DockStyle.Fill;
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(680, 341);
            this.label1.TabIndex = 0;
            this.label1.Paint += new System.Windows.Forms.PaintEventHandler(this.label1_Paint);
            // 
            // mnuFileExit
            // 
            this.mnuFileExit.Index = 0;
            this.mnuFileExit.Text = "Exit";
            this.mnuFileExit.Click += new System.EventHandler(this.mnuFileExit_Click);
            // 
            // menuItem1
            // 
            this.menuItem1.Index = 0;
            this.menuItem1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
                        this.mnuFileExit});
            this.menuItem1.Text = "File";
            // 
            // mainMenu1
            // 
            this.mainMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
                        this.menuItem1});
            // 
            // clsMain
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
            this.ClientSize = new System.Drawing.Size(680, 341);
            this.Controls.AddRange(new System.Windows.Forms.Control[] {
                        this.label1});
            this.Menu = this.mainMenu1;
            this.MinimizeBox = false;
            this.Name = "Poly";
            this.Text = "Poly";
            this.ResumeLayout(false);

        }
        #endregion

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main() 
    {
      Application.Run(new PolyclsMain());
    }

    private void mnuFileExit_Click(object sender, System.EventArgs e)
    {
      this.Close (); 
    }

    int m_cx = 100;
    int m_cy = 50;

    private void label1_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
    {
//    foreach (clsShape shape in Shapes)
//      shape.Show (e);
      pt.Show(e);
      ellipse.Show (e);
      circle.Show (e);
      line.Show (e);
    }
  }
  abstract public class clsShape
  {
    protected clsShape() { }
    ~clsShape ()
    {
      if (m_Pen != null)
        m_Pen.Dispose ();
      if (m_Brush != null)
        m_Brush.Dispose ();
    }
    protected Pen m_Pen = null;
    protected SolidBrush m_Brush = null;
    public Color color
    {
      get
      {
        if (m_Brush == null)
          m_Brush = new SolidBrush (Color.Black);
        return (m_Brush.Color);
      }
      set
      {
        if (m_Brush != null)
          m_Brush.Dispose ();
        m_Brush = new SolidBrush (value);
      }
    }
    protected virtual SolidBrush brush
    {
      get
      {
        if (m_Brush == null)
          m_Brush = new SolidBrush (Color.Black);
        return (m_Brush);
      }
    }
    protected virtual Pen pen
    {
      get
      {
        if (m_Pen == null)
          SetPen();
        return (m_Pen);
      }
      set {SetPen ();}
    }
    private void SetPen ()
    {
      if (m_Brush == null)
        m_Brush = new SolidBrush (Color.Black);
      if (m_Pen != null)
        m_Pen.Dispose ();
      m_Pen = new Pen (m_Brush, 2);
    }
    public void Show (PaintEventArgs e)
    {
      Draw (e);
    }
    virtual protected void Draw (PaintEventArgs e)
    {
    }
    protected void Rotate (int angle, Point ptCenter, Point [] ptControl)
    {
            // If the angle is 0, there&#039;s nothing to do
      if (angle == 0)
        return;
            
            // The angle is in tenths of a degree. Convert to radians
      double fAngle = (angle / 10.0) / 57.29578;
            
            // Calculate the sine of the angle
      double fSine = Math.Sin (fAngle);
            
            // Calculate the cosing of the angle
      double fCosine = Math.Cos (fAngle);
            
            // Translate the center point so it can be the center of rotation
      double fRotateX = ptCenter.X - ptCenter.X * fCosine - ptCenter.Y * fSine;
      double fRotateY = ptCenter.Y + ptCenter.X * fSine - ptCenter.Y * fCosine;
      for (int x = 0; x <  ptControl.Length; ++x)
      {
                // Rotate the control point and add the translated center point
        double fNewX = ptControl&#91;x&#93;.X * fCosine + ptControl&#91;x&#93;.Y *fSine + fRotateX;
        double fNewY = -ptControl&#91;x&#93;.X * fSine + ptControl&#91;x&#93;.Y *fCosine + fRotateY;
                
                // Put the new values in the control point
        ptControl&#91;x&#93;.X = (int) fNewX;
        ptControl&#91;x&#93;.Y = (int) fNewY;
      }
    }
  }
  public class clsPoint : clsShape
  {
    protected clsPoint () { }
    public clsPoint (int cx, int cy)
    {
      m_cx = cx;
      m_cy = cy;
    }
    public int cx
    {
      get {return(m_cx);}
      set {m_cx = value;}
    }
    public int cy
    {
      get {return(m_cy);}
      set {m_cy = value;}
    }
    protected int m_cx;
    protected int m_cy;
    override protected void Draw (PaintEventArgs e)
    {
      Point pt1 = new Point (m_cx, m_cy - 1);
      Point pt2 = new Point (m_cx, m_cy + 1);
      e.Graphics.DrawLine (pen, pt1, pt2);
      pt1.X = m_cx - 1;
      pt2.X = m_cx + 1;
      pt1.Y = pt2.Y = m_cy;
      e.Graphics.DrawLine (pen, pt1, pt2);
      e.Graphics.DrawRectangle (pen, m_cx - 3, m_cy - 3, 6, 6);
    }
  }
  public class clsLine : clsShape
  {
    protected clsLine () { }
    public clsLine (int cx, int cy, int length, int angle)
    {
      m_Start = new Point (cx, cy);
      m_End = new Point (cx + length, cy);
      m_Angle = angle;
    }
    protected Point m_End;
    protected Point m_Start;
    protected int m_Angle;
    override protected void Draw (PaintEventArgs e)
    {
      Point ptStart = new Point (m_Start.X, m_Start.Y);
      Point &#91;&#93; ptEnd = new Point&#91;1&#93; {new Point (m_End.X, m_End.Y)};
      Rotate (m_Angle, ptStart, ptEnd);
      e.Graphics.DrawLine (pen, ptStart, ptEnd&#91;0&#93;);
    }
  }
  public class clsCircle : clsPoint
  {
    protected clsCircle () { }
    public clsCircle (int cx, int cy, int radius)
    {
      m_cx = cx;
      m_cy = cy;
      m_Radius = radius;
    }
    protected int m_Radius;
    override protected void Draw (PaintEventArgs e)
    {
      e.Graphics.DrawEllipse (pen, m_cx - m_Radius, m_cy - m_Radius, 2 * m_Radius, 2 * m_Radius);
      DrawCenter (e);
    }
    public void DrawCenter (PaintEventArgs e)
    {
      base.Draw (e);
    }
  }
  /// <summary>
  /// Draws an ellipse using Bezier points
  /// </summary>
  public class clsEllipse : clsCircle, IDisposable
  {
    protected clsEllipse () { }
    public void Dispose ()
    {
    }
    public clsEllipse (int cx, int cy, int horiz, int vert, int rotate)
    {
      m_cx = cx;
      m_cy = cy;
      m_Radius = horiz;
      m_Vert = vert;
      m_Rotate = rotate;
    }
    protected double m_Eccentric;
    protected int m_Vert;
    protected int m_Rotate;
        /// <summary>
        /// Overridden from the clsCircle class
        /// </summary>
        /// <param name="e"></param>
    override protected void Draw (PaintEventArgs e)
    {
      int OffsetX = (int) (2 * m_Radius * (2 * (Math.Sqrt(2) - 1) / 3) + 0.5);
      int OffsetY = (int) (2 * m_Vert * (2 * (Math.Sqrt(2) - 1) / 3) + 0.5);
      Point [] ptEllipse = new Point [13]
          {
          new Point (m_cx + m_Radius, m_cy),
          new Point (m_cx + m_Radius, m_cy - OffsetY),
          new Point (m_cx + OffsetX,  m_cy - m_Vert),
          new Point (m_cx,            m_cy - m_Vert),
          new Point (m_cx - OffsetX,  m_cy - m_Vert),
          new Point (m_cx - m_Radius, m_cy - OffsetY),
          new Point (m_cx - m_Radius, m_cy),
          new Point (m_cx - m_Radius, m_cy + OffsetY),
          new Point (m_cx - OffsetX,  m_cy + m_Vert),
          new Point (m_cx,            m_cy + m_Vert),
          new Point (m_cx + OffsetX,  m_cy + m_Vert),
          new Point (m_cx + m_Radius, m_cy + OffsetY),
          new Point (m_cx + m_Radius, m_cy)
          };
      Point ptCenter = new Point (m_cx, m_cy);
      Rotate (m_Rotate, ptCenter, ptEllipse);
      e.Graphics.DrawBeziers (pen, ptEllipse);
      base.DrawCenter (e);
    }
  }
}



           
          


Add size to a Point

   
 

using System;

using System.Drawing;

class Class1 {
    [STAThread]
    static void Main(string[] args) {
        Point topLeft = new Point(10, 10);
        Size rectangleSize = new Size(50, 50);
        Point bottomRight = topLeft + rectangleSize;
        Console.WriteLine("topLeft = " + topLeft);
        Console.WriteLine("bottomRight = " + bottomRight);
        Console.WriteLine("Size = " + rectangleSize);
    }
}

    


Work with Point type

   
 
using System;
using System.Drawing;



class Program {
    static void Main(string[] args) {
        // Create and offset a point.
        Point pt = new Point(100, 72);
        Console.WriteLine(pt);
        pt.Offset(20, 20);
        Console.WriteLine(pt);

        // Overloaded Point operators.
        Point pt2 = pt;
        if (pt == pt2)
            Console.WriteLine("Points are the same");
        else
            Console.WriteLine("Different points");

        // Change pt2&#039;s X value.
        pt2.X = 4000;

        // Now show each X:
        Console.WriteLine("First point: {0}", pt);
        Console.WriteLine("Second point: {0}", pt2);


    }
}

    


Get Pixel information

using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Drawing.Imaging;

public class Form1 : System.Windows.Forms.Form
{
public Form1()
{
InitializeComponent();
}
private void InitializeComponent()
{
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(292, 273);
this.Text = “”;
this.Resize += new System.EventHandler(this.Form1_Resize);
this.Paint += new System.Windows.Forms.PaintEventHandler(this.Form1_Paint);

}
static void Main()
{
Application.Run(new Form1());
}

private void Form1_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
{
Graphics gForm = e.Graphics;
gForm.FillRectangle(Brushes.White, this.ClientRectangle);

// Create a bitmap in memory
Bitmap bmp = new Bitmap(6, 6);
Graphics gBmp = Graphics.FromImage(bmp);

gBmp.FillRectangle(Brushes.White, 0, 0, bmp.Width, bmp.Height);

gBmp.DrawLine(Pens.Red, 0, 0, 5, 5);

gForm.DrawImage(bmp, 20, 20, bmp.Width, bmp.Height);

// Finally, get the pixel information
for (int y = 0; y < bmp.Height; ++y) { for (int x = 0; x < bmp.Width; ++x) { Color c = bmp.GetPixel(x, y); Console.Write("{0,2:x}{1,2:x}{2,2:x}{3,2:x} ", c.A, c.R, c.G, c.G); } Console.WriteLine(); } bmp.Dispose(); } private void Form1_Resize(object sender, System.EventArgs e) { Invalidate(); } } [/csharp]

BitMap Pixel Format


   



  using System;
  using System.Drawing;
  using System.Drawing.Drawing2D;
  using System.Collections;
  using System.ComponentModel;
  using System.Windows.Forms;
  using System.Data;
  using System.Drawing.Imaging;

  public class Test
  {
    static void Main() 
    {
      // Create two new bitmap images
      Bitmap bmp1 = new Bitmap(100, 100, PixelFormat.Format32bppArgb);
      Bitmap bmp2 = new Bitmap(100, 100, PixelFormat.Format24bppRgb);

      bool b1 = ((bmp1.PixelFormat &amp; PixelFormat.Alpha) != 0);
      bool b2 = ((bmp2.PixelFormat &amp; PixelFormat.Alpha) != 0);

      Console.WriteLine("bmp1 has alpha?: " + b1);
      Console.WriteLine("bmp2 has alpha?: " + b2);

      bmp1.Dispose();
      bmp2.Dispose();
    }
  }

           
          


Draw a pie


   

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Drawing.Drawing2D;

public class Form1 : System.Windows.Forms.Form{
  private System.ComponentModel.Container components = null;

  public Form1(){
    InitializeComponent();
        SetStyle(ControlStyles.Opaque, true);
  }
  protected override void Dispose( bool disposing ){
    if( disposing ){
      if (components != null) 
      {
        components.Dispose();
      }
    }
    base.Dispose( disposing );
  }
    protected override void OnPaint(PaintEventArgs e) {
         Graphics g = e.Graphics;
         g.FillRectangle(Brushes.White, ClientRectangle);

         g.FillPie(Brushes.Chartreuse, new Rectangle(60, 60, 50, 50), 90, 210);
    }
  private void InitializeComponent(){
    this.components = new System.ComponentModel.Container();
    this.Size = new System.Drawing.Size(300,300);
    this.Text = "Form1";
  }
  static void Main() {
    Application.Run(new Form1());
  }
}



           
          


Arc Pie Demo

/*
GDI+ Programming in C# and VB .NET
by Nick Symmonds

Publisher: Apress
ISBN: 159059035X
*/
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

namespace MIsc2D_c
{
///

/// Summary description for MIsc2D.
///

public class MIsc2D : System.Windows.Forms.Form
{
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.ListBox listBox1;
///

/// Required designer variable.
///

private System.ComponentModel.Container components = null;

public MIsc2D()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();

//
// TODO: Add any constructor code after InitializeComponent call
//
}

///

/// Clean up any resources being used.
///

protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}

#region Windows Form Designer generated code
///

/// Required method for Designer support – do not modify
/// the contents of this method with the code editor.
///

private void InitializeComponent()
{
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.listBox1 = new System.Windows.Forms.ListBox();
this.SuspendLayout();
//
// label1
//
this.label1.Location = new System.Drawing.Point(40, 280);
this.label1.Name = “label1”;
this.label1.Size = new System.Drawing.Size(160, 16);
this.label1.TabIndex = 0;
//
// label2
//
this.label2.Location = new System.Drawing.Point(40, 296);
this.label2.Name = “label2”;
this.label2.Size = new System.Drawing.Size(160, 16);
this.label2.TabIndex = 1;
//
// label3
//
this.label3.Location = new System.Drawing.Point(40, 312);
this.label3.Name = “label3”;
this.label3.Size = new System.Drawing.Size(160, 16);
this.label3.TabIndex = 2;
//
// listBox1
//
this.listBox1.Location = new System.Drawing.Point(24, 200);
this.listBox1.Name = “listBox1”;
this.listBox1.Size = new System.Drawing.Size(192, 69);
this.listBox1.TabIndex = 3;
//
// MIsc2D
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(292, 373);
this.Controls.AddRange(new System.Windows.Forms.Control[] {
this.listBox1,
this.label3,
this.label2,
this.label1});
this.Name = “MIsc2D”;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = “MIsc2D”;
this.Load += new System.EventHandler(this.MIsc2D_Load);
this.ResumeLayout(false);

}
#endregion

///

/// The main entry point for the application.
///

[STAThread]
static void Main()
{
Application.Run(new MIsc2D());
}

private void MIsc2D_Load(object sender, System.EventArgs e)
{

}

protected override void OnPaint(PaintEventArgs e)
{
Graphics G = e.Graphics;

GraphicsPath p = new GraphicsPath();
PointF[] pts = { new PointF(50, 50),
new PointF(150, 25),
new PointF(200, 50)};
p.AddCurve(pts);
p.AddRectangle(new Rectangle(60, 60, 50, 50));
p.AddPie(100, 100, 80, 80, 0, 35);
G.DrawPath(Pens.Black,p);

GraphicsPathIterator iter = new GraphicsPathIterator(p);
label1.Text = “Num pts in path = ” + iter.Count.ToString();
label2.Text = “Num subpaths in path = ” + iter.SubpathCount.ToString();
label3.Text = “Path has curve = ” + iter.HasCurve().ToString();

int StartIndex;
int EndIndex;
int i;
bool IsClosed;
// Rewind the Iterator.
iter.Rewind();
// List the Subpaths.
for(i=0;i