2011-11-02 93 views
0

我想根據http://msdn.microsoft.com/en-us/library/aa327572%28v=vs.71%29.aspxhttp://www.switchonthecode.com/tutorials/csharp-snippet-tutorial-how-to-draw-text-on-an-image中的示例在某些形狀上繪製字符串。我使用C#,所以我需要在任何情況下PaintEventArgs e。但是,當我將其作爲參數插入DrawStringRectangleF(PaintEventArgs e)方法中時,它不是(如預期的那樣)直接識別。我導入System.Windows.Forms.PaintEventArgs和字段「表單」仍然不被識別?我該怎麼辦?在形狀上繪製文本

是否有任何其他更簡單的方式來分配形狀上的文字,我可以調整的樣式?

+0

您是否收到編譯器錯誤或運行時錯誤。如果是這樣,你是什麼? – fluent

回答

0

對於初學者來說,如果您使用的是WinForms,您可以通過重寫OnPaint方法並將控件樣式設置爲手動繪製來獲取圖形對象。像這樣

... .ctor() 
{ 
    ... 
    // indicate user will paint 
    SetStyle(ControlStyles.UserPaint, true); 

    // rest is optional if you want/need it 
    SetStyle(ControlStyles.AllPaintingInWmPaint, true); 
    SetStyle(ControlStyles.ResizeRedraw, true); 
    SetStyle(ControlStyles.OptimizedDoubleBuffer, true); 
    SetStyle(ControlStyles.Opaque, true); 
} 

protected override void OnPaint(PaintEventArgs p) 
{ 
    // depending on how you set the control styles, you might need 
    // this to draw the background of your control wit a call to the methods base 
    base.OnPaint(p); 

    Graphics g = p.Graphics; 
    // ... Do your painting here with g .... 
} 

但是,既然您也將此問題標記爲WPF,請注意,這不適用於wpf。我在這個主題上並不是很先進,但是我已經使用了UIElement.OnRender方法的重寫並取得了很好的結果。它會給你一個DrawingContext對象,而不是PaintEventArgs對象。但他們的工作方式大致相同。另外你不需要設置控制風格。

+0

問題是潛在的。它不適用於wpf,只適用於Windows窗體。因此我需要在wpf中找到相應功能的實現。任何接受的建議。 – arjacsoh

+0

壓倒一切如何實現?我還沒有管理它。 – arjacsoh

0

由於您使用的是WPF,因此只需將您的shapeTextBlock放置在允許控件重疊的容器中,如GridCanvas即可。

<Grid> 
    <Rectangle ... /> 
    <TextBlock Text="Test" 
       HorizontalAlignment="Center" VerticalAlignment="Center" /> 
</Grid>