C# Graphics - Drawing Image on String Tutorial. Here we want to see how to you draw a string on an image. We will make use of the Graphics class to do this. But first we will load our image from the file system via the Image
class. That class provides with the FromFile()
method which allows us easily load our image onto memory from the filesystem.
Then we draw that image using the Graphics class. We also draw a frame around the image and fill the rectangle with some color.
Demo
Here's the demo:
Video Tutorial
You can also watch the video tutorial for this example:
Program.cs
Here's the full source code.
using System.Drawing;
using System.Windows.Forms;
namespace ImageFromFile
{
internal class Program : Form
{
private Pen p;
private SolidBrush brush;
private readonly SolidBrush blackBrush = new SolidBrush(Color.White);
private const string path = @"D:ResourcesImgscentaurus.jpg"; // change the path if needed
private Image image;
private Font font;
private void InitializeComponent()
{
SuspendLayout();
ClientSize = new Size(580, 520);
Text = "Centaurus";
ResumeLayout(false);
}
private void initializeStuff()
{
Color cP = Color.Gray;
Color cB = Color.LightGray;
p = new Pen(cP, 6);
brush = new SolidBrush(cB);
image = Image.FromFile(path);
font = new Font(new FontFamily("Times New Roman"), 20);
}
private void Sketch()
{
//Instantiate the Graphics class. This class encapsulates the GDI+ drawing surface
Graphics mGraphics = Graphics.FromHwnd(Handle);
//fill the interior of the rectangle. Pass the SolidBrush, and integers x,y, width and heigh
mGraphics.FillRectangle(brush, 4, 4, 520, 440);
//draw rectangle/frame. Pass pen, and integers x,y,width and height respectively
mGraphics.DrawRectangle(p, 4, 4, 520, 440);
//draw image. Pass the image object, and integers x, y,width and height
mGraphics.DrawImage(image, 33, 35, 400, 290);
//draw string. Pass text to draw, font, the brush, and two floats x and y
mGraphics.DrawString("Centaurus", font, blackBrush, 90, 95);
//Release resources occuppied by the Graphics object
mGraphics.Dispose();
}
protected override void OnPaint(PaintEventArgs pea)
{
Sketch();
}
public Program()
{
InitializeComponent();
initializeStuff();
}
private static void Main()
{
Application.Run(new Program());
}
}
}