2011-04-25 46 views
2

我試圖理解模具。我可以用一個很好的教程解釋它們是如何工作的,但在這裏的平均時間到我的工作是什麼:試圖理解模具(XNA 4.0,Windows Phone 7)

DepthStencilState _StencilAlways; 
DepthStencilState _StencilKeepIfZero; 

SpriteBatch _StencilBatch; 
SpriteBatch _MaskBatch; 

_StencilAlways = new DepthStencilState(); 
_StencilAlways.StencilEnable = true; 
_StencilAlways.StencilFunction = CompareFunction.Always; 
_StencilAlways.StencilPass = StencilOperation.Replace; 
_StencilAlways.ReferenceStencil = 1; 
_StencilAlways.DepthBufferEnable = false; 

_StencilKeepIfZero = new DepthStencilState(); 
_StencilKeepIfZero.StencilEnable = true; 
_StencilKeepIfZero.StencilFunction = CompareFunction.Equal; 
_StencilKeepIfZero.StencilPass = StencilOperation.Keep; 
_StencilKeepIfZero.ReferenceStencil = 0; 
_StencilKeepIfZero.DepthBufferEnable = false; 

RenderTarget2D MaskRenderTarget = new RenderTarget2D(device, Width, Height, false, SurfaceFormat.Color, DepthFormat.Depth24Stencil8, 0, RenderTargetUsage.DiscardContents); 

GraphicsDevice.SetRenderTarget(MaskRenderTarget); 
GraphicsDevice.Clear(ClearOptions.Target | ClearOptions.Stencil, new Color(0, 0, 0, 1), 0, 0); 

_MaskBatch.Begin(SpriteSortMode.Immediate, null, null, _StencilAlways, null); 
_MaskBatch.Draw(
    Texture, 
    Position, 
    null, 
    Shade, 
    0, 
    Vector2.Zero, 
    Scale, 
    SpriteEffects.None, 
    0); 
_MaskBatch.End(); 

_StencilBatch.Begin(SpriteSortMode.Immediate, null, null, _StencilKeepIfZero, null); 
_StencilBatch.DrawString(
    _Font, 
    Line, 
    Position2, 
    Shade); 
_StencilBatch.End(); 

_RenderedTexture = MaskRenderTarget; 

GraphicsDevice.SetRenderTargets(null); 

可能有一些換位/衛生錯誤,但任何想法我做錯了嗎?

回答

1

的代碼,請參閱應用程序中心論壇我的回答:http://forums.create.msdn.com/forums/p/81189/499989.aspx#499989

您希望ReferenceStencil值爲1兩次。您還需要使用AlphaFunction = CompareGreater,ReferenceAlpha = 0和使用Matrix.OrthographicOffCenter(0,寬度,高度,0,0,1)創建的適當的投影矩陣創建AlphaTestEffect實例; 。

然後,您必須在繪製模板時將SpriteBatch.Begin傳遞給繪圖工具,然後再繪製您想要的模板。

此外,你應該最初繪製模具,然後繪製你想要的模板。在上面的例子中,將DrawString移動到Draw所在的位置,並將Draw移動到DrawString所在的位置。它首先繪製模板(文本)。然後它繪製物品(你的紋理),只保留模板所在的物品部分。

而且你可能想使用Color.Transparent而不是新顏色(0,0,0,1)作爲Clear顏色。

+0

這個答案和你在App Hub論壇上發佈的帖子確實幫助我理解了它的工作原理! :) **非常感謝! :)** – Venemo 2012-01-02 18:26:42