Search code examples
c#winformsscalepanel

How to scale panel in C#


I'm making a graph with over 400 nodes and trying to draw them. The nodes are representation of cities so I took their longitude and latitude and set them as X and Y. The problem is that those cities are from one county so their longitude and latitude are pretty close to each other so even if I make the X and Y 10 times bigger they are still close to each other. The only thing is to increase the "resolution" to 100 times bigger but then, they won't be visible because the values are going up to 5000px

My question is: can I scale the panel so it will show everything, even if it's 5000px big? Or maybe there is a method scale the longitude and latitude so they'll be more spaced but still resemble the real life layout of the cities? Thak you


Solution

  • Given a set of points, take the min and max for X and the min and max for Y

    var minMaxX = new PointF(
        points.Min(point => point.X), 
        points.Max(point => point.X)
    );
    var minMaxY = new PointF(
        points.Min(point => point.Y), 
        points.Max(point => point.Y)
    );
    

    Then loop over each point, get the normalized point values for X and Y, then multiply by the corresponding viewport size values (width and height).

    var normalizedX = (point.X - minMaxX.X) / (minMaxX.Y - minMaxX.X);
    var normalizedY = (point.Y - minMaxY.X) / (minMaxY.Y - minMaxY.X);
    
    var posX = (int)(normalizedX * viewportWidth);
    var posY = (int)(normalizedY * viewportHeight);
    

    The above does not take into account the aspect ratio of the original points' rectangle, so your results will likely be squished. This can be solved using letter boxing or pillar boxing, depending on the width/height of the points rectangle compared to the viewport rectangle.