在矩形内绘制字符串的动态字体大小
本文关键字:动态 字体 字符串 绘制 | 更新日期: 2023-09-27 17:49:42
我正在用控件的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;
尝试使用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)
}