【问题标题】:Draw image into shape?将图像绘制成形状?
【发布时间】:2014-11-10 14:21:28
【问题描述】:

我制作了一个可以用作圆形/正方形/三角形的用户控件,该控件可以绘制边框(外)并填充边框内的内容(内)

理解它:

边框是黑色,内部是红色。

好吧,现在我想在我的控件中添加一个功能,以使用图像填充形状的内部。

但是当我尝试使用图像仅填充该空间时,还会绘制形状的外部区域:

我不是使用 GDI+ 的专家,我该如何解决这个问题?

我需要用一个圆、一个正方形和一个三角形来做这个,我不知道这是否可以停止。

这是我用来用图像填充圆圈的代码:

Public Property InnerImage As Image = Image.FromFile("C:\random.jpg")

''' <summary>
''' Draws a circle on the specified <see cref="System.Drawing.Graphics"/> object.
''' </summary>
''' <param name="g">The <see cref="System.Drawing.Graphics"/> object to draw.</param>
Private Sub DrawCircle(ByRef g As Graphics)

    With g

        Using pen As New Pen(Me._BorderColor, Me._BorderWidth)

            Dim rect As Rectangle = Me.GetFigueRectangle(pen)

            ' Fill the circle using the image.
            If Me.InnerImage IsNot Nothing Then
                .DrawImage(Me.InnerImage, rect)

            Else ' Fill the circle using a solid colour.
                If Not Me._InnerColor = Color.Transparent Then

                    Using brush As New SolidBrush(Me._InnerColor)
                        .FillEllipse(brush, rect)
                    End Using

                End If ' Not Me._InnerColor = Color.Transparent

            End If

            ' Draw the circle border.
            .DrawEllipse(pen, rect)

        End Using ' pen As New Pen(Me._BorderColor, Me._BorderWidth)

    End With ' g

End Sub

GetFigueRectangle 函数(用于圆形、方形和三角形)是这样的:

''' <summary>
''' Gets a <see cref="System.Drawing.Rectangle"/> with the bounds fixed according to the specified <see cref="System.Drawing.Pen.Width"/>.
''' </summary>
''' <param name="pen">The <see cref="System.Drawing.Pen"/>.</param>
''' <returns>The <see cref="System.Drawing.Rectangle"/> with the bounds fixed.</returns>
Private Function GetFigueRectangle(ByVal pen As Pen) As Rectangle

    Return New Rectangle With
                {
                    .x = CInt(0.0F + (pen.Width / 2.0F)),
                    .y = CInt(0.0F + (pen.Width / 2.0F)),
                    .width = CInt(MyBase.Width - pen.Width),
                    .height = CInt(MyBase.Height - pen.Width)
                }

End Function

【问题讨论】:

  • 查看建议的副本。您需要以相反的方式进行:使用由源位图制成的画笔绘制所需的形状(例如圆形)。
  • 谢谢,我会试试的,但请注意我的图像被拉伸了...

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


【解决方案1】:

您可以使用带有GraphicsPathGraphics.SetClip 来设置剪辑区域。 更多信息在这里:http://msdn.microsoft.com/en-us/library/0z994t06(v=vs.110).aspx

这将允许您将绘图剪辑成您能想到的任何可能的形状。实际上只会绘制路径内的像素。

【讨论】:

  • 谢谢,工作完美,只是一个小问题:在任何更改之前恢复原始剪辑的方法是“Resetclip”还是其他方法(例如 excludeclip 或...)?
  • .ResetClip 将清除当前剪辑区域,以便重新绘制所有像素,就像没有设置剪辑区域一样。如果您想要恢复之前的剪辑区域集,则应在更改剪辑之前将 Graphics.Clip 存储在变量中,然后在完成绘制后再次将其 .SetClip 恢复。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-10
相关资源
最近更新 更多