DrawString( ) Demo

The main work of displaying text is done by the DrawString( ) method. The DrawString( ) method has many overloads but what we have used here is this

public void DrawString(string, Font, Brush, float, float);

The first parameter represents the string to be draw. Second and third parameters specify the Font and Brush to draw with. The last two parameters represent the x and y coordinates of the desired point at which string will be drawn.

In this program we should be able to display text wherever we click with the mouse in the Form. Moreover the text should be of random Font, Color and Size.

We have to add the MouseDown event. The code to add in the handler looks like this:

protected void Form1_MouseDown (object sender, System.WinForms.MouseEventArgs e)

Graphics g = CreateGraphics( );
Random r = new Random ( );
int x, y ;
FontFamily[] f = FontFamily.Families ;
int i = r.Next ( f.GetUpperBound ( 0 ) ) ;

x = e.X ;
y = e.Y ;

Font myfont = new Font ( f[i] ,r.Next (14, 40 ) ) ;
Color c1 = Color.FromArgb ( r.Next(255), r.Next(255), r.Next(255));
SolidBrush mybrush = new SolidBrush ( c1 );
g.DrawString ( "Hello", myfont, mybrush, x,y );


As we want some attributes to be random we have used an object of the Random class. The Random class represents a random number generator. A mathematical function is used here to generate random numbers. The Next( ) method of this class returns a random number. If we pass an integer to this function it returns a positive random number less than the specified maximum range.

The Families property of the FontFamily class returns an array that contains all of the FontFamily objects associated with the current graphics context.

We have collected such a collection of font families in array f. To the Next( ) method we passed the upper bound of the array whose return value will be used as an index.

In x and y we store the x and y coordinates of the point where the mouse was pressed down.

To create a random Font object we have passed the randomly generated index. This will pick any one of the font families from the array. The Color of the Brush is also generated randomly every time. If we pass 255 as a parameter to the Next( ) method, it avoids generation of an invalid red, blue and green component. Now we can display the desired text at the x and y coordinates.

The output is :

Posted bySumedh at 9:31 PM  


Post a Comment