Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 692
Trevor Elliott Avatar asked Oct 10 '22 18:10

Trevor Elliott


2 Answers

Try putting all your objects in a GraphicsPath instance first. It doesn't have a ScaleTransform method but you can transform the objects with GraphicsPath.Transform. You can pass a scaling matrix via Matrix.Scale.

like image 50
Ilian Avatar answered Oct 13 '22 12:10

Ilian


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
}
like image 24
Anders Forsgren Avatar answered Oct 13 '22 11:10

Anders Forsgren