将图像绘制成形状?

时间:2014-11-10 14:21:29

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

我已经制作了一个可以用作圆形/方形/三角形的用户控件,控件可以绘制边框(外部)并填充其内部边界(内部)

理解它:

enter image description here

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

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

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

enter image description here

我不是任何使用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函数(将它用于Circle,Square和Triangle)是这样的:

''' <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

1 个答案:

答案 0 :(得分:3)

您可以使用Graphics.SetClip GraphicsPath来设置裁剪区域。 更多信息:http://msdn.microsoft.com/en-us/library/0z994t06(v=vs.110).aspx

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

相关问题