473,396 Members | 1,777 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

DrawString Graphics problem

I am trying to get to grips with some basic graphics, being new to C#.
I have this code (see below) in a simple project .. when I run it 6 text
strings are drawn, as I expected .. but this happens twice .. once with
a grey background and once with the white one.
Clearly I am missing something fundamental here.
Can anyone please explain.
TIA
===
Brian
=====
private void Form1_Paint(object sender, PaintEventArgs e)
{
this.BackColor = Color.White;
Graphics g = e.Graphics; // get a graphics object
Font ft = new Font("Arial", 30); // create a font ft
Brush br = new SolidBrush(Color.Tomato); // create a brush br
int y = 20;
for (int i = 0; i < 6; i++)
{
g.DrawString("Brian is texting a Window", ft, br, 30, y);
y += 50;
System.Threading.Thread.Sleep(1000); // pause for 1 sec
}
}
Jan 10 '08 #1
7 10026
On Thu, 10 Jan 2008 08:40:42 -0800, Brian Ward <br********@zetnet.co.uk>
wrote:
I am trying to get to grips with some basic graphics, being new to C#.
I have this code (see below) in a simple project .. when I run it 6 text
strings are drawn, as I expected .. but this happens twice .. once with
a grey background and once with the white one.
Clearly I am missing something fundamental here.
Your event handler is wrong.

First, you created a Font and a Brush, both of which need to be disposed
of when you're done with them.

Second, you _never_ ever want to do anything in a paint handler except
anything _directly_ related to drawing to the control. Calling
Thread.Sleep() is a _huge_ no-no. So is changing the background color for
the control.

I believe that what's going on in your case is that the change to the
background color won't take effect until you return from the paint
handler, because nothing else can happen to the control until the paint
handler is done. So you're stuck in the paint handler, drawing the string
six times using the old background color. Then you finally exit, which
allows the background color change to take effect, at which point another
redraw is signaled, causing you to draw the string six more times.

The basic .NET Forms painting outline is as follows:

* Write a paint handler (or override OnPaint()) that, given some state
for your control and/or data can always draw the complete state

* Write some code elsewhere that manages the state. For animation,
this usually involves some sort of timing mechanism that updates the state
at suitable intervals.

* Any time the state changes, call Control.Invalidate() to signal to
the framework that the display of that state needs to be updated. This
will result in your paint handler being called, at which time it will
completely draw the current state.

It is completely inappropriate to manage the state and/or timing of
animation from within the paint handler. Do not ever do this.

Pete
Jan 10 '08 #2
On Jan 10, 10:40 am, Brian Ward <brian.w...@zetnet.co.ukwrote:
I am trying to get to grips with some basic graphics, being new to C#.
I have this code (see below) in a simple project .. when I run it 6 text
strings are drawn, as I expected .. but this happens twice .. once with
a grey background and once with the white one.
Clearly I am missing something fundamental here.
Can anyone please explain.
TIA
===
Brian
=====
private void Form1_Paint(object sender, PaintEventArgs e)
{
this.BackColor = Color.White;
Graphics g = e.Graphics; // get a graphics object
Font ft = new Font("Arial", 30); // create a font ft
Brush br = new SolidBrush(Color.Tomato); // create a brush br
int y = 20;
for (int i = 0; i < 6; i++)
{
g.DrawString("Brian is texting a Window", ft, br, 30, y);
y += 50;
System.Threading.Thread.Sleep(1000); // pause for 1 sec
}

}
To add to what Peter has said, here is a site that might help you:

http://www.bobpowell.net

Chris
Jan 10 '08 #3
Funny, I was just about to suggest that myself ;-)
--
--
Bob Powell [MVP]
Visual C#, System.Drawing

Ramuseco Limited .NET consulting
http://www.ramuseco.com

Find great Windows Forms articles in Windows Forms Tips and Tricks
http://www.bobpowell.net/tipstricks.htm

Answer those GDI+ questions with the GDI+ FAQ
http://www.bobpowell.net/faqmain.htm

All new articles provide code in C# and VB.NET.
Subscribe to the RSS feeds provided and never miss a new article.
"Chris Dunaway" <du******@gmail.comwrote in message
news:53**********************************@v67g2000 hse.googlegroups.com...
On Jan 10, 10:40 am, Brian Ward <brian.w...@zetnet.co.ukwrote:
>I am trying to get to grips with some basic graphics, being new to C#.
I have this code (see below) in a simple project .. when I run it 6 text
strings are drawn, as I expected .. but this happens twice .. once with
a grey background and once with the white one.
Clearly I am missing something fundamental here.
Can anyone please explain.
TIA
===
Brian
=====
private void Form1_Paint(object sender, PaintEventArgs e)
{
this.BackColor = Color.White;
Graphics g = e.Graphics; // get a graphics object
Font ft = new Font("Arial", 30); // create a font ft
Brush br = new SolidBrush(Color.Tomato); // create a brush
br
int y = 20;
for (int i = 0; i < 6; i++)
{
g.DrawString("Brian is texting a Window", ft, br, 30, y);
y += 50;
System.Threading.Thread.Sleep(1000); // pause for 1 sec
}

}

To add to what Peter has said, here is a site that might help you:

http://www.bobpowell.net

Chris
Jan 11 '08 #4
On Jan 11, 4:56 am, "Bob Powell [MVP]" <b...@spamkillerbobpowell.net>
wrote:
Funny, I was just about to suggest that myself ;-)

--
--
Bob Powell [MVP]
Visual C#, System.Drawing

Ramuseco Limited .NET consultinghttp://www.ramuseco.com

Find great Windows Forms articles in Windows Forms Tips and Trickshttp://www.bobpowell.net/tipstricks.htm

Answer those GDI+ questions with the GDI+ FAQhttp://www.bobpowell.net/faqmain.htm

All new articles provide code in C# and VB.NET.
Subscribe to the RSS feeds provided and never miss a new article.

"Chris Dunaway" <dunaw...@gmail.comwrote in message

news:53**********************************@v67g2000 hse.googlegroups.com...
On Jan 10, 10:40 am, Brian Ward <brian.w...@zetnet.co.ukwrote:
I am trying to get to grips with some basic graphics, being new to C#.
I have this code (see below) in a simple project .. when I run it 6 text
strings are drawn, as I expected .. but this happens twice .. once with
a grey background and once with the white one.
Clearly I am missing something fundamental here.
Can anyone please explain.
TIA
===
Brian
=====
private void Form1_Paint(object sender, PaintEventArgs e)
{
this.BackColor = Color.White;
Graphics g = e.Graphics; // get a graphics object
Font ft = new Font("Arial", 30); // create a font ft
Brush br = new SolidBrush(Color.Tomato); // create a brush
br
int y = 20;
for (int i = 0; i < 6; i++)
{
g.DrawString("Brian is texting a Window", ft, br, 30, y);
y += 50;
System.Threading.Thread.Sleep(1000); // pause for 1 sec
}
}
To add to what Peter has said, here is a site that might help you:
http://www.bobpowell.net
Chris
Hi Bob,

I love your site! When will your book be out? ;)

I noticed on your site that you have started a WPF faq. Have had a
chance to use WPF much? What are your impressions of it compared to
GDI and GDI+ ?

Cheers,

Chris
Jan 11 '08 #5
Thanks for all this help .. Bob's site looks really good.
One more thing. I have another problem (always another!)
I am using protected override bool ProcessCmdKey to control the movement
of this circle (see below) by adjusting x and y values .. it works fine,
but I also want the circle to leave a trace behind it as it moves .. I
would think that writing to a Bitmap would be the thing, but I can't
seem to figure out how.
Any help again much appreciated
==
Brian
==

private void Form1_Paint(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
g.FillEllipse(Brushes.Blue, x, y, 20, 20);
g.Dispose()
}
Jan 12 '08 #6
On Sat, 12 Jan 2008 01:27:09 -0800, Brian Ward <br********@zetnet.co.uk>
wrote:
[...]
but I also want the circle to leave a trace behind it as it moves .. I
would think that writing to a Bitmap would be the thing, but I can't
seem to figure out how.
Any help again much appreciated
Well, the basic idea would be to create a Bitmap instance into which you
draw, using Graphics.FromImage() to get a Graphics instance you can use
for drawing the circle, then in your Paint handler draw the Bitmap instead
of the circle.

Assuming the size of your control never changes, this may be the easiest.
If you want to handle changes in the control size gracefully it gets more
complicated, at least partly just because you then need to decide what
behavior is "correct" for your application.

You could save the circles into a Metafile instead, which introduces its
own complexities but can avoid the resizing issue. Alternatively, you
could just keep your own list of circles as you add them, drawing all of
them one by one each time the control needs to be painted. And of course
you could use some combination of the above, such as using a Bitmap most
of the time, but still storing a list of the circles so that you can
recreate a new Bitmap at arbitrary sizes as the control changes without
worrying about how best to preserve previously drawn circles.

Basically, for small numbers of circles, just storing the circles
themselves is easiest and more efficient. As the number of circles goes
up, a solution that uses only a Bitmap becomes more efficient. There's a
large area of wiggle room in the middle where you can pretty much do it
however you prefer. :)

Pete
Jan 12 '08 #7
I was looking at this thread in review for a reply elsewhere, and I took
another look at this post. I'm embarassed that I didn't notice the
obvious bug, especially since it might have been introduced as a result of
a misunderstanding of a comment I made earlier. In particular:

On Sat, 12 Jan 2008 01:27:09 -0800, Brian Ward <br********@zetnet.co.uk>
wrote:
[...]
private void Form1_Paint(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
g.FillEllipse(Brushes.Blue, x, y, 20, 20);
g.Dispose()
}
Do _not_ dispose the Graphics instance. It is good and correct to dispose
objects that are disposable and which you created in your own code. But
the Graphics instance is passed to you in the event args and must remain
valid for other Paint event handlers. Don't call Dipose() on it.

Sorry for not noticing this earlier.

Pete
Jan 14 '08 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: DrDevious | last post by:
Maybe I am doing something wrong but has anyone else here noticed a difference in the positioning of text between the Graphics.DrawString method and the Win32 GDI DrawText function? My text is...
0
by: Marc Ouellette | last post by:
Hi All. In the code below it will output the text string that is using the text from txtTextToDraw.Text using the font properties of the lblFont. Then problem is that not matter the font size...
3
by: Rich | last post by:
Hello, I need to draw some text on a form. No problem .... e.Graphics.DrawString(drawString, drawFont, drawBrush, x, y, drawFormat) My problem is that I want to draw the text on top of some...
3
by: Allen | last post by:
I've got a control that you can resize the contents of one of the text fields inside it. When the contents are resized to smaller than the text, I remove some of the end of the text and...
3
by: =?Utf-8?B?SlIx?= | last post by:
I would like to add text to an image. I have tried to use DrawString and it works on some images but on others it is very very small. I am pretty sure it has something to do with the size of the...
2
by: ChrisNightingale | last post by:
Hi everybody, I have an odd issue which I'm not sure how to resolve. I'm basically implementing a print mechanism which takes a series of controls and reproduces them on a print document. So...
2
by: Tony Johansson | last post by:
Hello! If I use the DrawString below with object of StringFormat as the last object it works good. If I instead remove object StringFormat below as the last object of DrawString I get some rows...
6
vekipeki
by: vekipeki | last post by:
I am having a problem with basic drawing of unicode characters in Windows 2000 and XP. I have written a simplest possible C# WinForms program to test it (just create a new Windows Forms C#...
6
by: Dilip | last post by:
Howdy Folks I have a display where the Graphics.DrawString function is called to display something. Since the text seems to be larger than its bounding rectangle, the call basically splits the...
3
by: arunman | last post by:
Hi, Im writing a C# .Net application to print in zebra 2030 thermal receipt printer (Uses 80 mm wide paper). I'm using the windows Graphics object for printing. string text = "Line1\n ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.