Monday, December 1, 2008

DRAW STRING WITH MULTI LINES IN FIX RECTANGLE

·


using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Text;
using System.Runtime.InteropServices;
using System.Drawing.Drawing2D;



protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Color fontColor = Color.Yellow; // SET FONT COLOR
Color bg_Color = Color.Blue; // SET BACKGROUNG COLOR
bool fontBold = false;
bool fontItalic = false;
bool fontUnderline = false;
string[] strArray = new string[4];
strArray[0] = "My";
strArray[1] = "Name";
strArray[2] = "is";
strArray[3] = "Khan";

string fontFamily = "impact"; // FONT FAMILY
int w = 600; // IMAGE WIDTH
int h = 600; // IMAGE HEIGHT
int noOfLines = strArray.Length;

SolidBrush color;
FontStyle fontStyle = FontStyle.Regular;
if (fontBold) fontStyle |= FontStyle.Bold;
if (fontItalic) fontStyle |= FontStyle.Italic;
if (fontUnderline) fontStyle |= FontStyle.Underline;

Rectangle target = new Rectangle(0, 0, w, h); // GET TARGET RECTANGLE
Bitmap bitmap = new Bitmap(w, h);
Graphics g = Graphics.FromImage(bitmap);
color = new SolidBrush(bg_Color);
g.FillRectangle(color, target); // FILL BACKGROUND
g.SmoothingMode = SmoothingMode.AntiAlias;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;

int trgheight = target.Height / noOfLines;
int x = 3; // LEAVE SPACE TO LEFT,TOP,RIGHT AND BOTTOM OF IMAGE
int tLeft = target.Left + x;
int tTop = target.Top + x;
int tRight = target.Right - x;
int tBottom = target.Bottom - x;


Font the_font = new Font(fontFamily, trgheight, fontStyle, GraphicsUnit.Pixel);

StringFormat sf = new StringFormat();
sf.LineAlignment = StringAlignment.Center;
sf.Alignment = StringAlignment.Center;


GraphicsPath text_path = new GraphicsPath();

int useHeight = 0;
for (int count = 0; count < noOfLines; count++)
{
text_path.AddString(strArray[count], the_font.FontFamily, (int)fontStyle, trgheight, new PointF(0, useHeight), sf);
useHeight += trgheight;
}


RectangleF text_rectf = text_path.GetBounds();

PointF[] target_pts = new PointF[3];
target_pts[0] = new PointF(tLeft, tTop);
target_pts[1] = new PointF(tRight, tTop);
target_pts[2] = new PointF(tLeft, tBottom);
//GET POINTS TO DRAW TEXT INTO RECTANGLE

g.Transform = new Matrix(text_rectf, target_pts);

color = new SolidBrush(fontColor);
g.FillPath(color, text_path);

g.ResetTransform();
text_path.Dispose();
sf.Dispose();
the_font.Dispose();
g.Dispose();
bitmap.Save(Server.MapPath("TextWithMultilines.png"), System.Drawing.Imaging.ImageFormat.Png); // SAVE IMAGE TO THE ROOT



}
}

0 comments: