【问题标题】:Get the ownercontrol of a graphics object?获取图形对象的所有者控件?
【发布时间】:2014-10-13 15:04:40
【问题描述】:

可以知道Graphics 对象的ownercontrol 吗?

在此方法中,我将控件的图形对象连同控件的宽度和高度一起传递给自定义方法:

Private Sub PictureBox1_Paint(ByVal sender As Object, ByVal e As PaintEventArgs) _
Handles PictureBox1.Paint

    Me.MyMethod(g:=e.Graphics, Width:=sender.width, Height:=sender.height)

End Sub

但我想避免将宽度和高度参数传递给我的方法(或传递控件),而是 MyMethod 应该仅通过图形对象找到控件宽度/高度,以防万一.

类似这样的伪代码:

private sub mymethod(byval g as graphics)

    dim _width as integer = g.GetControlWidth
    dim _height as integer = g.GetontrolHeight

end sub

【问题讨论】:

  • 你的问题的前提有缺陷:仅仅因为你在控件的绘制事件中获取了图形对象,并不意味着图形与它相关。 System.Drawing.Graphics 与控件没有直接关系。 MyMethod(g As Graphics, ctl As Control) 与您将得到的一样接近,并且仍然会在其他与绘制相关的事件(e.DrawBackGround、e.DrawFocusRect、e.PaintParentBackground 等)中丢失其他 e 事件参数。
  • 谢谢 plutonix 然后这个问题解决了,如果你愿意的话,发布一个答案

标签: .net vb.net winforms gdi+ gdi


【解决方案1】:

您的问题的前提存在缺陷:仅仅因为您在控件的绘制事件中获取了 Graphics 对象,并不意味着它们是相关的,或者您可以从 Graphics 获取控件。 System.Drawing.GraphicsControl 没有直接关系。尽可能接近的是:

MyMethod(g As Graphics, ctl As Control) 

即便如此,对于许多其他绘画和绘图事件,您将丢失那些e As xxxEventArgs 中的其他重要信息,例如e.DrawBackGrounde.DrawFocusRecte.ClipRectangle(有时比控件的大小更重要)e.PaintParentBackground等等。

有时您可以调用一个通用过程 - 例如绘制 3D 矩形或边框等 - 但当一个过程依赖于一个或多个计算出的常见参数时,这些通常是有价值的每个控件或正在绘制/绘制的东西:

Protected Sub Draw3DRect(g As Graphics, rect As Rectangle, bRaised As Boolean)

Protected Sub DrawBorder(g As Graphics, R As Rectangle)

Private Sub DrawThumb(g As Graphics, R As Rectangle)

一旦定义了 Rectangle,实际绘制或绘制的任何东西都是一样的,但 Rectangle 不一定与 Control 的 Size 相关。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-06
    • 1970-01-01
    • 2011-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-16
    相关资源
    最近更新 更多