Skip to main content
 首页 » 编程设计

c#之如何使用 C# 在二维平面中绘制球体

2024年02月06日18xiaohuochai

我正在使用以下代码片段绘制圆,在代码中我生成圆点。我想绘制球体,它们是否有生成球体点的逻辑?

for(double i=0.0;i<360;i++) 
{ 
double angle=i*system.Math.PI/180; 
int x=(int)(80+radius*system.math.cos(angle)); 
int y=(int)(80+radius*system.math.sin(angle)); 
putpixel(myGraphics,x,y,color.Red); 
} 

请您参考如下方法:

扩展 Drew's answer下面是一个使用 PathGradientBrush 和一组四种命名颜色的径向渐变画笔示例。要以不同颜色显示球体,最好在代码中创建颜色数组。

private void panel1_Paint(object sender, PaintEventArgs e) 
{ 
 
    Rectangle bounds = panel1.ClientRectangle; 
    using (var ellipsePath = new GraphicsPath()) 
    { 
        ellipsePath.AddEllipse(bounds); 
        using (var brush = new PathGradientBrush(ellipsePath)) 
        { 
            // set the highlight point: 
            brush.CenterPoint = new PointF(bounds.Width/3f, bounds.Height/4f); 
            ColorBlend cb = new ColorBlend(4); 
            cb.Colors = new Color[]  
               {  Color.DarkRed, Color.Firebrick, Color.IndianRed, Color.PeachPuff }; 
            cb.Positions = new float[] { 0f, 0.3f, 0.6f, 1f }; 
            brush.InterpolationColors = cb; 
            brush.FocusScales = new PointF(0, 0); 
 
            e.Graphics.FillRectangle(brush, bounds); 
        } 
    } 
 
} 

这会产生一个看起来像 3d 球体的圆圈..

更新:事实上,绘制球体的(基本上)相同代码可用于绘制漂亮的阴影。以下是更改:选择适合您需要的位置和大小,使用 3 种颜色的数组并使用黑色阴影和 alpha 值 maybe: 0,96,192,位置为 0f, 0.3f, 1f 。这样,阴影将全部半透明并在边缘逐渐淡出。我添加了一个带有木质背景的示例,以便您可以看到阴影是如何混合的。