Search code examples
c#graphicsgdi+scaletransform

Alternative to Graphics.ScaleTransform


I am doing custom drawing using the GDI+.

Normally if I want to fit whatever I am drawing to the window, I calculate the appropriate ratio and I ScaleTransform everything by that ratio:

e.Graphics.ScaleTransform(ratio, ratio);

The problem with ScaleTransform is that it scales everything including pen strokes and brushes.

Hoe do I scale all of the pixel coordinates of what I'm drawing? Every line, rectangle, or path is basically a series of points. So I can multiply all of those points by the ratio manually, but is there an easy alternative to do this more seamlessly?


Solution

  • You can wrap the GDI graphics object and store the scale factor

    interface IDrawing
    {
       void Scale(float sx, float sy);
       void Translate(float dx, float dy);
       void SetPen(Color col, float thickness);
       void DrawLine(Point from, Point to);
       // ... more methods
    }
    
    class GdiPlusDrawing : IDrawing
    {
       private float scale;
       private Graphics graphics;
       private Pen pen;
    
       public GdiPlusDrawing(Graphics g)
       {
          float scale = 1.0f;
       }
    
       public void Scale(float s)
       {
           scale *= s;
           graphics.ScaleTransform(s,s);
       }
    
       public void SetPen(Color color, float thickness)
       {
           // Use scale to compensate pen thickness.
           float penThickness = thickness/scale;
           pen = new Pen(color, penThickness);   // Note, need to dispose.
       }
    
       // Implement rest of IDrawing
    }