Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. So I Tried Graphics Tonight For The First Time

So I Tried Graphics Tonight For The First Time

Scheduled Pinned Locked Moved C#
graphicshelpalgorithmsjsonquestion
29 Posts 8 Posters 5 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • A AspDotNetDev

    Som Shekhar wrote:

    Dispose the graphics object after you are done with it. This is a major source of memory leak.

    I've never heard that. Why would the Graphics object be a source for a memory leak?

    [Forum Guidelines]

    P Offline
    P Offline
    Pete OHanlon
    wrote on last edited by
    #6

    aspdotnetdev wrote:

    Why would the Graphics object be a source for a memory leak?

    Because it's using unmanaged resources (GDI+).

    "WPF has many lovers. It's a veritable porn star!" - Josh Smith

    As Braveheart once said, "You can take our freedom but you'll never take our Hobnobs!" - Martin Hughes.

    My blog | My articles | MoXAML PowerToys | Onyx

    1 Reply Last reply
    0
    • A AspDotNetDev

      Som Shekhar wrote:

      Dispose the graphics object after you are done with it. This is a major source of memory leak.

      I've never heard that. Why would the Graphics object be a source for a memory leak?

      [Forum Guidelines]

      OriginalGriffO Offline
      OriginalGriffO Offline
      OriginalGriff
      wrote on last edited by
      #7

      This gets a little complex, but: The Graphics object is a limited resource, which contains unmanaged memory. What that means is that it uses memory which is not on the normal C# heap, or the stack - it is in a different area completely, and the .NET garbage collector will not process it. When your method ends, the last reference to the object is destroyed, so it becomes available to be garbage collected - which is fine. But, the GC will only try to dispose of it when it runs short of managed memory - which could be in a few weeks time, you just don't know! In the meantime, all that unused, unmanaged memory is sitting there, being wasted. If you manually call Dispose() on your object when you are finished with it, the resources are released immediately, and all is well. The easiest way to do this is to wrap you object in a using block:

      using(Graphics g = CreateGraphics())
      {
      ... use the Graphics object
      }

      The system will then call Dispose at the end. I probably haven't explained this too well, but if you look in any reasonable book on C#, it will talk about it in loads more detail! BTW: I wouldn't do the drawing in the Button.Click event - do it in the Form.Paint event - which supplies you with a graphics context in e.Graphics - and use the Button.Click to set any parameters (such as where you want it, what color, etc.) then call Invalidate() to force a re-draw.

      I have learnt that you can not make someone love you, all you can do is stalk them and hope they panic and give in. Apathy Error: Don't bother striking any key.

      "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
      "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

      S A 2 Replies Last reply
      0
      • OriginalGriffO OriginalGriff

        This gets a little complex, but: The Graphics object is a limited resource, which contains unmanaged memory. What that means is that it uses memory which is not on the normal C# heap, or the stack - it is in a different area completely, and the .NET garbage collector will not process it. When your method ends, the last reference to the object is destroyed, so it becomes available to be garbage collected - which is fine. But, the GC will only try to dispose of it when it runs short of managed memory - which could be in a few weeks time, you just don't know! In the meantime, all that unused, unmanaged memory is sitting there, being wasted. If you manually call Dispose() on your object when you are finished with it, the resources are released immediately, and all is well. The easiest way to do this is to wrap you object in a using block:

        using(Graphics g = CreateGraphics())
        {
        ... use the Graphics object
        }

        The system will then call Dispose at the end. I probably haven't explained this too well, but if you look in any reasonable book on C#, it will talk about it in loads more detail! BTW: I wouldn't do the drawing in the Button.Click event - do it in the Form.Paint event - which supplies you with a graphics context in e.Graphics - and use the Button.Click to set any parameters (such as where you want it, what color, etc.) then call Invalidate() to force a re-draw.

        I have learnt that you can not make someone love you, all you can do is stalk them and hope they panic and give in. Apathy Error: Don't bother striking any key.

        S Offline
        S Offline
        Som Shekhar
        wrote on last edited by
        #8

        Wise men have already spoken. So, no need to answer the question asked about disposing. Your suggestion is right about doing the paint part in Form.Paint event. However, I don't see anything wrong in doing it in Button_Click for learning purposes. Doing all drawing during paint may become an herculean task. I prefer doing my drawing on a bitmap at different occasions and draw the bitmap during Form.Paint. This imitates double buffering and saves from doing any calculations that may be required in Form.Paint every time the form is painted.

        OriginalGriffO P 2 Replies Last reply
        0
        • R Roger Wright

          Big mistake... I've avoided it for decades, as Windows makes it so hard to do - at least through the eyes of a tyro. But it's time I learned it, and I sat down tonight intending to do so. I thought I'd start with drawing a simple circle on a form, and searching in Help returned a likely bit with sample code for drawing a rectangle and a circle within it, along with a button_Click handler to call the drawing function. I copied and pasted the sample code into my 800x600 form, just to try it out. Then I added a button1 object to provide the event. The code is:

          public partial class FlowCalcs : Form
          {
          public FlowCalcs()
          {
          InitializeComponent();
          }
          private void DrawIt()
          {
          System.Drawing.Graphics graphics = this.CreateGraphics();
          System.Drawing.Rectangle rectangle = new System.Drawing.Rectangle(
          100, 100, 200, 200);
          graphics.DrawEllipse(System.Drawing.Pens.Black, rectangle);
          graphics.DrawRectangle(System.Drawing.Pens.Red, rectangle);
          }
          private void button1_Click(object sender, EventArgs e)
          {
          DrawIt();
          }
          }

          When I debugged it, absolutely nothing happened - no rectangle, no circle, and no errors. I would welcome an error message, since occasionally Microsoft divulges some tiny bit of information that Google can find a solution for. But no such luck this time - it executes perfectly and does nothing. Can someone lend a clue to the clueless? I haven't any idea where to go next...

          "A Journey of a Thousand Rest Stops Begins with a Single Movement"

          D Offline
          D Offline
          DaveyM69
          wrote on last edited by
          #9

          Hi Roger, All the advice you've been given is correct. I just thought I'd put my 2c in... Graphics objects, Pens & Brushes should be disposed of unless they are available already as a property/parameter. If you draw in OnPaint you can use the e.Graphics property and there is no need to dispose it. If however you are drawing elsewhere and using CreateGraphics then you should dispose of it either explicitly, or implicitly by using a using block. The same for Pens and Brushes, if you are using the System ones as in your code then there is no need to dispose, but if you create your own then you must dispose of them. If it's a one off drawing I normally drop it into the OnPaint handler as has been suggested. If it's likely to be used several times I create a class/struct with a Draw method that takes any useful parameters including a Graphics instance and call that from OnPaint. Triggering OnPaint is easily done by calling Invalidate. Something like this gives you a reusable Rectangle/Ellipse that can be drawn easily and no memory leaks.

          using System;
          using System.Drawing;
          using System.Windows.Forms;

          public partial class FormFlowCalcs : Form
          {
          private RectangleWithEllipseUnfilled rectangleWithEllipseUnfilled;
          private Point rectangleWithEllipseUnfilledLocation;
          private bool rectangleWithEllipseUnfilledVisible;

          public FormFlowCalcs()
          {
              InitializeComponent();
              Size = new Size(800, 600);
              rectangleWithEllipseUnfilled = new RectangleWithEllipseUnfilled(
                  Color.Black, Color.Red, new Size(200, 200));
              rectangleWithEllipseUnfilledLocation = new Point(200, 200);
              rectangleWithEllipseUnfilledVisible = false;
          }
          
          private void buttonToggle\_Click(object sender, EventArgs e)
          {
              rectangleWithEllipseUnfilledVisible = !rectangleWithEllipseUnfilledVisible;
              Invalidate();
          }
          
          protected override void OnPaint(PaintEventArgs e)
          {
              base.OnPaint(e);
              if (rectangleWithEllipseUnfilledVisible)
                  rectangleWithEllipseUnfilled.Draw(rectangleWithEllipseUnfilledLocation, e.Graphics);
          }
          

          }

          public struct RectangleWithEllipseUnfilled
          {
          private Color ellipseColor;
          private Color rectangleColor;
          private Size size;

          public RectangleWithEllipseUnfilled(Color ell
          
          1 Reply Last reply
          0
          • S Som Shekhar

            Wise men have already spoken. So, no need to answer the question asked about disposing. Your suggestion is right about doing the paint part in Form.Paint event. However, I don't see anything wrong in doing it in Button_Click for learning purposes. Doing all drawing during paint may become an herculean task. I prefer doing my drawing on a bitmap at different occasions and draw the bitmap during Form.Paint. This imitates double buffering and saves from doing any calculations that may be required in Form.Paint every time the form is painted.

            OriginalGriffO Offline
            OriginalGriffO Offline
            OriginalGriff
            wrote on last edited by
            #10

            While Pete had explained that dispose should be used, he hadn't explained why, or how to best do it. I felt it worth a (slightly) more detailed response. The only problem with drawing in the Click event for learning purposes is that it can confuse more than elucidate - look at the number of "I drew it and it disappeared" questions we get. Starting off with drawing into the Paint event, with an existing Graphics context just makes it a bit easier for beginners. They can them be introduced to the concept of graphics contexts for other objects. :-D

            I have learnt that you can not make someone love you, all you can do is stalk them and hope they panic and give in. Apathy Error: Don't bother striking any key.

            "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
            "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

            S P 2 Replies Last reply
            0
            • OriginalGriffO OriginalGriff

              While Pete had explained that dispose should be used, he hadn't explained why, or how to best do it. I felt it worth a (slightly) more detailed response. The only problem with drawing in the Click event for learning purposes is that it can confuse more than elucidate - look at the number of "I drew it and it disappeared" questions we get. Starting off with drawing into the Paint event, with an existing Graphics context just makes it a bit easier for beginners. They can them be introduced to the concept of graphics contexts for other objects. :-D

              I have learnt that you can not make someone love you, all you can do is stalk them and hope they panic and give in. Apathy Error: Don't bother striking any key.

              S Offline
              S Offline
              Som Shekhar
              wrote on last edited by
              #11

              Hey, lemme say sorry for not writing in the correct grammar. What i said was:

              Som wrote:

              Wise men have already spoken. So, no need to answer the question asked about disposing.

              and what i meant Wise men have already spoken. So, I do not need to answer the question asked about disposing. he he he. I was talking about both of you. I do not deny that writing in Paint event is incorrect. I am only saying that it is not necessary and shouldn't be considered as a norm. Thats all. By the way, our so long discussion might be confusing the poor guy who wrote the code for the first time :laugh:

              1 Reply Last reply
              0
              • R Roger Wright

                Big mistake... I've avoided it for decades, as Windows makes it so hard to do - at least through the eyes of a tyro. But it's time I learned it, and I sat down tonight intending to do so. I thought I'd start with drawing a simple circle on a form, and searching in Help returned a likely bit with sample code for drawing a rectangle and a circle within it, along with a button_Click handler to call the drawing function. I copied and pasted the sample code into my 800x600 form, just to try it out. Then I added a button1 object to provide the event. The code is:

                public partial class FlowCalcs : Form
                {
                public FlowCalcs()
                {
                InitializeComponent();
                }
                private void DrawIt()
                {
                System.Drawing.Graphics graphics = this.CreateGraphics();
                System.Drawing.Rectangle rectangle = new System.Drawing.Rectangle(
                100, 100, 200, 200);
                graphics.DrawEllipse(System.Drawing.Pens.Black, rectangle);
                graphics.DrawRectangle(System.Drawing.Pens.Red, rectangle);
                }
                private void button1_Click(object sender, EventArgs e)
                {
                DrawIt();
                }
                }

                When I debugged it, absolutely nothing happened - no rectangle, no circle, and no errors. I would welcome an error message, since occasionally Microsoft divulges some tiny bit of information that Google can find a solution for. But no such luck this time - it executes perfectly and does nothing. Can someone lend a clue to the clueless? I haven't any idea where to go next...

                "A Journey of a Thousand Rest Stops Begins with a Single Movement"

                L Offline
                L Offline
                Luc Pattyn
                wrote on last edited by
                #12

                Hi Roger, I agree with what the others have said. And I add an example[^] that contains the relevant bits. :)

                Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles]


                I only read formatted code with indentation, so please use PRE tags for code snippets.


                I'm not participating in frackin' Q&A, so if you want my opinion, ask away in a real forum (or on my profile page).


                R S 2 Replies Last reply
                0
                • L Luc Pattyn

                  Hi Roger, I agree with what the others have said. And I add an example[^] that contains the relevant bits. :)

                  Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles]


                  I only read formatted code with indentation, so please use PRE tags for code snippets.


                  I'm not participating in frackin' Q&A, so if you want my opinion, ask away in a real forum (or on my profile page).


                  R Offline
                  R Offline
                  Roger Wright
                  wrote on last edited by
                  #13

                  Now I remember why I gave up trying to do any graphics work when Windows came out. :sigh:

                  "A Journey of a Thousand Rest Stops Begins with a Single Movement"

                  L 1 Reply Last reply
                  0
                  • S Som Shekhar

                    Wise men have already spoken. So, no need to answer the question asked about disposing. Your suggestion is right about doing the paint part in Form.Paint event. However, I don't see anything wrong in doing it in Button_Click for learning purposes. Doing all drawing during paint may become an herculean task. I prefer doing my drawing on a bitmap at different occasions and draw the bitmap during Form.Paint. This imitates double buffering and saves from doing any calculations that may be required in Form.Paint every time the form is painted.

                    P Offline
                    P Offline
                    PIEBALDconsult
                    wrote on last edited by
                    #14

                    Som Shekhar wrote:

                    I don't see anything wrong in doing it in Button_Click for learning purposes

                    For the most part yes, but many beginners get the idea that that is a "best practice" and never progress -- much like all the books that show data access in click handlers.

                    1 Reply Last reply
                    0
                    • L Luc Pattyn

                      Hi Roger, I agree with what the others have said. And I add an example[^] that contains the relevant bits. :)

                      Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles]


                      I only read formatted code with indentation, so please use PRE tags for code snippets.


                      I'm not participating in frackin' Q&A, so if you want my opinion, ask away in a real forum (or on my profile page).


                      S Offline
                      S Offline
                      Som Shekhar
                      wrote on last edited by
                      #15

                      Hey Luc, Is there any Graphics Library available for .Net which does more than what GDI+ does? I mean something that takes care of some advanced functions like layering? I have an interest in printing multiple png images with transparency, being able to drag and drop them. Also, having multiple layers like in Adobe Photoshop? Ofcourse I mean open source/free. Som

                      L P 2 Replies Last reply
                      0
                      • R Roger Wright

                        Big mistake... I've avoided it for decades, as Windows makes it so hard to do - at least through the eyes of a tyro. But it's time I learned it, and I sat down tonight intending to do so. I thought I'd start with drawing a simple circle on a form, and searching in Help returned a likely bit with sample code for drawing a rectangle and a circle within it, along with a button_Click handler to call the drawing function. I copied and pasted the sample code into my 800x600 form, just to try it out. Then I added a button1 object to provide the event. The code is:

                        public partial class FlowCalcs : Form
                        {
                        public FlowCalcs()
                        {
                        InitializeComponent();
                        }
                        private void DrawIt()
                        {
                        System.Drawing.Graphics graphics = this.CreateGraphics();
                        System.Drawing.Rectangle rectangle = new System.Drawing.Rectangle(
                        100, 100, 200, 200);
                        graphics.DrawEllipse(System.Drawing.Pens.Black, rectangle);
                        graphics.DrawRectangle(System.Drawing.Pens.Red, rectangle);
                        }
                        private void button1_Click(object sender, EventArgs e)
                        {
                        DrawIt();
                        }
                        }

                        When I debugged it, absolutely nothing happened - no rectangle, no circle, and no errors. I would welcome an error message, since occasionally Microsoft divulges some tiny bit of information that Google can find a solution for. But no such luck this time - it executes perfectly and does nothing. Can someone lend a clue to the clueless? I haven't any idea where to go next...

                        "A Journey of a Thousand Rest Stops Begins with a Single Movement"

                        P Offline
                        P Offline
                        PIEBALDconsult
                        wrote on last edited by
                        #16

                        I tried a little of that a while back, and found it not to be as straight-forward as I had hoped. I only needed to draw some lines and I got it working.

                        L 1 Reply Last reply
                        0
                        • R Roger Wright

                          Now I remember why I gave up trying to do any graphics work when Windows came out. :sigh:

                          "A Journey of a Thousand Rest Stops Begins with a Single Movement"

                          L Offline
                          L Offline
                          Luc Pattyn
                          wrote on last edited by
                          #17

                          Really? I don't find it hard at all, and Windows does a lot of things for you. You don't have to care about windows being partly hidden, getting uncovered, minimized, etc. It will repaint for you, assuming you did it right to start with. :)

                          Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles]


                          I only read formatted code with indentation, so please use PRE tags for code snippets.


                          I'm not participating in frackin' Q&A, so if you want my opinion, ask away in a real forum (or on my profile page).


                          1 Reply Last reply
                          0
                          • P PIEBALDconsult

                            I tried a little of that a while back, and found it not to be as straight-forward as I had hoped. I only needed to draw some lines and I got it working.

                            L Offline
                            L Offline
                            Luc Pattyn
                            wrote on last edited by
                            #18

                            Then don't stop; the first line is the hardest :laugh:

                            Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles]


                            I only read formatted code with indentation, so please use PRE tags for code snippets.


                            I'm not participating in frackin' Q&A, so if you want my opinion, ask away in a real forum (or on my profile page).


                            S P 2 Replies Last reply
                            0
                            • S Som Shekhar

                              Hey Luc, Is there any Graphics Library available for .Net which does more than what GDI+ does? I mean something that takes care of some advanced functions like layering? I have an interest in printing multiple png images with transparency, being able to drag and drop them. Also, having multiple layers like in Adobe Photoshop? Ofcourse I mean open source/free. Som

                              L Offline
                              L Offline
                              Luc Pattyn
                              wrote on last edited by
                              #19

                              I'm not experienced with any additional library, I tend to write the code I use myself. Mostly from reading forums like this one, I must warn you transparancy is a bit tricky in Windows. You may want to look to some of the graphics articles at CodeProject; and then there is GIMP which could inspire you. :)

                              Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles]


                              I only read formatted code with indentation, so please use PRE tags for code snippets.


                              I'm not participating in frackin' Q&A, so if you want my opinion, ask away in a real forum (or on my profile page).


                              R 1 Reply Last reply
                              0
                              • L Luc Pattyn

                                Then don't stop; the first line is the hardest :laugh:

                                Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles]


                                I only read formatted code with indentation, so please use PRE tags for code snippets.


                                I'm not participating in frackin' Q&A, so if you want my opinion, ask away in a real forum (or on my profile page).


                                S Offline
                                S Offline
                                Som Shekhar
                                wrote on last edited by
                                #20

                                naah.. the hardest part is to fight flickering ;) when anything u do in windows doesn't work :D

                                P 1 Reply Last reply
                                0
                                • OriginalGriffO OriginalGriff

                                  While Pete had explained that dispose should be used, he hadn't explained why, or how to best do it. I felt it worth a (slightly) more detailed response. The only problem with drawing in the Click event for learning purposes is that it can confuse more than elucidate - look at the number of "I drew it and it disappeared" questions we get. Starting off with drawing into the Paint event, with an existing Graphics context just makes it a bit easier for beginners. They can them be introduced to the concept of graphics contexts for other objects. :-D

                                  I have learnt that you can not make someone love you, all you can do is stalk them and hope they panic and give in. Apathy Error: Don't bother striking any key.

                                  P Offline
                                  P Offline
                                  Pete OHanlon
                                  wrote on last edited by
                                  #21

                                  He wasn't talking about me. He said wise. ;) Good explanation though and you might want to consider posting it as a tip/trick so that it can be easily linked to in response to other questions.

                                  "WPF has many lovers. It's a veritable porn star!" - Josh Smith

                                  As Braveheart once said, "You can take our freedom but you'll never take our Hobnobs!" - Martin Hughes.

                                  My blog | My articles | MoXAML PowerToys | Onyx

                                  1 Reply Last reply
                                  0
                                  • S Som Shekhar

                                    Hey Luc, Is there any Graphics Library available for .Net which does more than what GDI+ does? I mean something that takes care of some advanced functions like layering? I have an interest in printing multiple png images with transparency, being able to drag and drop them. Also, having multiple layers like in Adobe Photoshop? Ofcourse I mean open source/free. Som

                                    P Offline
                                    P Offline
                                    Pete OHanlon
                                    wrote on last edited by
                                    #22

                                    You might be able to do something with the Netron library available here[^].

                                    "WPF has many lovers. It's a veritable porn star!" - Josh Smith

                                    As Braveheart once said, "You can take our freedom but you'll never take our Hobnobs!" - Martin Hughes.

                                    My blog | My articles | MoXAML PowerToys | Onyx

                                    1 Reply Last reply
                                    0
                                    • L Luc Pattyn

                                      I'm not experienced with any additional library, I tend to write the code I use myself. Mostly from reading forums like this one, I must warn you transparancy is a bit tricky in Windows. You may want to look to some of the graphics articles at CodeProject; and then there is GIMP which could inspire you. :)

                                      Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles]


                                      I only read formatted code with indentation, so please use PRE tags for code snippets.


                                      I'm not participating in frackin' Q&A, so if you want my opinion, ask away in a real forum (or on my profile page).


                                      R Offline
                                      R Offline
                                      Roger Wright
                                      wrote on last edited by
                                      #23

                                      GIMP is what drove me to try drawing in Windows. :-O

                                      "A Journey of a Thousand Rest Stops Begins with a Single Movement"

                                      1 Reply Last reply
                                      0
                                      • S Som Shekhar

                                        naah.. the hardest part is to fight flickering ;) when anything u do in windows doesn't work :D

                                        P Offline
                                        P Offline
                                        PIEBALDconsult
                                        wrote on last edited by
                                        #24

                                        The hardest part was keeping them where I want them as the underlying control scrolls, horizontally and vertically. :sigh:

                                        1 Reply Last reply
                                        0
                                        • L Luc Pattyn

                                          Then don't stop; the first line is the hardest :laugh:

                                          Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles]


                                          I only read formatted code with indentation, so please use PRE tags for code snippets.


                                          I'm not participating in frackin' Q&A, so if you want my opinion, ask away in a real forum (or on my profile page).


                                          P Offline
                                          P Offline
                                          PIEBALDconsult
                                          wrote on last edited by
                                          #25

                                          Just don't go one toke over the line.

                                          1 Reply Last reply
                                          0
                                          Reply
                                          • Reply as topic
                                          Log in to reply
                                          • Oldest to Newest
                                          • Newest to Oldest
                                          • Most Votes


                                          • Login

                                          • Don't have an account? Register

                                          • Login or register to search.
                                          • First post
                                            Last post
                                          0
                                          • Categories
                                          • Recent
                                          • Tags
                                          • Popular
                                          • World
                                          • Users
                                          • Groups