Graphics
7.1 Drawing Methods
The Windows.Forms namespace contains classes for creating Windows based applications.
In this namespace we find the Form class and many other controls that can
be added to forms to create user interfaces. The System.Drawing namespace provides
access to GDI + basic graphics functionality. The Graphics object provides
methods for drawing a variety of lines and shapes. Simple or complex shapes can
be rendered in solid or transparent colors, or using user-defined gradient or image
textures. Lines, open curves, and outline shapes are created using a Pen object. To
fill in an area, such as a rectangle or a closed curve, a Brush object is required. The
drawing methods are
DrawString(), DrawLine(), DrawRectangle(),
DrawEllipse(), DrawPie(), DrawPolygon(),
DrawArc()
and DrawImage(). Using DrawImage() we can display an image.
The method DrawString() takes five arguments
DrawString(string,Font,Brush,int X,int Y)
The first argument is a string, i.e. the text we want to display. The last two
arguments is the position where we put the string. The method DrawEllipse() is
given by
DrawEllipse(System.Drawing.Pen,float x,float y,float width,float height)
Every method in the Graphics class has to be accessed by creating an object of that
class. We can easily update the above program to render other graphical shapes like
Rectangle, Ellipse, etc. All we have to do is to apply the relevant methods appropriately.
96
7.1. DRAWING METHODS 97
Using the Pen class we can specify colour of the border and also the thickness. The
Pen class is applied for drawing shapes. The Brush is applied for filling shapes such
as SolidBrush and HatchStyleBrush.
The default Graphics unit is Pixel. By applying the PageUnit property, we can
change the unit of measurement to Inch and Millimeter.
// HelloGraphics.cs
using System;
using System.Drawing;
using System.Windows.Forms;
public class Hello : Form
{
public Hello()
{
this.Paint += new PaintEventHandler(f1_paint);
}
private void f1_paint(object sender,PaintEventArgs e)
{
Graphics g = e.Graphics;
g.DrawString("Hello C#",new Font("Verdana",20),new SolidBrush(Color.Tomato),
40,40);
g.DrawRectangle(new Pen(Color.Pink,3),20,20,150,100);
}
public static void Main()
{
Application.Run(new Hello());
}
}
The method
DrawPolygon(System.Drawing.Pen,new Point[]{
new Point(x,y),new Point(x,y),
new Point(x,y),new Point(x,y),
new Point(x,y),new Point(x,y)});
draws a polygon for a given set of points. The following program shows how do
draw two triangles using this method.
98 CHAPTER 7. GRAPHICS
// MyPolygon.cs
using System;
using System.Drawing;
using System.Windows.Forms;
class Triangle : Form
{
public Triangle()
{
this.Paint += new PaintEventHandler(draw_triangle);
}
public void draw_triangle(Object sender,PaintEventArgs e)
{
Graphics g = e.Graphics;
Pen pen1 = new Pen(Color.Blue,2);
Pen pen2 = new Pen(Color.Green,2);
g.DrawPolygon(pen1,new Point[]{new Point(150,50),
new Point(50,150),new Point(250,150)});
g.DrawPolygon(pen2,new Point[]{new Point(50,155),
new Point(250,155),new Point(250,255)});
}
public static void Main()
{
Application.Run(new Triangle());
}
}
The following program shows how to use
FillRectangle(Brush,float x,float y,float width,float height);
FillEllipse(Brush,float x,float y, float width,float height);
FillPie(Brush,float x,float y,float width,float height,float angleX,float angleY);
// Fill.cs
using System;
using System.Drawing;
using System.Windows.Forms;
public class Fill : Form
{
public Fill()
7.2. COLOR CLASS 99
{
this.Paint += new PaintEventHandler(fillpaint);
}
private void fillpaint(object sender,PaintEventArgs e)
{
Graphics g = e.Graphics;
g.FillRectangle(new SolidBrush(Color.Red),15,15,100,150);
g.FillEllipse(new SolidBrush(Color.Blue),50,50,150,120);
g.FillPie(new SolidBrush(Color.Yellow),200,200,40,40,0,90);
}
public static void Main()
{
Application.Run(new Fill());
}
}
7.2 Color Class
The Color class provides “constants” for common colors such as White, Black,
Blue, Red, Green, Pink. To create a Color structure from the specified 8-bit Color
(red,green,blue) we call for example
Color myColor = Color.FromArgb(0,255,125);
The alpha-value is implicit 255 (no transparency). To create a Color structure from
the four ARGB component (alpha,red,green,blue) we call for example
Color myColor = Color.FromArgb(51,255,0,0);
Alpha is also known as transparency where 255 is totally solid and 0 is totally
transparent.
// draw.cs
using System;
using System.Drawing;
using System.Windows.Forms;
public class Draw : Form
{
public Draw() { } // default constructor
protected override void OnPaint(PaintEventArgs e)
100 CHAPTER 7. GRAPHICS
{
FontFamily fontFamily = new FontFamily("Times New Roman");
Font font = new Font(fontFamily,24,FontStyle.Bold,GraphicsUnit.Pixel);
PointF pointF = new PointF(30,10);
SolidBrush solidbrush =
new SolidBrush(Color.FromArgb(51,255,0,0));
e.Graphics.DrawString ("Hello",font,solidbrush,pointF);
Pen myPen = new Pen(Color.Red);
myPen.Width = 50;
e.Graphics.DrawEllipse(myPen,new Rectangle(33,45,40,50));
e.Graphics.DrawLine(myPen,1,1,45,65);
e.Graphics.DrawBezier(myPen,15,15,30,30,45,30,87,20);
}
public static void Main()
{
Application.Run(new Draw());
}
}
In C# the user can choose a color by applying the ColorDialog class appropriatly.
First we have to create an object of ColorDialog class
ColorDialog cd = new ColorDialog();
An example is given in the followsing program
// ColorD.cs
using System;
using System.Drawing;
using System.Windows.Forms;
public class ColorD : Form
{
Button b = new Button();
TextBox tb = new TextBox();
ColorDialog clg = new ColorDialog();
public ColorD()
{
b.Click += new EventHandler(b_click);
b.Text = "OK";
tb.Location = new Point(50,50);
this.Controls.Add(b);
7.3. BUTTON AND EVENTHANDLER 101
this.Controls.Add(tb);
}
public void b_click(object sender,EventArgs e)
{
clg.ShowDialog();
tb.BackColor = clg.Color;
}
public static void Main(string[] args)
{
Application.Run(new ColorD());
}
}
7.3 Button and EventHandler
The Button class defines a Click event of type EventHandler. Inside the Button
class, the Click member is exactly like a private field of type EventHandler. However,
outside the Button class, the Click member can only be used on the left-hand
side of the += and -= operators. The operator += adds a handler for the event, and
the -= operator removes a handler for the event.
// Winhello.cs
using System;
using System.Windows.Forms;
using System.ComponentModel;
using System.Drawing;
class WinHello : Form
{
private Button bnclick;
public WinHello()
{
Text = "Hello World";
Size = new Size(400,400);
bnclick = new Button();
bnclick.Text = "Click.Me";
bnclick.Size = new Size(60,24);
bnclick.Location = new Point(20,60);
bnclick.Click += new EventHandler(bnclick_Click);
Controls.Add(bnclick);
Closing += new CancelEventHandler(WinHello_Closing);
102 CHAPTER 7. GRAPHICS
}
private void bnclick_Click(object sender,EventArgs ev)
{
MessageBox.Show("Hello Egoli!!!!","Button Clicked",
MessageBoxButtons.OK,MessageBoxIcon.Information);
}
private void WinHello_Closing(object sender,CancelEventArgs ev)
{
if(MessageBox.Show("Are you sure?","Confirm exit",
MessageBoxButtons.YesNo,MessageBoxIcon.Question)
== DialogResult.No) ev.Cancel = true;
}
// Initialize the main thread
// using Single Threaded Apartment (STA) model
public static void Main()
{
Application.Run(new WinHello());
}
}
We can create a Font selection dialog box using the FontDialog class. The following
program gives an example
// Fonts.cs
using System;
using System.Drawing;
using System.Windows.Forms;
public class Fonts : Form
{
Button b = new Button();
TextBox tb = new TextBox();
FontDialog flg = new FontDialog();
public Fonts()
{
b.Click += new EventHandler(b_click);
b.Text = "OK";
tb.Location = new Point(50,50);
this.Controls.Add(b);
this.Controls.Add(tb);
7.4. DISPLAYING IMAGES 103
}
public void b_click(object sender,EventArgs e)
{
flg.ShowDialog();
tb.Font = flg.Font;
}
public static void Main(string[] args)
{
Application.Run(new Fonts());
}
}
7.4 Displaying Images
Next we provide a program that displays images using the method DrawImage. The
file formats could be bmp, gif or jpeg.
// mydrawim.cs
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
public class Texturedbru : Form
{
public Texturedbru()
{
this.Text = "Using Texture Brushes";
this.Paint += new PaintEventHandler(Text_bru);
}
public void Text_bru(object sender,PaintEventArgs e)
{
Graphics g = e.Graphics;
Image bgimage = new Bitmap("forest.bmp");
g.DrawImage(bgimage,20,20,1000,600);
}
public static void Main()
{
Application.Run(new Texturedbru());
104 CHAPTER 7. GRAPHICS
}
}
Another option to display the picture is
// textbru.cs
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
public class Texturedbru : Form
{
Brush bgbrush;
public Texturedbru()
{
this.Text = "Using Texture Brushes";
Image bgimage = new Bitmap("forest.bmp");
bgbrush = new TextureBrush(bgimage);
this.Paint += new PaintEventHandler(Text_bru);
}
public void Text_bru(object sender,PaintEventArgs e )
{
Graphics g = e.Graphics;
g.FillEllipse(bgbrush,50,50,500,300);
g.FillEllipse(bgbrush,150,150,450,300);
g.FillRectangle(bgbrush,350,450,100,130);
}
public static void Main()
{
Application.Run(new Texturedbru());
}
}
7.5 Overriding OnPaint
The next program shows how to override OnPaint(). We create a Button and
clicking on it switches the color of the circle from red to blue and vice versa.
// MyOnPaint.cs
7.5. OVERRIDING ONPAINT 105
using System;
using System.Drawing;
using System.Windows.Forms;
class Draw : Form
{
private SolidBrush b = new SolidBrush(Color.Red);
public Draw()
{
Button button1 = new Button();
button1.Text = "Click Me";
button1.Location = new Point(210,220);
button1.Click += new EventHandler(HandleClick);
Controls.Add(button1);
}
protected override void OnPaint(PaintEventArgs e)
{
int diameter = 200;
int x = 50;
int y = 30;
if(b.Color == Color.Blue)
{
b.Color = Color.Red;
}
else
{
b.Color = Color.Blue;
}
e.Graphics.FillEllipse(b,x,y,diameter,diameter);
} // end OnPaint
void HandleClick(object sender,EventArgs e)
{
this.Refresh();
}
public static void Main()
{
Application.Run(new Draw());
}
}
106 CHAPTER 7. GRAPHICS
Another example we consider a rotation line. We call the Invalidate() method to
force a repaint at the end of the frame.
// Rotate.cs
using System.Windows.Forms;
using System.Drawing;
using System.Drawing.Drawing2D;
using System;
class TimerVector : Form
{
float rot;
public static void Main()
{
Application.Run(new TimerVector());
}
private void TimerEvent(Object myObject,EventArgs myEventArgs)
{
Invalidate();
}
protected override void OnPaint(PaintEventArgs pea)
{
Graphics g = pea.Graphics;
GraphicsState gs = g.Save();
Pen myPen = new Pen(Color.Black,3);
float x1 = ClientSize.Width/4;
float y1 = ClientSize.Height/4;
float x2 = (ClientSize.Width*3)/4;
float y2 = (ClientSize.Height*3)/4;
float centerx = ClientSize.Width/2;
float centery = ClientSize.Height/2;
g.TranslateTransform(-centerx,-centery);
g.RotateTransform(rot,MatrixOrder.Append);
g.TranslateTransform(centerx,centery,MatrixOrder.Append);
g.SmoothingMode = SmoothingMode.AntiAlias;
g.DrawLine(myPen,x1,y1,x2,y2);
g.Restore(gs);
rot = (rot + 1)%360;
}
public TimerVector()
{
7.5. OVERRIDING ONPAINT 107
rot = 0.0f;
Timer t = new Timer();
t.Interval = 100;
t.Tick += new EventHandler(TimerEvent);
t.Start();
}
}
Another example is
// Flicker.cs
using System;
using System.Drawing;
using System.Windows.Forms;
class Flicker : Form
{
private Timer t = new Timer();
private Size playerSize = new Size(50,50);
private Point playerPosition = new Point(0,0);
public Flicker()
{
ClientSize = new Size(500,500);
SetStyle(ControlStyles.DoubleBuffer,true);
SetStyle(ControlStyles.UserPaint,true);
SetStyle(ControlStyles.AllPaintingInWmPaint,true);
t.Interval = 40;
t.Tick += new EventHandler(TimerOnTick);
t.Enabled = true;
this.KeyDown += new KeyEventHandler(OnKeyPress);
}
private void TimerOnTick(object sender,EventArgs e)
{
this.Refresh();
this.Text = DateTime.Now.ToString();
this.Text += " " + this.PlayerPosition.ToString();
}
private Point PlayerPosition
{
get { return this.playerPosition; }
108 CHAPTER 7. GRAPHICS
set
{
if(value.X < 0)
{
this.playerPosition.X = this.ClientSize.Width-this.playerSize.Width;
}
else if(value.X+this.playerSize.Width > this.ClientSize.Width)
{
this.playerPosition.X = 0;
}
else
{
this.playerPosition.X = value.X;
}
if(value.Y < 0)
{
this.playerPosition.Y = this.ClientSize.Height-this.playerSize.Height;
}
else if(value.Y+this.playerSize.Height > this.ClientSize.Height)
{
this.playerPosition.Y = 0;
}
else
{
this.playerPosition.Y = value.Y;
}
}
}
private void OnKeyPress(object sender,KeyEventArgs e)
{
if(e.KeyValue == 37)
{
this.PlayerPosition =
new Point(this.PlayerPosition.X-this.playerSize.Width,this.PlayerPosition.Y);
}
if(e.KeyValue == 38)
{
this.PlayerPosition =
new Point(this.PlayerPosition.X,this.PlayerPosition.Y-this.playerSize.Width);
}
if(e.KeyValue == 39)
{
this.PlayerPosition =
7.5. OVERRIDING ONPAINT 109
new Point(this.PlayerPosition.X+this.playerSize.Height,this.PlayerPosition.Y);
}
if(e.KeyValue == 40)
{
this.PlayerPosition =
new Point(this.PlayerPosition.X,this.PlayerPosition.Y+this.playerSize.Height);
}
}
protected override void OnPaint(PaintEventArgs e)
{
e.Graphics.FillRectangle(new SolidBrush(Color.Red),this.PlayerPosition.X,
this.playerPosition.Y,this.playerSize.Width,
this.playerSize.Height);
}
public static void Main()
{
Application.Run(new Flicker());
}
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment