Drawing Strings via the Graphics Object in C#
Submitted by Yorkiebar on Sunday, August 24, 2014 - 20:12.
Introduction:
This tutorial is on how to draw text in .NET (C#/Visual Basic).Labels, Textboxes?
I'm sure if you've not looked in to the 'graphics' (etc) objects in the .NET framework, you're thinking, why don't we just use labels or textboxes with their read-only property enabled. Labels and textboxes both have a surrounding area around the text which are both of different colours (however we could change this to the form background colour to give the effect of the backgrounds being removed), but would we create extra controls (labels, and textboxes) when we don't need to? That's consuming more resources than needed.Paint Events:
We are going to be using Form1's 'paint' event to draw the text to the screen. A paint event is a script which handles the drawing of the object, all controls in the .NET framework would have some form of 'paint' event otherwise they would not be drawn to the screen and updated every frame. So in essence, the paint event handles the drawing of it's parent (the control the event is linked with) each frame in order to show updates such as additional text, button click highlights, etc.Steps:
First create a new C#/Visual Basic project. I'll be using C# for this tutorial, then select 'Windows Form Project', give it a name and click 'Create'. Now double click on form1, click inside of the sub, then on the event panel drop down list where it currently says 'load', select 'paint'. A new 'Form1_paint' event will be created. In there, do the following...- protected override void OnPaint(PaintEventArgs e)
- {
- }
- string text = "Yorkiebar";
- Brush brush = Brushes.Black;
- e.Graphics.DrawString(text, font, brush, point);
Finished!
Here is the full source...- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.Windows.Forms;
- namespace GraphicsDrawing_Form
- {
- public partial class Form1 : Form
- {
- public Form1()
- {
- InitializeComponent();
- }
- protected override void OnPaint(PaintEventArgs e)
- {
- string text = "Yorkiebar";
- Brush brush = Brushes.Black;
- e.Graphics.DrawString(text, font, brush, point);
- }
- }
- }
Add new comment
- 148 views