2011-11-02 73 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>