当前位置: 首页>>代码示例>>C#>>正文


C# SpriteBatch.Dispose方法代码示例

本文整理汇总了C#中Microsoft.Xna.Framework.Graphics.SpriteBatch.Dispose方法的典型用法代码示例。如果您正苦于以下问题:C# SpriteBatch.Dispose方法的具体用法?C# SpriteBatch.Dispose怎么用?C# SpriteBatch.Dispose使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Microsoft.Xna.Framework.Graphics.SpriteBatch的用法示例。


在下文中一共展示了SpriteBatch.Dispose方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: FromText

        public static Texture2D FromText(string text, SpriteFont font, Color color, Size size, bool multiLine, int lineStart, GraphicsDevice device)
        {
            string[] drawAbleText = multiLine ? text.Split(new string[1] { "\n" }, StringSplitOptions.None) : new string[1] { text };
            RenderTarget2D target = new RenderTarget2D(device, size.Width, size.Height);
            SpriteBatch sb = new SpriteBatch(device);

            device.SetRenderTarget(target);
            device.Clear(Color.Transparent);

            sb.Begin();
            for (int i = lineStart; i < drawAbleText.Length; i++)
            {
                float y = 1 + (i - lineStart) * font.GetHeight();
                sb.DrawString(font, drawAbleText[i], new Vector2(1, y), color, 0f, Vector2.Zero, Vector2.One, SpriteEffects.None, 0f);
            }
            sb.End();

            device.SetRenderTarget(null);

            Texture2D texture = new Texture2D(device, size.Width, size.Height);
            Color[] colorData = target.GetColorData();
            texture.SetData(colorData);

            target.Dispose();
            sb.Dispose();

            return texture;
        }
开发者ID:MentulaGames,项目名称:XnaGuiItems,代码行数:28,代码来源:Drawing.cs

示例2: Draw

        protected override void Draw()
        {
            base.Draw();

            var spriteBatch = new SpriteBatch(GraphicsDevice);

            _rendererCollection.Render(spriteBatch, GraphicsDevice.Viewport.Bounds, _textureContent);

            spriteBatch.Dispose();
        }
开发者ID:tj-miller,项目名称:TextAdventure,代码行数:10,代码来源:TextAdventureEditorGame.cs

示例3: Draw

 /// <summary>
 /// Draw the screen
 /// </summary>
 /// <param name="gameTime">GameTime for this draw</param>
 public override void Draw(GameTime gameTime)
 {
     GraphicsDevice.Clear(ClearOptions.Target | ClearOptions.DepthBuffer,
         Color.Red, 1.0f, 0);
     SpriteBatch batch = new SpriteBatch(GraphicsDevice);
     batch.Begin();
     {
         batch.Draw(screenImage, new Rectangle(0, 0, SnailsPace.getInstance().Window.ClientBounds.Width, SnailsPace.getInstance().Window.ClientBounds.Height), Color.White);
     }
     batch.End();
     batch.Dispose();
 }
开发者ID:jreese,项目名称:snailspace,代码行数:16,代码来源:GameLoadingScreen.cs

示例4: Draw

 /// <summary>
 /// Draw the background image, the player's score, and a string indicating how to leave the screen.
 /// </summary>
 /// <param name="gameTime">GameTime for this update</param>
 public override void Draw(GameTime gameTime)
 {
     GraphicsDevice.Clear(ClearOptions.Target | ClearOptions.DepthBuffer,
         Color.Red, 1.0f, 0);
     SpriteBatch batch = new SpriteBatch(GraphicsDevice);
     batch.Begin();
     {
         batch.Draw(screenImage, new Rectangle(0, 0, SnailsPace.getInstance().Window.ClientBounds.Width, SnailsPace.getInstance().Window.ClientBounds.Height), Color.White);
         batch.DrawString(font, "Your score is...", new Vector2(100, 25), Color.White);
         batch.DrawString(font, pointsString, new Vector2(50, 60), Color.White);
         batch.DrawString(font, "Press " + SnailsPace.inputManager.getKeyBinding("MenuToggle") + " to continue...", new Vector2(250, 500), Color.White);
     }
     batch.End();
     batch.Dispose();
 }
开发者ID:jreese,项目名称:snailspace,代码行数:19,代码来源:LevelOverScreen.cs

示例5: Draw

 /// <summary>
 /// Draw the background image, the player's score, and a string indicating how to leave the screen.
 /// </summary>
 /// <param name="gameTime">GameTime for this update</param>
 public override void Draw(GameTime gameTime)
 {
     GraphicsDevice.Clear(ClearOptions.Target | ClearOptions.DepthBuffer,
         Color.Red, 1.0f, 0);
     SpriteBatch batch = new SpriteBatch(GraphicsDevice);
     batch.Begin();
     {
         batch.Draw(screenImage, new Rectangle(0, 0, SnailsPace.getInstance().Window.ClientBounds.Width, SnailsPace.getInstance().Window.ClientBounds.Height), Color.White);
         batch.DrawString(font, mapName, new Vector2(100, 25), Color.White);
         List<Score> pointsScores;
         SnailsPace.highScoreList.pointsScores.TryGetValue(mapName, out pointsScores);
         List<Score> accuracyScores;
         SnailsPace.highScoreList.pointsScores.TryGetValue(mapName, out accuracyScores);
         List<Score>.Enumerator pointEnumerator = pointsScores.GetEnumerator();
         List<Score>.Enumerator accuracyEnumerator = accuracyScores.GetEnumerator();
         for (int i = 0; i < pointsScores.Count; i++)
         {
             pointEnumerator.MoveNext();
             batch.DrawString(font, pointEnumerator.Current.score + "   " + pointEnumerator.Current.name, new Vector2(50, 50 + (25 * i)), Color.White);
         }
     }
     batch.End();
     batch.Dispose();
 }
开发者ID:jreese,项目名称:snailspace,代码行数:28,代码来源:HighScoreScreen.cs

示例6: GenerateAssets

 public void GenerateAssets()
 {
     SpriteBatch spriteBatch = new SpriteBatch(m_GraphicsDevice);
     ClearOldData();
     GenerateCityMesh(m_GraphicsDevice); //generates the city mesh
     CreateTextureAtlas(spriteBatch); //generates the many atlases used when rendering the city.
     CreateTransparencyAtlas(spriteBatch);
     RoadAtlas = CreateRoadAtlas(m_Roads, spriteBatch);
     RoadCAtlas = CreateRoadAtlas(m_RoadCorners, spriteBatch);
     spriteBatch.Dispose();
     RegenData = false; //don't do this again next frame...
 }
开发者ID:ddfczm,项目名称:Project-Dollhouse,代码行数:12,代码来源:Terrain.cs

示例7: DrawSprites

        private void DrawSprites(float HB, float VB)
        {
            SpriteBatch spriteBatch = new SpriteBatch(m_GraphicsDevice);
            spriteBatch.Begin();

            if (!m_Zoomed && m_HandleMouse)
            {
                //draw rectangle to indicate zoom position
                DrawLine(m_WhiteLine, new Vector2(m_MouseState.X - 15, m_MouseState.Y - 11), new Vector2(m_MouseState.X - 15, m_MouseState.Y + 11), spriteBatch, 2, 1);
                DrawLine(m_WhiteLine, new Vector2(m_MouseState.X - 16, m_MouseState.Y + 10), new Vector2(m_MouseState.X + 16, m_MouseState.Y + 10), spriteBatch, 2, 1);
                DrawLine(m_WhiteLine, new Vector2(m_MouseState.X + 15, m_MouseState.Y + 11), new Vector2(m_MouseState.X + 15, m_MouseState.Y - 11), spriteBatch, 2, 1);
                DrawLine(m_WhiteLine, new Vector2(m_MouseState.X + 16, m_MouseState.Y - 10), new Vector2(m_MouseState.X - 16, m_MouseState.Y - 10), spriteBatch, 2, 1);
            }
            else if (m_Zoomed && m_HandleMouse)
            {
                if (m_LotCost != 0)
                {
                    float X = GetHoverSquare()[0];
                    float Y = GetHoverSquare()[1];
                    //TODO: Should this have opacity? Might have to change this to render only when hovering over a lot.
                    DrawTooltip(spriteBatch, m_LotCost.ToString() + "§", new Vector2(X, Y), 0f);
                }
                else
                {
                    if (m_CurrentLot != null)
                    {
                        float X = GetHoverSquare()[0];
                        float Y = GetHoverSquare()[1];
                        bool Online = ProtoHelpers.GetBit(m_CurrentLot.flags, 0);
                        string OnlineStr = (Online == true) ? "Online" : "Offline";
                        //TODO: Should this have opacity? Might have to change this to render only when hovering over a lot.
                        DrawTooltip(spriteBatch, GameFacade.Strings.GetString("215", "3", new string[]{m_CurrentLot.name}) + "\n"
                            + OnlineStr, new Vector2(X, Y), 0f);
                    }
                }
            }

            if (m_ZoomProgress < 0.5)
            {
                spriteBatch.End();
                spriteBatch.Dispose();
                return;
            }

            float iScale = (float)m_ScrWidth / (HB * 2);

            float treeWidth = (float)(Math.Sqrt(2)*(128.0/144.0));
            float treeHeight = treeWidth*(80/128);

            Vector2 mid = CalculateR(new Vector2(m_ViewOffX, -m_ViewOffY)); //determine approximate tile position at center of screen
            mid.X -= 6;
            mid.Y += 6;
            float[] bounds = new float[] { (float)Math.Round(mid.X - 19), (float)Math.Round(mid.Y - 19), (float)Math.Round(mid.X + 19), (float)Math.Round(mid.Y + 19) };

            Texture2D img = m_Forest;
            float fade = Math.Max(0, Math.Min(1, (m_ZoomProgress - 0.4f) * 2));

            DrawTileBorders(iScale, spriteBatch);

            for (short y = (short)bounds[1]; y < bounds[3]; y++) //iterate over tiles close to the approximate tile position at the center of the screen and draw any trees/houses on them
            {
                if (y < 0 || y > 511) continue;
                for(short x = (short)bounds[0]; x < bounds[2]; x++)
                {
                    if (x < 0 || x > 511) continue;

                    float elev = (m_ElevationData[(y * 512 + x) * 4] + m_ElevationData[(y * 512 + Math.Min(x + 1, 511)) * 4] +
                        m_ElevationData[(Math.Min(y + 1, 511) * 512 + Math.Min(x + 1, 511)) * 4] +
                        m_ElevationData[(Math.Min(y + 1, 511) * 512 + x) * 4]) / 4; //elevation of sprite is the average elevation of the 4 vertices of the tile

                    var xy = transformSpr(iScale, new Vector3((float)(x + 0.5), elev / 12.0f, (float)(y + 0.5)));

                    if (xy.X > -64 && xy.X < m_ScrWidth + 64 && xy.Y > -40 && xy.Y < m_ScrHeight + 40) //is inside screen
                    {

                        Vector2 loc = new Vector2( x, y );
                        LotTileEntry house;

                        if (m_CityLookup.ContainsKey(loc))
                        {
                            house = m_CityLookup[loc];
                        }
                        else
                        {
                            house = null;
                        }
                        if (house != null) //if there is a house here, draw it
                        {
                            if ((house.flags & 1) > 0) {
                                PathTile(x, y, iScale, (float)(0.3+Math.Sin(4*Math.PI*(m_SpotOsc%1))*0.15));
                            }

                            double scale = treeWidth * iScale / 128.0;
                            if (!m_HouseGraphics.ContainsKey(house.lotid)) {
                                //no house graphic found - request one!
                                m_HouseGraphics[house.lotid] = m_DefaultHouse;
                                m_CityData.RetrieveHouseGFX(house.lotid, m_HouseGraphics, m_GraphicsDevice);
                            }
                            Texture2D lotImg = m_HouseGraphics[house.lotid];
                            spriteBatch.Draw(lotImg, new Rectangle((int)(xy.X - 64.0 * scale), (int)(xy.Y - 32.0 * scale), (int)(scale * 128), (int)(scale * 64)), m_TintColor);
//.........这里部分代码省略.........
开发者ID:ddfczm,项目名称:Project-Dollhouse,代码行数:101,代码来源:Terrain.cs

示例8: Dispose

 /// <summary>
 /// Dispose
 /// </summary>
 /// <param name="someObject">Some object</param>
 public static void Dispose(ref SpriteBatch someObject)
 {
     if (someObject != null)
         someObject.Dispose();
     someObject = null;
 }
开发者ID:kiichi7,项目名称:XnaTetris,代码行数:10,代码来源:DisposeHelper.cs

示例9: render

        /// <summary>
        /// Render the scene.
        /// </summary>
        /// <param name="objects">All GameObjects to be rendered.</param>
        /// <param name="strings">Strings of text to render.</param>
        /// <param name="gameTime">The current time.</param>
        public void render(List<Objects.GameObject> objects, List<Objects.Text> strings, GameTime gameTime)
        {
            SnailsPace.getInstance().GraphicsDevice.RenderState.CullMode = CullMode.None;
            SnailsPace.getInstance().GraphicsDevice.RenderState.DepthBufferEnable = true;
            SnailsPace.getInstance().GraphicsDevice.RenderState.DepthBufferWriteEnable = true;
            SnailsPace.getInstance().GraphicsDevice.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.CornflowerBlue, 1.0f, 0);
            Vector3 cameraTargetPosition = getCameraTargetPosition();
            cameraTargetPosition.Z = cameraTargetPosition.Z * debugZoom;
            if (!cameraPosition.Equals(cameraTargetPosition))
            {
                // If the camera is not at it's target position, move the camera toward the target.
                float elapsedTime = (float)Math.Min(gameTime.ElapsedRealTime.TotalSeconds, 1);
                Vector3 cameraDifference = cameraTargetPosition - cameraPosition;
                Vector3 cameraPositionMovement = Vector3.Zero;
                cameraPositionMovement.X = calculateCameraMovement(cameraDifference.X, elapsedTime);
                cameraPositionMovement.Y = calculateCameraMovement(cameraDifference.Y, elapsedTime);
                cameraPositionMovement.Z = calculateCameraMovement(cameraDifference.Z, elapsedTime);
                cameraPosition = cameraPosition + cameraPositionMovement;

                // Keep the camera inside the level's specified bounds.
                float cameraStopXDistance = (float)(1000 * Math.Tan(45 / 2.0));
                float cameraStopYDistance = (float)(1000 * Math.Tan(MathHelper.PiOver4 / 2.0));
                for (int i = 1; i < cameraBounds.Length; i++)
                {
                    if (cameraBounds[i].X == cameraBounds[i - 1].X)
                    {
                        // This is a vertical bounding line, check the camera position to the left and right.
                        if ((cameraBounds[i].X < 0) && (cameraPosition.X - cameraStopXDistance < cameraBounds[i].X))
                            cameraPosition.X = cameraBounds[i].X + cameraStopXDistance;
                        else if ((cameraBounds[i].X > 0) && (cameraPosition.X + cameraStopXDistance > cameraBounds[i].X))
                            cameraPosition.X = cameraBounds[i].X - cameraStopXDistance;
                    }
                    else if (cameraBounds[i].Y == cameraBounds[i - 1].Y)
                    {
                        // This is a horizontal bounding line, check the camera position on top and bottom.
                        if ((cameraBounds[i].Y > 0) && (cameraPosition.Y + cameraStopYDistance > cameraBounds[i].Y))
                            cameraPosition.Y = cameraBounds[i].Y - cameraStopYDistance;
                        else if ((cameraBounds[i].Y < 0) && (cameraPosition.Y - cameraStopYDistance < cameraBounds[i].Y))
                            cameraPosition.Y = cameraBounds[i].Y + cameraStopYDistance;
                    }
                }
            }

            Viewport viewport = SnailsPace.getInstance().GraphicsDevice.Viewport;
            float aspectRatio = (float)viewport.Width / (float)viewport.Height;
            cameraProjection = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, aspectRatio, nearClip, farClip);
            cameraView = Matrix.CreateLookAt(cameraPosition, cameraPosition + Vector3.Forward, Vector3.Up);
            BoundingFrustum viewFrustum = new BoundingFrustum(cameraView * cameraProjection);

            #if DEBUG
            // If debugging bounding boxes, make sure the list exists.
            if (boundingBoxVertices == null)
            {
                boundingBoxVertices = new List<VertexPositionColorTexture[]>();
            }
            else
            {
                boundingBoxVertices.Clear();
            }
            #endif
            if (objects != null)
            {
                List<Objects.GameObject>.Enumerator objectEnumerator = objects.GetEnumerator();

                SnailsPace.getInstance().GraphicsDevice.VertexDeclaration = new VertexDeclaration(SnailsPace.getInstance().GraphicsDevice, VertexPositionColorTexture.VertexElements);
                while (objectEnumerator.MoveNext())
                {
                    // Iterate over each GameObject and draw it.
                    drawObject(objectEnumerator.Current, viewFrustum);
            #if DEBUG
                    if (SnailsPace.debugBoundingBoxes && objectEnumerator.Current.collidable)
                    {
                        // Draw a bounding box if we are debugging bounding boxes and this object has one.
                        Objects.GameObjectBounds boundingBox = objectEnumerator.Current.bounds;
                        Vector2[] boxVertices = boundingBox.Points;
                        VertexPositionColorTexture[] visualBoxVertices = new VertexPositionColorTexture[boxVertices.Length + 2];
                        visualBoxVertices[0].Color = boundingBoxCenterColor;
                        visualBoxVertices[0].Position = new Vector3(objectEnumerator.Current.position, 1);
                        visualBoxVertices[visualBoxVertices.Length - 1].Position = new Vector3(boxVertices[0], 1);
                        visualBoxVertices[visualBoxVertices.Length - 1].Color = boundingBoxColor;
                        for (int boxVertexIndex = 0; boxVertexIndex < boxVertices.Length; boxVertexIndex++)
                        {
                            visualBoxVertices[boxVertexIndex + 1].Position = new Vector3(boxVertices[boxVertexIndex], 1);
                            visualBoxVertices[boxVertexIndex + 1].Color = boundingBoxColor;
                        }
                        boundingBoxVertices.Add(visualBoxVertices);
                    }
            #endif
                }
                objectEnumerator.Dispose();
            #if DEBUG
                if (SnailsPace.debugTriggers)
                {
                    // Draw a trigger box if we are debugging triggers.
//.........这里部分代码省略.........
开发者ID:jreese,项目名称:snailspace,代码行数:101,代码来源:Renderer.cs

示例10: Draw

        protected override void Draw(IXnaGameTime gameTime)
        {
            gameTime.ThrowIfNull("gameTime");

            var spriteBatch = new SpriteBatch(GraphicsDevice);

            _rendererCollection.Render(spriteBatch, gameTime, _fontContent, _textureContent);

            spriteBatch.Dispose();
        }
开发者ID:nathan-alden,项目名称:old-text-adventure,代码行数:10,代码来源:TextAdventureGame.cs

示例11: LoadAndInitialize


//.........这里部分代码省略.........
                {
                    try
                    {
                        Edges.Add(new MapEdge(edge.Attribute("name").Value, Points.Find(p => p.Name == edge.Attribute("start").Value), Points.Find(p => p.Name == edge.Attribute("end").Value)));
                    }
                    catch { }
                }

                //spawn points
                XElement spawns = root.Element("Spawns");
                if (spawns == null)
                    return;
                foreach (XElement spawn in spawns.Elements("Spawn"))
                {
                    try
                    {
                        SpawnPoints.Add(new MapSpawnPoint(spawn.Attribute("name").Value,
                                        new Vector2(float.Parse(spawn.Attribute("x").Value.Replace('.', ',')), float.Parse(spawn.Attribute("y").Value.Replace('.', ','))),
                                        float.Parse(spawn.Attribute("rot").Value.Replace('.', ',')),
                                        int.Parse(spawn.Attribute("team").Value)));
                        SpawnInUse.Add(false);
                    }
                    catch { }
                }

                //rectangles
                XElement rects = root.Element("Rects");
                if (rects == null)
                    return;
                foreach (XElement rect in rects.Elements("Rect"))
                {
                    try
                    {
                        Rects.Add(new MapRect(rect.Attribute("name").Value,
                                  new Rectangle(int.Parse(rect.Attribute("x").Value), int.Parse(rect.Attribute("y").Value), int.Parse(rect.Attribute("w").Value), int.Parse(rect.Attribute("h").Value)),
                                  float.Parse(rect.Attribute("rot").Value.Replace('.', ',')),
                                  int.Parse(rect.Attribute("originX").Value), int.Parse(rect.Attribute("originY").Value)));
                    }
                    catch { }
                }

                //clean up
                //erase edges not assigned to any sector
                for (int i = 0; i < Edges.Count; )
                {
                    if (Sectors.FindIndex(s => s.Edges.FindIndex(e => Edges[i].Name == e) != -1) == -1)
                        Edges.RemoveAt(i);
                    else
                        i++;
                }
                //erase spawns outside of every sector (spawn need to be inside of some sector for motor initialization)
                for (int i = 0; i < SpawnPoints.Count; )
                {
                    if (Sectors.FindIndex(s => s.IsInSector(SpawnPoints[i].Coords)) == -1)
                        SpawnPoints.RemoveAt(i);
                    else
                        i++;
                }

                #endregion

                #region draw map and slice it

                //draw to memory
                Texture = UIParent.defaultTextures;

                RenderTarget2D mappicture = new RenderTarget2D(game.GraphicsDevice, (int)Parameters.Size.X, (int)Parameters.Size.Y, false, SurfaceFormat.Color, DepthFormat.None, 1, RenderTargetUsage.PreserveContents);
                SpriteBatch sb = new SpriteBatch(game.GraphicsDevice);
                game.GraphicsDevice.SetRenderTarget(mappicture);
                game.GraphicsDevice.Clear(Parameters.BackColor);
                sb.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend);
                for (int x = 0; x < (int)(Parameters.Size.X / BackCrateTexture.Width + (Parameters.Size.X % BackCrateTexture.Width != 0 ? 1 : 0)); x++)
                    for (int y = 0; y < (int)(Parameters.Size.Y / BackCrateTexture.Height + (Parameters.Size.Y % BackCrateTexture.Height != 0 ? 1 : 0)); y++)
                        sb.Draw(Texture, new Vector2(x * BackCrateTexture.Width, y * BackCrateTexture.Height), BackCrateTexture, Parameters.BackCrateColor);
                for (int i = 0; i < Rects.Count; i++)
                    Rects[i].Draw(ref sb, Parameters.BlockingColor);
                sb.End();

                //slice map
                for (int x = 0; x < Slices.GetLength(0); x++)
                    for (int y = 0; y < Slices.GetLength(1); y++)
                    {
                        Slices[x, y] = new MapSlice(game, new Rectangle((int)(x * Parameters.Slicing.X), (int)(y * Parameters.Slicing.Y), (int)Parameters.Slicing.X, (int)Parameters.Slicing.Y));
                        game.GraphicsDevice.SetRenderTarget(Slices[x, y].picture);
                        game.GraphicsDevice.Clear(Color.Transparent);
                        sb.Begin(SpriteSortMode.Immediate, BlendState.Opaque);
                        sb.Draw(mappicture, Vector2.Zero, Slices[x, y].PositionAndSize, Color.White);
                        sb.End();
                    }

                game.GraphicsDevice.SetRenderTarget(null);

                mappicture.Dispose();
                sb.Dispose();
                Rects.Clear();

                #endregion
            }
            catch { }
        }
开发者ID:valdemart,项目名称:Motorki,代码行数:101,代码来源:Map.cs

示例12: Stretch

        public static Texture2D Stretch(this Texture2D texture, Size size)
        {
            RenderTarget2D target = new RenderTarget2D(texture.GraphicsDevice, size.Width, size.Height);
            SpriteBatch sb = new SpriteBatch(texture.GraphicsDevice);

            texture.GraphicsDevice.SetRenderTarget(target);
            texture.GraphicsDevice.Clear(Color.Transparent);
            sb.Begin();
            sb.Draw(texture, new Rectangle(0, 0, size.Width, size.Height), Color.White);
            sb.End();

            texture.GraphicsDevice.SetRenderTarget(null);
            Texture2D result = new Texture2D(texture.GraphicsDevice, size.Width, size.Height);
            result.SetData(target.GetColorData());

            target.Dispose();
            sb.Dispose();

            return result;
        }
开发者ID:MentulaGames,项目名称:XnaGuiItems,代码行数:20,代码来源:Extentions.cs

示例13: RenderOnto

        public static Texture2D RenderOnto(this Texture2D texture, Size size, Vector2 position = default(Vector2), float rotation = 0, Vector2 scale = default(Vector2))
        {
            RenderTarget2D target = new RenderTarget2D(texture.GraphicsDevice, size.Width, size.Height);
            SpriteBatch sb = new SpriteBatch(texture.GraphicsDevice);

            texture.GraphicsDevice.SetRenderTarget(target);
            texture.GraphicsDevice.Clear(Color.Transparent);
            sb.Begin();
            sb.Draw(texture, position, null, Color.White, rotation, Vector2.Zero, scale == default(Vector2) ? Vector2.One : scale, SpriteEffects.None, 1f);
            sb.End();

            texture.GraphicsDevice.SetRenderTarget(null);
            Texture2D result = new Texture2D(texture.GraphicsDevice, size.Width, size.Height);
            result.SetData(target.GetColorData());

            target.Dispose();
            sb.Dispose();


            return result;
        }
开发者ID:MentulaGames,项目名称:XnaGuiItems,代码行数:21,代码来源:Extentions.cs

示例14: LoadTexture

		static public Texture2D LoadTexture (GraphicsDevice device, Stream input) {
			Texture2D file = Texture2D.FromStream(device, input);

			// Setup a render target to hold our final texture which will have premulitplied alpha values
			RenderTarget2D result = new RenderTarget2D(device, file.Width, file.Height);
			device.SetRenderTarget(result);
			device.Clear(Color.Black);

			// Multiply each color by the source alpha, and write in just the color values into the final texture
			BlendState blendColor = new BlendState();
			blendColor.ColorWriteChannels = ColorWriteChannels.Red | ColorWriteChannels.Green | ColorWriteChannels.Blue;
			blendColor.AlphaDestinationBlend = Blend.Zero;
			blendColor.ColorDestinationBlend = Blend.Zero;
			blendColor.AlphaSourceBlend = Blend.SourceAlpha;
			blendColor.ColorSourceBlend = Blend.SourceAlpha;

			SpriteBatch spriteBatch = new SpriteBatch(device);
			spriteBatch.Begin(SpriteSortMode.Immediate, blendColor);
			spriteBatch.Draw(file, file.Bounds, Color.White);
			spriteBatch.End();

			// Now copy over the alpha values from the PNG source texture to the final one, without multiplying them
			BlendState blendAlpha = new BlendState();
			blendAlpha.ColorWriteChannels = ColorWriteChannels.Alpha;
			blendAlpha.AlphaDestinationBlend = Blend.Zero;
			blendAlpha.ColorDestinationBlend = Blend.Zero;
			blendAlpha.AlphaSourceBlend = Blend.One;
			blendAlpha.ColorSourceBlend = Blend.One;

			spriteBatch.Begin(SpriteSortMode.Immediate, blendAlpha);
			spriteBatch.Draw(file, file.Bounds, Color.White);
			spriteBatch.End();

			// Release the GPU back to drawing to the screen.
			device.SetRenderTarget(null);
			spriteBatch.Dispose();
			file.Dispose();

#if IOS
			return result as Texture2D;
#else
			// RenderTarget2D are volatile and will be lost on screen resolution changes.
			// So instead of using this directly, we create a non-voliate Texture2D.
			// This is computationally slower, but should be safe as long as it is done on load.
			Texture2D resultTexture = new Texture2D(device, file.Width, file.Height);
			Color[] resultContent = new Color[Convert.ToInt32(file.Width * file.Height)];
			result.GetData(resultContent);
			resultTexture.SetData(resultContent);
			result.Dispose(); // Dispose of the RenderTarget2D immediately.
			return resultTexture;
#endif
		}
开发者ID:jaimeBokoko,项目名称:spine-runtimes,代码行数:52,代码来源:Util.cs


注:本文中的Microsoft.Xna.Framework.Graphics.SpriteBatch.Dispose方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。