It shows how to draw font at different sizes in C#.NET
Keywords: C#.NET, CSharp.NET, Font, DrawString.
When the program receives a Paint event, the code clears the graphics context. It then loops over a series of font sizes. For each size, it creates a new Font object at that size. It uses the object's Height property to see if we have room to fit the next line of text on the form. If we are too close to the bottom of the form, the code uses the graphics context's MeasureString method to see how wide the string WWWW is and adds that amount to the next string's X coordinate.
Next the routine uses the graphics context's DrawString method to draw the text using the new font and a black brush. It finishes by increasing the Y coordinate for the next line of text.
Here the complete code to draw font.
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;
namespace testc
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Paint(object sender,
PaintEventArgs e)
{
Graphics gr = default(Graphics);
float font_size = 0;
float X = 0;
float Y = 0;
Font new_font = default(Font);
gr = e.Graphics;
gr.Clear(BackColor);
X = 0;
Y = 0;
for (font_size = 9.75f; font_size <= 30;
font_size += 0.75f)
{
// Get the next font.
new_font = new Font("Times New Roman", font_size);
// See if we have room.
if (Y + new_font.Height > this.ClientSize.Height)
{
// Start a new column.
Y = 0;
X += gr.MeasureString("WWWW", new_font).Width;
}
// Draw the text.
gr.DrawString(font_size.ToString(), new_font,
Brushes.Black, X, Y);
Y += new_font.Height;
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
No comments:
Post a Comment