Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic font size to draw string inside a rectangle

I am drawing a rectangle in the paint method of a control. There is a zoom factor to consider, e.g. each positive MouseWheel event causes the control to repaint and then the rectangle gets bigger. Now I am drawing a string inside this rectangle, but I couldn't figure out how to relate the font size of the text to the growth or shrinkage of the rectangle that the text is supposed to be inside it.

Here is some relevant part of my code:

public GateShape(Gate gate, int x, int y, int zoomFactor, PaintEventArgs p)
{
    _gate = gate;
    P = p;
    StartPoint = new Point(x, y);
    ShapeSize = new Size(20 + zoomFactor * 10, 20 + zoomFactor * 10);
    Draw();
}

public Bitmap Draw()
{

    #if DEBUG
    Debug.WriteLine("Drawing gate '" + _gate.GetGateType() + "' with symbol '" + _gate.GetSymbol() + "'");
    #endif

    Pen pen = new Pen(Color.Red);
    DrawingRect = new Rectangle(StartPoint.X, StartPoint.Y, ShapeSize.Width, ShapeSize.Height);
    P.Graphics.DrawRectangle(pen, DrawingRect);

    StringFormat sf = new StringFormat
    {
        Alignment = StringAlignment.Center,
        LineAlignment = StringAlignment.Center
    };
    using(Font font = new Font(FontFamily.GenericMonospace, 8)) //what to do here?
    P.Graphics.DrawString(_gate.GetSymbol(), font, Brushes.Black, DrawingRect, sf);

    return null;
}

A hardcoded simple multiplication by the zoom factor seems to some how work but this is not the smartest way I assume. int size = 8 + _zoomFactor * 6;

like image 543
Saeid Yazdani Avatar asked Sep 28 '22 22:09

Saeid Yazdani


1 Answers

Try using the Graphics.ScaleTransform method to apply your zoom factor.

Example:

public GateShape(Gate gate, int x, int y, float zoomFactor, PaintEventArgs p)
{
  _gate = gate;
  P = p;
  StartPoint = new Point(x, y);
  ShapeSize = new Size(20, 20);
  ZoomFactor = zoomFactor;
  Draw();
}

public Bitmap Draw()
{
  P.Graphics.ScaleTransform(ZoomFactor, ZoomFactor);
  ...
  // The rest of rendering logic should be the same (as is previously written)
}
like image 193
IronGeek Avatar answered Oct 06 '22 20:10

IronGeek