How to prevent panel content from being erased upon scroll

I have a question regarding how I can prevent some content drawn on a panel control from being erased when a scroll action brings it out of view.

What I am trying to do is create a 2D tile-map editor. Whenever a mouse click event happens on the panel, a tile should get drawn onto the panel. I have this working fine. But if I place the object on the panel and scroll to one side, and scroll back, the object I had placed is gone.

I have done some research and I have seen suggestions on implementing the paint event. The problem is that I do not understand what to implement here. I think most of my struggles is coming from not fully understanding the Graphics object.

Here is some of my code:

     private void canvas_MouseClick(object sender, MouseEventArgs e)
     {
        Graphics g = canvas.CreateGraphics();

        float x1 = CommonUtils.GetClosestXTile(e.X);
        float y1 = CommonUtils.GetClosestYTile(e.Y);

        if (currentTile != null)
        {
            g.DrawImage(currentTile, x1, y1);
            me.AddTile((int)currX, (int)currY, (int)x1, (int)y1, "C:\\DemoAssets\\tileb.png");
        }
        else
        {
            // dont do anything
        }
        g.Dispose();
    }

    private void canvas_Paint(object sender, PaintEventArgs e)
    {
        // update here?
    }

Answers


To hold multiple Tiles, you'd need a List to hold each clicked location along with its associated tile:

    List<Tuple<Image, PointF>> Tiles = new List<Tuple<Image, PointF>>();

    private void canvas_MouseClick(object sender, MouseEventArgs e)
    {
        if (currentTile != null)
        {
            float x1 = CommonUtils.GetClosestXTile(e.X);
            float y1 = CommonUtils.GetClosestYTile(e.Y);
            Tiles.Add(new Tuple<Image, PointF>(currentTile, new PointF(x1, y1)));
            canvas.Refresh();

            me.AddTile((int)currX, (int)currY, (int)x1, (int)y1, "C:\\DemoAssets\\tileb.png");
        }
    }

    private void canvas_Paint(object sender, PaintEventArgs e)
    {
        foreach (Tuple<Image, PointF> tile in Tiles)
        {
            e.Graphics.DrawImage(tile.Item1, tile.Item2);
        }
    }

Need Your Help

Write huge XML file from DOM to file

java xml dom

I have a java program which queries a table which has millions of records and generates a xml with each record as node.

How can I slide a vertical SeekBar in a ScrollView

android android-layout android-scrollview android-event

I've made a vertical SeekBar by overriding the onDraw method and flipping it 90 degrees.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.