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.
  • 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
            • 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.

              A Offline
              A Offline
              AspDotNetDev
              wrote on last edited by
              #26

              I'm not sure it's a big deal. This seems to work fine:

              private void button1_Click(object sender, EventArgs e)
              {
              Random rnd = new Random((int)(DateTime.Now.Ticks % int.MaxValue));
              for (int i = 0; i < 100000; i++)
              {
              Graphics g = this.CreateGraphics();
              g.DrawEllipse(Pens.Blue, new Rectangle(rnd.Next(0, 50),
              rnd.Next(0, 50), rnd.Next(55, 100), rnd.Next(55, 100)));
              }
              }

              I'm sure it's not a bad idea to manually dispose of the Graphics object, but I'm not sure it's entirely necessary to make sure one does so.

              [Forum Guidelines]

              OriginalGriffO 1 Reply Last reply
              0
              • A AspDotNetDev

                I'm not sure it's a big deal. This seems to work fine:

                private void button1_Click(object sender, EventArgs e)
                {
                Random rnd = new Random((int)(DateTime.Now.Ticks % int.MaxValue));
                for (int i = 0; i < 100000; i++)
                {
                Graphics g = this.CreateGraphics();
                g.DrawEllipse(Pens.Blue, new Rectangle(rnd.Next(0, 50),
                rnd.Next(0, 50), rnd.Next(55, 100), rnd.Next(55, 100)));
                }
                }

                I'm sure it's not a bad idea to manually dispose of the Graphics object, but I'm not sure it's entirely necessary to make sure one does so.

                [Forum Guidelines]

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

                Don't forget that the Graphics object (along with Pens, Brushes, etc.) do not just allocate unmanaged memory - they also allocate GDI handles, which are a limited system resource. If you do not release them, there is no guarantee that your software will continue to work in all environments. Using Dispose on all applicable objects is considered good practice because it does reduce the chances of unpredictable failures now or in the future. On a side note: If your code executed only once a second, it would execute 100000 Graphics object creations in just over a day. How long would it last before it started to get problems? I dunno; that is the fun of memory leaks!

                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

                A 1 Reply Last reply
                0
                • OriginalGriffO OriginalGriff

                  Don't forget that the Graphics object (along with Pens, Brushes, etc.) do not just allocate unmanaged memory - they also allocate GDI handles, which are a limited system resource. If you do not release them, there is no guarantee that your software will continue to work in all environments. Using Dispose on all applicable objects is considered good practice because it does reduce the chances of unpredictable failures now or in the future. On a side note: If your code executed only once a second, it would execute 100000 Graphics object creations in just over a day. How long would it last before it started to get problems? I dunno; that is the fun of memory leaks!

                  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.

                  A Offline
                  A Offline
                  AspDotNetDev
                  wrote on last edited by
                  #28

                  OriginalGriff wrote:

                  If your code executed only once a second, it would execute 100000 Graphics object creations in just over a day.

                  Did you see the for loop? That's how many it creates per button click. There was not much of an increase in memory usage.

                  OriginalGriff wrote:

                  they also allocate GDI handles, which are a limited system resource

                  That might be a valid concern.

                  [Forum Guidelines]

                  OriginalGriffO 1 Reply Last reply
                  0
                  • A AspDotNetDev

                    OriginalGriff wrote:

                    If your code executed only once a second, it would execute 100000 Graphics object creations in just over a day.

                    Did you see the for loop? That's how many it creates per button click. There was not much of an increase in memory usage.

                    OriginalGriff wrote:

                    they also allocate GDI handles, which are a limited system resource

                    That might be a valid concern.

                    [Forum Guidelines]

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

                    aspdotnetdev wrote:

                    Did you see the for loop?

                    I did - but I've only had one cup of coffee this morning, and explained what I meant badly. What I meant was: In the real world, your code would not necessarily sit on a button click, but would react to what else is going on. If you had your drawing code in a method that was executed frequently (by a timer update, or other external event) then at a rate of one execution per second, 100000 Graphics object creations would happen in just over a day.

                    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

                    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