XNA 没有任何支持圆绘制的方法。
通常,当我必须绘制圆圈时,总是使用相同的颜色,我只是用那个圆圈制作图像,然后我可以将其显示为 Sprite 。
但是现在圆圈的颜色是在运行时指定的,任何想法如何处理?
最佳答案
您可以简单地制作带有 Transparent
的圆形图像。背景和圆圈的彩色部分为 White
.然后,当涉及到在 Draw()
中绘制圆圈时方法,选择您想要的色调:
Texture2D circle = CreateCircle(100);
// Change Color.Red to the colour you want
spriteBatch.Draw(circle, new Vector2(30, 30), Color.Red);
只是为了好玩,这里是 CreateCircle 方法:
public Texture2D CreateCircle(int radius)
{
int outerRadius = radius*2 + 2; // So circle doesn't go out of bounds
Texture2D texture = new Texture2D(GraphicsDevice, outerRadius, outerRadius);
Color[] data = new Color[outerRadius * outerRadius];
// Colour the entire texture transparent first.
for (int i = 0; i < data.Length; i++)
data[i] = Color.TransparentWhite;
// Work out the minimum step necessary using trigonometry + sine approximation.
double angleStep = 1f/radius;
for (double angle = 0; angle < Math.PI*2; angle += angleStep)
{
// Use the parametric definition of a circle: http://en.wikipedia.org/wiki/Circle#Cartesian_coordinates
int x = (int)Math.Round(radius + radius * Math.Cos(angle));
int y = (int)Math.Round(radius + radius * Math.Sin(angle));
data[y * outerRadius + x + 1] = Color.White;
}
texture.SetData(data);
return texture;
}
关于colors - 如何在 XNA 中绘制具有特定颜色的圆圈?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2983809/