// Demonstrates using a bitmap in memory to create
persisting Graphics.
//
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 Persisting_Graphics
{
public partial class fclsMain : Form
{
// Bitmap object to draw to.
private Bitmap m_objDrawingSurface;
public fclsMain()
{
InitializeComponent();
}
private void fclsMain_Load(object sender, EventArgs
e)
{
// Create a drawing surface with the same
dimensions
// as the client area of the form.
m_objDrawingSurface = new
Bitmap(this.ClientRectangle.Width,
this.ClientRectangle.Height,
System.Drawing.Imaging.PixelFormat.Format24
bppRgb);
InitializeSurface();
}
private void InitializeSurface()
{
Graphics objGraphics;
// Create a Graphics object that references the
bitmap and clear it.
objGraphics =
Graphics.FromImage(m_objDrawingSurface);
objGraphics.Clear(SystemColors.Control);
// Free up resources
objGraphics.Dispose();
}
private void fclsMain_Paint(object sender,
PaintEventArgs e)
{
Graphics objGraphics;
// you cant modify e.Graphics directly
objGraphics = e.Graphics;
// Draw the contents of the bitmap on the form.
objGraphics.DrawImage(m_objDrawingSurface, 0, 0,
m_objDrawingSurface.Width,
m_objDrawingSurface.Height);
// Free resources
objGraphics.Dispose();
}
private void btnDrawText_Click(object sender,
EventArgs e)
{
Graphics objGraphics;
Font objFont;
int intFontSize, intTextX, intTextY;
Random RandomGenerator = new Random();
// if no input has been entered, get out.
if (txtInput.Text == "")
return;
// Create a Graphics object using the memory
bitmap.
objGraphics =
Graphics.FromImage(m_objDrawingSurface);
// Create a random number for the font size,
keep between 8 & 48.
intFontSize = RandomGenerator.Next(8, 48);
// random number for text X coord.
intTextX = RandomGenerator.Next(0,
this.ClientRectangle.Width);
// random number for text Y coord.
intTextY = RandomGenerator.Next(0,
this.ClientRectangle.Height);
// Create a new font object
objFont = new Font("Ariel", intFontSize,
FontStyle.Bold);
// Draw the users text
objGraphics.DrawString(txtInput.Text, objFont,
Brushes.Red, intTextX, intTextY);
// Clean up
objGraphics.Dispose();
// force the form to paint it self.
this.Invalidate();
}
private void fclsMain_FormClosed(object sender,
FormClosedEventArgs e)
{
// Free up global object on form closed
m_objDrawingSurface.Dispose();
}
}
}