this blog contains information for .net and sql stuffs. You can find various tips and tricks to overcome problem you may be facing in ...

Wednesday, May 26, 2010

Graphics with .net (Part -3)

Till now we got idea of how to create image and edit existing image. Now we are moving to add text data to our existing image or creating image where text is to be inserted as copyright logo or company’s initial.

To add text to any image, following things are required.

Object of Graphics

Object of Font

If require Object of Brush

Call Graphics.DrawString method and pass font and brush object.

Yes its very simple to add text to our image. Now let’s check out how to create Font object and how to write in image

Create object of Font
Font f = new Font(“Arial”,10,FontStyle.Bold);

Apart from above constructor Font class has more than 12 constructor, we can create FontFamily object and pass it to Font Constructor.

FontFamily ffm = new FontFamily(“Arial”);
Font f = new Font(ffm,10);

If we need to read type of font, we can do with help of FontConverter class. But their errors prone, as we don’t get any error at compile time. We don’t come to know any error till it throws Runtime exception.

FontConverter converter = new FontConverter();
Font f = (Font)converter.ConvertFromString("Arial, 12pt");

Write text To Image
Once font is created, we need to create object of brush to fill text with that color, or we can use Brushes if we don’t wish to create object of brush.

Graphics g = this.CreateGraphics();
Font f = new Font("Arial", 40, FontStyle.Bold);
g.DrawString("My Test String!", f, Brushes.Blue, 10, 10);

Above code will draw “My Test String!” in form with Blue color and bold style with Arial font family.

With help of StringFormat we can format string like its alignment, FormatFlags, LineAlignment, Traimming etc.

Alternatively, to add text to image saved in disk, load it by using any of the bitmap or image class then follow step to draw string on it.

After that call save method of image or bitmap class, that will store new modified image in disk.

No comments: