2015-05-19 74 views
5

我正在繪製控件的繪製方法中的矩形。有一個縮放因子需要考慮,例如每個積極的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;

+3

我沒有發現這個問題的最佳解決方案是重複'MeasureString'通話,調整字體大小,直到你剛下適合的最大尺寸。 – Blorgbeard

+2

或者,您可以使用鼠標滾輪來影響字體大小,並在文本週圍繪製矩形而不是反過來。 – Blorgbeard

+0

@Blorgbeard非常感謝小費。我相信它會起作用。但我不知道HansPassant是否有解決方案:D –

回答

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