Draw 3D Balls

Divil

Well-known member
Joined
Nov 17, 2002
Messages
2,748
I just had to knock up a subroutine which draws simple 3d balls using PathGradientBrush so I thought Id post it here for anyone to use.

To use this code, just paste these two functions in to your existing form and the drawing will take effect.

Code:
    Private Sub Form1_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles MyBase.Paint
        e.Graphics.Clear(Color.White)

        Draw3DBall(e.Graphics, New Rectangle(10, 10, 250, 250), Color.FromArgb(227, 239, 254), Color.FromArgb(129, 169, 226))
        Draw3DBall(e.Graphics, New Rectangle(300, 50, 20, 20), Color.FromArgb(227, 239, 254), Color.FromArgb(129, 169, 226))
        Draw3DBall(e.Graphics, New Rectangle(320, 150, 100, 100), Color.FromArgb(236, 240, 213), Color.FromArgb(184, 198, 147))
    End Sub

    Private Sub Draw3DBall(ByVal graphics As Graphics, ByVal bounds As Rectangle, ByVal color1 As Color, ByVal color2 As Color)
        Enforce anti-aliasing
        Dim oldSmoothingMode As SmoothingMode = graphics.SmoothingMode
        graphics.SmoothingMode = SmoothingMode.AntiAlias

        Create the path used for drawing our ellipse
        Dim path As GraphicsPath = New GraphicsPath
        Dim ellipseBounds As Rectangle = bounds
        ellipseBounds.Offset(-Convert.ToInt32(bounds.Width * 0.2), -Convert.ToInt32(bounds.Height * 0.2))
        ellipseBounds.Inflate(Convert.ToInt32(bounds.Width * 0.3), Convert.ToInt32(bounds.Width * 0.3))
        path.AddEllipse(ellipseBounds)

        Create our brush and fill ellipse
        Dim brush As PathGradientBrush = New PathGradientBrush(path)
        brush.CenterColor = color1
        brush.SurroundColors = New Color() {color2}
        graphics.FillEllipse(brush, bounds)
        brush.Dispose()

        Restore old smoothing
        graphics.SmoothingMode = oldSmoothingMode
    End Sub
 

Attachments

Back
Top