动态字体大小在矩形内绘制字符串

时间:2015-05-19 03:29:41

标签: c# .net winforms gdi+

我在控件的paint方法中绘制一个矩形。需要考虑缩放因子,例如每个正MouseWheel事件导致控件重绘,然后矩形变大。现在我在这个矩形中绘制一个字符串,但我无法弄清楚如何将文本的字体大小与文本应该在其中的矩形的增长或缩小相关联。

以下是我的代码的一些相关部分:

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;
}

缩放因子的硬编码简单乘法似乎在某些方面有效,但这不是我假设的最聪明的方法。 int size = 8 + _zoomFactor * 6;

1 个答案:

答案 0 :(得分:4)

尝试使用Graphics.ScaleTransform方法应用缩放系数。

示例:

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)
}