It shows how to draw text stretched to fit a rectangle precisely in C#.NET.
keywords: stretch text, Graphics, DrawString, GraphicsPath, draw text, draw string, text, text size, C#.NET
It helps to draw a text completely streched to your frame. it Works with the help of Graphics Objects Measuring String
You have to import a namespace.
using System.Drawing.Drawing2D;
Drawing.Drawing2D
The System.Drawing.Drawing2D namespace provides advanced two-dimensional and vector graphics functionality.
Here the complete code.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
namespace testc
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
// Get the target area.
{
Rectangle target = new Rectangle(8, 8, this.ClientSize.Width - 16,
this.ClientSize.Height - 16);
Font the_font = new Font("Times New Roman", target.Height,
FontStyle.Bold, GraphicsUnit.Pixel);
// Make the StringFormat.
StringFormat sf = new StringFormat();
sf.Alignment = StringAlignment.Center;
sf.LineAlignment = StringAlignment.Center;
// Add the text to the GraphicsPath.
GraphicsPath text_path = new GraphicsPath();
text_path.AddString("Hello .NET World", the_font.FontFamily,
Convert.ToInt32(FontStyle.Bold), target.Height, new PointF(0, 0), sf);
RectangleF text_rectf = text_path.GetBounds();
PointF[] target_pts = {
new PointF(target.Left, target.Top),
new PointF(target.Right, target.Top),
new PointF(target.Left, target.Bottom)};
e.Graphics.Transform = new Matrix(text_rectf, target_pts);
// Draw the text.
e.Graphics.Clear(this.BackColor);
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
e.Graphics.FillPath(Brushes.Blue, text_path);
e.Graphics.DrawPath(Pens.Blue, text_path);
e.Graphics.ResetTransform();
//It draws the boundry for the text.
e.Graphics.DrawRectangle(Pens.Red, target);
// to clear the graphics.
text_path.Dispose();
sf.Dispose();
the_font.Dispose();
}
}
}
}
I'm so happy to read this. This is the kind of manual that needs to be given and not the accidental misinformation that is at the other blogs. Appreciate your sharing this best doc.
ReplyDeleteShun Pro 8-1/4-Inch Deba Knife