Vous êtes sur la page 1sur 9

This tutorial will show you how to draw pie and font in ASP.NET 2.

0 and
C# by using the classes of Graphics.
The class of Graphics provide the method of drawing to display device. F
or instance, the Rectangle, point and
others GDI+ basic components that can be assembled. The class of Pen is used fo
r drawing line and curve, while the classes
derived from the abstract class Brush can be used for fill the shape. The class
of FontFamily have the similar design, but
have a little bit of differences on modality.
First, you will need to import the System.Drawing, System.Drawing.Imagin
g, System.Drawing.Text namespace.
The namespace of system.Drawing provides the access to basic GDI+ graphi
c function. In the namespace of
System.Drawing.Drawing2D, System.Drawing.Imaging and System.Drawing.Text , .Net
provides more advanced functionalities.
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Text;
Need help with Windows Dedicated Hosting? Try Server Intellect. I'm a ha
ppy customer!
Create canvas and fill the background
Bitmap objBitmap;
Graphics objGraphics;
objBitmap = new Bitmap(400, 440);
objGraphics = Graphics.FromImage(objBitmap);

objGraphics.Clear(Color.White);
Draw the pie and fill
Pen p=new Pen(Color.Yellow,0);
Rectangle rect=new Rectangle(10,10,280,280);
objGraphics.DrawEllipse(p,rect);
Brush b1=new SolidBrush(Color.Red);
Brush b2=new SolidBrush(Color.Green);
Brush b3=new SolidBrush(Color.Blue);
objGraphics.FillPie(b1, rect, 0f, 60f);
objGraphics.FillPie(b2, rect, 60f, 150f);
objGraphics.FillPie(b3, rect, 210f, 150f);
Server Intellect assists companies of all sizes with their hosting needs
by offering fully configured server
solutions coupled with proactive server management services. Server Intellect sp
ecializes in providing complete
internet-ready server solutions backed by their expert 24/365 proactive support
team.
Draw font
FontFamily fontfml = new FontFamily(GenericFontFamilies.Serif);
Font font = new Font(fontfml, 16);
SolidBrush brush = new SolidBrush(Color.Blue);
objGraphics.DrawString("Drawing Graphics", font, brush, 70, 300);
Export and save to picture
objBitmap.Save(Response.OutputStream, ImageFormat.Gif);
objBitmap.Save(Server.MapPath("x.jpg"), ImageFormat.Jpeg);
We used over 10 web hosting companies before we found Server Intellect.
Their dedicated servers and add-ons were
setup swiftly, in less than 24 hours. We were able to confirm our order over the
phone. They respond to our inquiries
within an hour. Server Intellect's customer support and assistance are the best
we've ever experienced.
End drawing
objBitmap.Dispose();
objGraphics.Dispose();
--------------------------------------------------------------------------------
-------------------------------------
Working with GDI+ in ASP .NET
1/2/2005 11:46:55 AM
GDI+ (Graphics Device Interface) is the new interface for drawing Window
s graphics. It is used frequently in
Windows Applications but the nice thing is that they are also available in ASP .
NET Web Applications.

The best way to start is with an example.


Creating graphics on the fly is not rocket science when using ASP .NET.
First thing you need to do is add a using
directive in the code-behind file:
using System.Drawing.Imaging;
Next a new instance of the Bitmap object must be created in the WebForm1
class:
Bitmap Bmp;
We'll start by creating a new gif graphic with no background defined or
anything else. You can place this in the
Page_Load() event:
Bmp = new Bitmap(300, 200);
Bmp.Save(Response.OutputStream, ImageFormat.Gif);
We can see that the graphic is a rectangle with 300 width and 200 height
. The graphic is saved to the OutputStream
and therefore it is displayed in the web page when you compile the application.
Not much to see, just a black rectangle.
The important thing is that now you saw how a new graphic object is created.
We take one step at a time, and now we will change one little pixel on t
he graphic, just one. We do this by using
the SetPixel() method of the Bitmap object:
Bmp = new Bitmap(300, 200);
Bmp.SetPixel(20, 20, Color.Yellow);
Bmp.Save(Response.OutputStream, ImageFormat.Gif);
I think it's straightforward what this does, it sets a pixel at the spec
ified coordinates to the specified color
(in our case, yellow). 20, 20 are the coordinates of the pixel relative to the g
raphic. Run the web application and you can
see that in the left corner there's a small yellow dot, just as we expected.
Houston, we've got a problem. Maybe you spotted it or maybe not, but it
has to be fixed: in Internet Explorer, for
example, if you try to view the source of the page (WebForm1.aspx) you won't be
able. Also, if you try to see the name of
the graphic by right clicking it and choosing Properties you'll wonder to see th
at its name is WebForm1.aspx. It's true,
the name of the graphic is WebForm1.aspx and you can't view the source of the pa
ge because actually there is no page, it's
all a graphic, just like when you open a photo in the browser.
How can we fix this? Create a new WebForm (.aspx file) and inside it link the ol
d one (WebForm1.aspx) just like you would
do with any other graphic. So in the HTML of the second WebForm - in my case I r
enamed it to default.aspx - add a tag like
the following:
<img src="WebForm1.aspx">
Compile and open the file default.aspx. Now WebForm1.aspx is actually a
graphic inside default.aspx.
Now that we fixed that problem, we can continue with drawing using GDI+.
Let's draw a line in our graphic.
First, for drawing such objects, we need to create a new instance of Gra
phics object. So declare this in the class
of the WebForm1.aspx file:
Graphics Gfx;
Now place the following code right before the Save() method (after the S
etPixel() method if you want):
Gfx = Graphics.FromImage(Bmp);
Gfx.DrawLine(Pens.Aqua, 0, 0, 300, 200);
This code creates a diagonal from the left top corner of the rectangle t
o the lower right corner, it uses
DrawLine() to accomplish this. The prototype of DrawLine() we are using is DrawL
ine(System.Drawing.Pen pen, int x1, int y1,
int x2, int y2). The following graphic will help you understand how the coordina
tes work:

We set x1 to 0 and y1 to 0 so that the line starts in the left top corne
r of the rectangle. Then x2 was set to
pixel number 300 and y2 to 200, the far right bottom corner of the rectangle.
To add another diagonal from the right upper corner of the rectangle to
the left bottom corner, and form an X you
can use the following line:
Gfx.DrawLine(Pens.Aqua, 300, 0, 0, 200);
I recommend you play with these coordinates to fully understand how they
are positioned on the graphic.
Before moving one to creating something really useful using GDI+ and ASP
.NET let's see how you can write text in a
graphic.
For this, we first have to create a new instance of the Font object, alo
ng with the Bitmap and Graphics object, so
you should have the three:
Bitmap Bmp;
Graphics Gfx;
Font Fnt;
Inside the Page_Load() event, this is all the code we need:
Bmp = new Bitmap(300, 200);
Gfx = Graphics.FromImage(Bmp);
Fnt = new Font("Verdana", 12);
Gfx.DrawString("Hello world!", Fnt, Brushes.Yellow, 50, 50);
Bmp.Save(Response.OutputStream, ImageFormat.Gif);
You can see how the Font instance Fnt is set to the font style Verdana a
nd to size 12. Using the Graphics object we
draw the string on the graphic with yellow and at the coordinate x = 50 and y =
50. The result is the following:

Doing something useful with GDI+ and ASP .NET


Still, the purpose of this article is not to teach you GDI+, as GDI+ is
a vast subject and it's not something
specific to ASP .NET because it's being used in Windows applications also. Inste
ad here you must see how GDI+ can be
helpful when it is used with web applications. That's why now we shall create so
mething useful.
The code validator (name varies) is used to prevent automatic registrati
ons from web robots or to prevent other
actions that a web robot can take. We see validators almost everywhere when we h
ave to register or use some service on the
web. They are composed from a graphic which contains a small amount of character
s and numbers that the user must write in a
text box. If the characters match with the ones randomly generated in the graphi
c then it's clear that at the other end
there's a human and not a robot. We'll try to create this now using GDI+.
We'll be using the same files, WebForm1.aspx which actually is the graph
ic and default.aspx which is the web page.
I also suppose you have the using statement and the three object instances creat
ed (Bmp, Gfx and Fnt). We'll work inside
the Page_Load() event:
Random Rand = new Random();
// Create a new random number between the specified range
int RandNum = Rand.Next(10000, 99999);
Bmp = new Bitmap(90, 50);
Gfx = Graphics.FromImage(Bmp);
Fnt = new Font("Verdana", 12);
// Draw the random number
Gfx.DrawString(RandNum.ToString(), Fnt, Brushes.Yellow, 15, 15);
Bmp.Save(Response.OutputStream, ImageFormat.Gif);
This is all the code we need. A random number between 10000 and 99999 is
generated and displayed as a graphic so
robots can't pass it.

Now you would only need a text box where the visitor should type the num
ber and a few lines of code to compare it
with the random value inside RandNum.
I should mention that some smart robots use character recognition to rec
ognize the numbers in the graphic and paste
them in the text box. But we can confuse the character recognition system a bit
by adding some shapes in the background.
Using the following code two horizontal lines are added to the graphic t
hat try to fool the robot:
Random Rand = new Random();
int RandNum = Rand.Next(10000, 99999);
Bmp = new Bitmap(90, 50);
Gfx = Graphics.FromImage(Bmp);
Fnt = new Font("Verdana", 12, FontStyle.Bold);
Gfx.DrawString(RandNum.ToString(), Fnt, Brushes.Yellow, 15, 15);
// Create random numbers for the first line
int RandY1 = Rand.Next(0, 50);
int RandY2 = Rand.Next(0, 50);
// Draw the first line
Gfx.DrawLine(Pens.Yellow, 0, RandY1, 90, RandY2);
// Create random numbers for the second line
RandY1 = Rand.Next(0, 50);
RandY2 = Rand.Next(0, 50);
// Draw the second line
Gfx.DrawLine(Pens.Yellow, 0, RandY1, 90, RandY2);
Bmp.Save(Response.OutputStream, ImageFormat.Gif);
What this code basically does, is draw two lines with random Y (Y1 and Y
2) coordinates, so the results look similar
to this one:

The visitor still recognizes the numbers but the character recognition s
oftware might have some hard time with them. There are many other things you can
add to make the graphic fool even the smartest robot. You can play with adding
circles and other shapes to the background, drawing the characters with random c
olors or sizes and so on. Or you can add some random pixels to the graphic, arou
nd 100, using the following code:
int i;
// Repeat this process 100 times
for(i = 0; i < 100; i++)
{
// Set random position for the pixel
int RandPixelX = Rand.Next(0, 90);
int RandPixelY = Rand.Next(0, 50);
Bmp.SetPixel(RandPixelX, RandPixelY, Color.White);
}
The result being similar to the following:

What I like about GDI+ is that the only limit is your imagination, Micro
soft provides you with plenty methods and
properties in the GDI+ classes. If you're fascinated about GDI+ and its uses wit
h ASP .NET like I am, you can now explore
more by developing other useful things like a chart application.
There are some books covering in detail the subject of GDI+ with .NET, a
nd one that I can recommend is GDI+
Programming with C# by Mahesh Chand from Addison Wesley. It has 784 pages coveri
ng all you need to know about GDI+,
including manipulating images.
--------------------------------------------------------------------------------
------------------------------------------
he .NET Framework provides plenty of tools for us to create graphics, but it can
seem daunting at first. This tutorial will introduce you to the Drawing namespa
ce, and how we can get started drawing programmatically in VB.NET
In this example, we will be using a PictureBox control as our canvas, and we wil
l use buttons to draw different shapes for us.
The first thing that we can do is to arrange our form by adding the controls. We
will add a PictureBox control that will take up the majority of the form, and w
e will also increase the form's width by around double. We will then proceed to
add several buttons to the form, which will do the drawing for us. We will have
a button to draw a line, one to draw a rectangle, one to draw an arc, etc.
Once we have our form arranged, it may look something like this:

Click to enlarge.
We moved our web sites to Server Intellect and have found them to be incredibly
professional. Their setup is very easy and we were up and running in no time.
The next thing we need to do is to reference the assemblies we shall be using. W
e will be using the following namespaces, so they should be Imported accordingly
:
Imports System.Drawing
Imports System.Drawing.Drawing2D
Imports System.Windows.Forms
We chose Server Intellect for its dedicated servers, for our web hosting. They h
ave managed to handle virtually everything for us, from start to finish. And the
ir customer service is stellar.
Now we can begin writing our logic. Before we move onto the button click events,
we will want to declare a couple of variables. We need the pen that we will be
drawing with, and we also need to instantiate the System.Drawing.Graphics object
. We do this with the following:
Dim g As System.Drawing.Graphics
Dim pen1 As New System.Drawing.Pen(Color.Blue, 2)
We can now being drawing - or allowing our buttons to draw. We will create an ev
ent handler for the first button, and make it draw a line when it is clicked:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.Event
Args) Handles Button1.Click
g = PictureBox1.CreateGraphics
g.DrawLine(pen1, 250, 50, 400, 200)
End Sub
Yes, it is possible to find a good web host. Sometimes it takes a while. After t
rying several, we went with Server Intellect and have been very happy. They are
the most professional, customer service friendly and technically knowledgeable h
ost we've found so far.
Notice that the Graphics object, of which we created an instance, has built-in m
ethods such as DrawLine. All we need to do is called this method and feed it par
ameters (of which are pen, x1, y1, x2, y2).
Similarly, we use the following to draw an ellipse:
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.Event
Args) Handles Button2.Click
g = PictureBox1.CreateGraphics
g.DrawEllipse(pen1, 50, 50, 100, 150)
End Sub
We do similar code blocks for DrawRectangle, DrawArc, DrawPie and DrawBezier. On
e that is noticeably different is the DrawPolygon, as this requires a special pa
rameter (points() As System.Drawing.PointF). For this, we first set the values o
f each of our points, as follows:
Private Sub Button6_Click(ByVal sender As System.Object, ByVal e As System.Event
Args) Handles Button6.Click
Dim p(5) As System.Drawing.Point
p(0).X = 0
p(0).Y = 0
p(1).X = 53
p(1).Y = 111
p(2).X = 114
p(2).Y = 86
p(3).X = 34
p(3).Y = 34
p(4).X = 165
p(4).Y = 7
g = PictureBox1.CreateGraphics
g.DrawPolygon(pen1, p)
End Sub
If you're ever in the market for some great Windows web hosting, try Server Inte
llect. We have been very pleased with their services and most importantly, techn
ical support.
Because these buttons are passing static values as parameters, the drawings will
not change position. We can create a button that will clear the PictureBox cont
rol so we can start over. We do this by adding the following:
Private Sub Button8_Click(ByVal sender As System.Object, ByVal e As System.Event
Args) Handles Button8.Click
PictureBox1.Refresh()
End Sub
We are using Server Intellect and have found that by far, they are the most frie
ndly, responsive, and knowledgeable support team we've ever dealt with!
The entire code-behind will look something like this:
Imports System.Drawing
Imports System.Drawing.Drawing2D
Imports System.Windows.Forms
Public Class Form1
Dim g As System.Drawing.Graphics
Dim pen1 As New System.Drawing.Pen(Color.Blue, 2)
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.Event
Args) Handles Button1.Click
g = PictureBox1.CreateGraphics
g.DrawLine(pen1, 250, 50, 400, 200)
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.Event
Args) Handles Button2.Click
g = PictureBox1.CreateGraphics
g.DrawEllipse(pen1, 50, 50, 100, 150)
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.Event
Args) Handles Button3.Click
g = PictureBox1.CreateGraphics
g.DrawRectangle(pen1, 30, 30, 50, 60)
End Sub
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.Event
Args) Handles Button4.Click
g = PictureBox1.CreateGraphics
g.DrawArc(pen1, 150, 100, 150, 200, 150, 160)
End Sub
Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.Event
Args) Handles Button5.Click
g = PictureBox1.CreateGraphics
g.DrawPie(pen1, 50, 50, 150, 150, 0, 170)
End Sub
Private Sub Button6_Click(ByVal sender As System.Object, ByVal e As System.Event
Args) Handles Button6.Click
Dim p(5) As System.Drawing.Point
p(0).X = 0
p(0).Y = 0
p(1).X = 53
p(1).Y = 111
p(2).X = 114
p(2).Y = 86
p(3).X = 34
p(3).Y = 34
p(4).X = 165
p(4).Y = 7
g = PictureBox1.CreateGraphics
g.DrawPolygon(pen1, p)
End Sub
Private Sub Button7_Click(ByVal sender As System.Object, ByVal e As System.Event
Args) Handles Button7.Click
g = PictureBox1.CreateGraphics
g.DrawBezier(pen1, 100, 200, 240, 250, 100, 200, 150, 30)
End Sub
Private Sub Button8_Click(ByVal sender As System.Object, ByVal e As System.Event
Args) Handles Button8.Click
PictureBox1.Refresh()
End Sub
End Class
--------------------------------------------------------------------------------
---------------------------------------------

Vous aimerez peut-être aussi