2010-06-06 92 views
10

XNA沒有任何支持圓繪圖的方法。
通常,當我不得不畫圓圈時,總是用相同的顏色,我只是用那個圓圈做出圖像,然後我可以將它顯示爲精靈。
但是現在在運行時指定了圓的顏色,任何想法如何處理?如何在XNA中繪製具有特定顏色的圓?

+0

我記得在XNA的論壇上看到類似的東西。 – Mike 2010-06-06 10:48:23

回答

37

您可以簡單地用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; 
    } 
+0

我知道這個線程真的很老,但你的代碼爲我返回一個圓。你會通過任何改變知道我能如何解決這個問題嗎? – Weszzz7 2013-03-09 08:42:23

+13

@ Weszzz7,難道它不支持返回一個圓? – Cyral 2013-08-04 15:57:12