Monday, December 1, 2008

DRAW STRING 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.Red; // SET FONT COLOR
bool fontBold = false;
bool fontItalic = false;
bool fontUnderline = false;
string text = "WELCOME"; // TEXT

string fontFamily = "impact"; // FONT FAMILY
int w = 600; // IMAGE WIDTH
int h = 300; // IMAGE HEIGHT

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);

g.SmoothingMode = SmoothingMode.AntiAlias;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;

int trgheight = target.Height;
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();

text_path.AddString(text, the_font.FontFamily, (int)fontStyle, trgheight, new PointF(0, 0), sf);
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("MyImage.png"), System.Drawing.Imaging.ImageFormat.Png); // SAVE IMAGE TO THE ROOT

}
}

0 comments: