Changes

Jump to: navigation, search

Using Bitmaps for Persistent Graphics in C Sharp

2 bytes added, 20:27, 1 April 2009
no edit summary
In the previous chapter we explained that simply drawing graphics on a component in C# is not sufficient to ensure the graphics will remain if part or all of the window containing the graphics is obscured by another window. In such situations the application will not know to redraw the erased graphics once the obscured section of the window is uncovered. To address this problem we used the ''Paint()'' method of the component to ensure that the draw commands were executed again when the ''Paint()'' event was triggered. This approach works well for simple, pre-defined graphics but is not suitable for complex drawings or situations where different graphics are drawn each time the application runs (for example the graphics may be drawn based on interaction with the user).
To address such situations it is preferable to draw the graphics on a bitmap residing in memory which can be rendered on a component whenever the a ''Paint()'' event is triggered. This avoids the problem of having to call all the Draw methods or store and replay a complex sequence of draw commands each time the graphics need to be refreshed.
== Creating a Bitmap ==
The first step in this tutorial is to create a new Visual Studio Windows Form Application project named CSharpBitmap. Once the project is created , double click on the Form to display the source code. Within the class declaration for the form we need to add a Bitmap declaration called ''myBitmap'' as follows:
<pre>
</pre>
This bitmap will be used to store the graphics image in memeory memory ready to be displayed to the user.
== Instantiating a Bitmap and Creating a Graphics Object ==
== Changing the Background Color of a Bitmap ==
If you followed the tutorial you will now have a plum color circle drawn on a black background. The background is black because this is the default for a new Bitmap object and we made not no attempt change the color after we created the Graphics Object. Had we wanted a different background color we could have called the ''Clear()'' method of the bitmap's Graphics Object, passing in a new color:
<pre>

Navigation menu