2011-11-28 77 views
3

我有我從內容管道加載的Texture2D。這是工作正常,但只要我嘗試在一個完全不同的Texture2D使用SetData都在我的遊戲中的紋理去完全是黑色的:Texture2D變黑

Normal

Black

這是我HUDMeter類,我想要的類

Texture2D colorGrad = Content.Load<Texture2D>(GradientAsset); 

Color[,] pixels = new Color[colorGrad.Width, colorGrad.Height]; 

Color[] pixels1D = new Color[colorGrad.Width * colorGrad.Height]; 

pixels = GetRedChannel(colorGrad); 

pixels1D = Color2DToColor1D(pixels, colorGrad.Width); 

System.Diagnostics.Debug.WriteLine(pixels[32,32]); 
Gradient = colorGrad; 
Gradient.SetData<Color>(pixels1D); 

這些是使用Riemers教程

是正當紅
protected Color[,] GetRedChannel(Texture2D texture) 
{ 
    Color[,] pixels = TextureTo2DArray(texture); 

    Color[,] output = new Color[texture.Width, texture.Height]; 

    for (int x = 0; x < texture.Width; x++) 
    { 
     for (int y = 0; y < texture.Height; y++) 
     { 
      output[x,y] = new Color(pixels[x,y].G, 0, 0); 
     } 
    } 

    return output; 
} 

protected Color[,] TextureTo2DArray(Texture2D texture) 
{ 
    Color[] colors1D = new Color[texture.Width * texture.Height]; 
    texture.GetData(colors1D); 

    Color[,] colors2D = new Color[texture.Width, texture.Height]; 
    for (int x = 0; x < texture.Width; x++) 
     for (int y = 0; y < texture.Height; y++) 
      colors2D[x, y] = colors1D[x + y * texture.Width]; 

    return colors2D; 
} 

private Color[] Color2DToColor1D (Color[,] colors, int width) 
{ 
    Color[] output = new Color[colors.Length]; 

    for (int x = 0; x < width; x++) 
    { 
     for (int y = 0; y < colors.Length/width; y++) 
     { 
      output[x + y * width] = colors[x % width, y % (colors.Length/width)]; 
     } 
    } 

    return output; 
} 

這裏是繪製精靈的代碼,這工作得很好,是我怎麼總是吸引精靈:

batch.Draw(meter.Gradient, new Vector2(X, Y), Color.White); 

更新:

其實我已經發現,精靈,唐」 t使用相同的文件不是黑色的。 Texture2D.SetData <>()實際上是否改變了文件本身?那有什麼用?

更新:

我只是試圖利用阿爾法以及RGB和它的工作。我認爲其中一種轉換方法存在問題。

+2

代碼在哪裏? – ChrisF

+0

哦,對,可能有點困難。它分佈在3個類,但我可以發佈我使用SetData的方法(可能是錯誤的方式) – annonymously

+0

這將值得發佈*其中*這也被稱爲。 – ChrisF

回答

2

如果你這樣做:

Texture2D textureA = Content.Load<Texture2D>("MyTexture"); 
Texture2D textureB = Content.Load<Texture2D>("MyTexture"); 

兩個textureAtextureB指向同一個對象。所以如果你在其中一個上叫SetData,它會影響到他們兩個。這是因爲ContentManager保留已加載資源的內部列表,所以它不必繼續重新加載相同的資源。

的解決方案是創建相同大小的新Texture2D對象,調用GetDataContentManager加載的一個,然後在新的紋理SetData

例(未測試):

Color[] buffer = new Color[textureA.Width * textureA.Height]; 
Texture2D textureB = new Texture2D(textureA.GraphicsDevice, 
            textureA.Width, 
            textureA.Height); 
textureA.GetData(buffer); 
textureB.SetData(buffer); 

新的紋理Dispose()當你完成了它(例如:在你的Game.UnloadContent法)。但不要處理由ContentManager加載的那個(因爲,就像我說的那樣,它是一個共享對象;改爲使用ContentManager.Unload)。

+0

,你會介意給一些代碼示例 – annonymously

+0

我真的不知道如何使用的Texture2D SetData的和的GetData,它沒有任何意義存放在一維數組位圖 – annonymously

+1

上回收速度較慢,你有兩個數組訪問,而不是一個。而不是2DColorArray [X] [Y] [X(Y *寬)+]反正它從左至右然後從上到下就像一本書,那麼根本就ColorArray。 – ClassicThunder