public static void TakeScreenShot(GraphicsDevice device, Keys theKey) { currentState = Keyboard.GetState(); if (currentState.IsKeyDown(theKey) && preState.IsKeyUp(theKey)) { byte[] screenData; screenData = new byte[device.PresentationParameters.BackBufferWidth * device.PresentationParameters.BackBufferHeight * 4]; device.GetBackBufferData<byte>(screenData); Texture2D Screenshot = new Texture2D(device, device.PresentationParameters.BackBufferWidth, device.PresentationParameters.BackBufferHeight, false, device.PresentationParameters.BackBufferFormat); Screenshot.SetData<byte>(screenData); string name = "Screenshot_" + counter + ".jpeg"; while (File.Exists(name)) { counter += 1; name = "Screenshot_" + counter + ".jpeg"; } Stream stream = new FileStream(name, FileMode.Create); Screenshot.SaveAsJpeg(stream, Screenshot.Width, Screenshot.Height); stream.Close(); Screenshot.Dispose(); } preState = currentState; }
public static void Copy(SpanBitmap src, ref XNA.Texture2D dst, bool fit, Func <int, int, XNA.Texture2D> texFactory) { if (dst == null || dst.Width != src.Width || dst.Height != src.Height) { if (dst != null) { dst.Dispose(); } dst = null; } if (dst == null) { dst = texFactory(src.Width, src.Height); } if (dst.Format == XNA.SurfaceFormat.Bgr565) { _Copy16(src, dst, fit); return; } if (dst.Format == XNA.SurfaceFormat.Bgra32) { _Copy32(src, dst, fit); return; } }
} // Texture(tex) #endregion #region Disposing /// <summary> /// Dispose /// </summary> public virtual void Dispose() { if (internalXnaTexture != null) { internalXnaTexture.Dispose(); } internalXnaTexture = null; loaded = false; } // Dispose()
public override void Dispose() { disposeChilderen(); if (texture != null && !loadedFromContentManager) { texture.Dispose(); texture = null; } base.Dispose(); }
/// <summary> /// Converts the given System.Drawing.Image into a Texture2D. /// </summary> /// <param name="image">The image to be converted</param> /// <param name="graphicsDevice">The GraphicsDevice with which the image will be displayed</param> /// <param name="texture">A texture to reuse - can be null</param> /// <returns>A Texture2D of the image</returns> public static Texture2D Image2Texture(System.Drawing.Image image, GraphicsDevice graphicsDevice, Texture2D texture) { GraphicsDevice graphics = graphicsDevice; if (graphics == null) return null; if (image == null) { return null; } if (texture == null || texture.IsDisposed || texture.Width != image.Width || texture.Height != image.Height || texture.Format != SurfaceFormat.Color) { if (texture != null && !texture.IsDisposed) { texture.Dispose(); } texture = new Texture2D(graphics, image.Width, image.Height, false, SurfaceFormat.Color); } else { for (int i = 0; i < 16; i++) { if (graphics.Textures[i] == texture) { graphics.Textures[i] = null; break; } } } //Memory stream to store the bitmap data. MemoryStream ms = new MemoryStream(); //Save to that memory stream. image.Save(ms, System.Drawing.Imaging.ImageFormat.Png); //Go to the beginning of the memory stream. ms.Seek(0, SeekOrigin.Begin); //Fill the texture. texture = Texture2D.FromStream(graphics, ms, image.Width, image.Height, false); //Close the stream. ms.Close(); ms = null; return texture; }
protected override void Dispose(bool disposing) { if (!IsDisposed) { //Dispose of managed resources if (disposing) { if (_texture2D != null) { _texture2D.Dispose(); } } } base.Dispose(disposing); }
private void captureScreenshot() { try { byte[] screenData; screenData = new byte[graphicsDevice.PresentationParameters.BackBufferWidth * graphicsDevice.PresentationParameters.BackBufferHeight * 4]; //take whats on the graphics device and put it to the back buffer graphicsDevice.GetBackBufferData<byte>(screenData); Texture2D texture2D = new Texture2D(graphicsDevice, graphicsDevice.PresentationParameters.BackBufferWidth, graphicsDevice.PresentationParameters.BackBufferHeight, false, graphicsDevice.PresentationParameters.BackBufferFormat); texture2D.SetData<byte>(screenData); saveScreenshot(texture2D); texture2D.Dispose(); } catch (Exception e) { MessageBox.Show("You broke it...."); } }
public override void Render(GraphicsDevice graphicsDevice) { Update(); if (visible&&size.Width>0&&size.Height>0) { Color drawColour = new Color(1f, 1f, 1f); if (!enabled) { drawColour = new Color(.5f, .5f, .5f); } //Generate 1px white texture Texture2D shade = new Texture2D(graphicsDevice, 1,1,1,TextureUsage.None,SurfaceFormat.Color); shade.SetData(new Color[] { Color.White }); //Draw end boxes SpriteBatch spriteBatch = new SpriteBatch(graphicsDevice); spriteBatch.Begin(SpriteBlendMode.AlphaBlend, SpriteSortMode.Deferred, SaveStateMode.SaveState); spriteBatch.Draw(shade, new Rectangle(size.X, size.Y, size.Height, size.Height), drawColour); spriteBatch.Draw(shade, new Rectangle(size.X + size.Width - size.Height, size.Y, size.Height, size.Height), drawColour); //Draw line float sliderPercent = getPercent(); int sliderPartialWidth = size.Height / 4; int midHeight = (int)(size.Height/2)-1; int actualWidth = size.Width - 2 * size.Height; int actualPosition = (int)(sliderPercent * actualWidth); spriteBatch.Draw(shade, new Rectangle(size.X, size.Y + midHeight, size.Width, 1), drawColour); //Draw slider spriteBatch.Draw(shade, new Rectangle(size.X + size.Height + actualPosition - sliderPartialWidth, size.Y + midHeight - sliderPartialWidth, size.Height / 2, size.Height / 2), drawColour); if (text != "") { //Draw text spriteBatch.DrawString(uiFont, text, new Vector2(size.X, size.Y - 36), drawColour); } //Draw amount spriteBatch.DrawString(uiFont, (((float)(int)(value * 10)) / 10).ToString(), new Vector2(size.X, size.Y - 20), drawColour); spriteBatch.End(); shade.Dispose(); } }
public void WriteData(pr2.sharppng.Pcx pcx) { Texture2D tex = null; try { tex = new Texture2D(device, pcx.width, pcx.height, false, SurfaceFormat.Color); int[] data = new int[pcx.width*pcx.height]; int dest = 0; tex.GetData(data); //reformat the palette int[] colors = new int[256]; for (int i=0; i<256; i++) colors[i] = (int)GameEngine.MakeColor(255, pcx.palette[i*3], pcx.palette[i*3+1], pcx.palette[i*3+2]).PackedValue; //blast into image int pad = pcx.bytes_per_line - pcx.width; fixed (byte* pixels = pcx.pixels) { byte* src = pixels; if (bColor0) for (int y=0; y<pcx.height; y++) { for (int x=0; x<pcx.width; x++) { byte b = *src++; int col = colors[b]; if (b == 0) col = 0; data[dest++] = col; } src += pad; } else for (int y=0; y<pcx.height; y++) { for (int x=0; x<pcx.width; x++) data[dest++] = colors[*src++]; src += pad; } } tex.SetData<int>(data, 0, data.Length); image = new Image(GameEngine.Game.Device, tex); tex = null; } finally { if (tex != null) tex.Dispose(); } }
public override IEnumerator onBeginTransition() { // create a single pixel texture of our fadeToColor _overlayTexture = Graphics.createSingleColorTexture( 1, 1, fadeToColor ); var elapsed = 0f; while( elapsed < fadeOutDuration ) { elapsed += Time.deltaTime; _color = Lerps.ease( fadeEaseType, ref _toColor, ref _fromColor, elapsed, fadeOutDuration ); yield return null; } // load up the new Scene yield return Core.startCoroutine( loadNextScene() ); // dispose of our previousSceneRender. We dont need it anymore. previousSceneRender.Dispose(); previousSceneRender = null; yield return Coroutine.waitForSeconds( delayBeforeFadeInDuration ); elapsed = 0f; while( elapsed < fadeInDuration ) { elapsed += Time.deltaTime; _color = Lerps.ease( EaseHelper.oppositeEaseType( fadeEaseType ), ref _fromColor, ref _toColor, elapsed, fadeInDuration ); yield return null; } transitionComplete(); _overlayTexture.Dispose(); }
// Trim transparent edges public Texture2D trimTransparentEdges(Texture2D canvas) { Color[] data1d = new Color[canvas.Width * canvas.Height]; Color[,] data2d = new Color[canvas.Width, canvas.Height]; Color[] newData; int halfWidth = canvas.Width / 2; int halfHeight = canvas.Height / 2; int lastTransparentColumnFromLeft; int lastTransparentColumnFromRight; int lastTransparentRowFromTop; int lastTransparentRowFromBottom; int newWidth; int newHeight; int widthTrim; int heightTrim; Func<int, int> findTransparentColumnFromLeft = (end) => { int lastTransparentColumn = 0; for (int i = 0; i < end; i++) { for (int j = 0; j < canvas.Height; j++) { if (data2d[i, j].A > 0) { return lastTransparentColumn; } } lastTransparentColumn = i; } return lastTransparentColumn; }; Func<int, int> findTransparentColumnFromRight = (end) => { int lastTransparentColumn = canvas.Width - 1; for (int i = canvas.Width - 1; i >= end; i--) { for (int j = 0; j < canvas.Height; j++) { if (data2d[i, j].A > 0) { return lastTransparentColumn; } } lastTransparentColumn = i; } return lastTransparentColumn; }; Func<int, int> findTransparentRowFromTop = (end) => { int lastTransparentRow = 0; for (int j = 0; j < end; j++) { for (int i = 0; i < canvas.Width; i++) { if (data2d[i, j].A > 0) { return lastTransparentRow; } } lastTransparentRow = j; } return lastTransparentRow; }; Func<int, int> findTransparentRowFromBottom = (end) => { int lastTransparentRow = canvas.Height - 1; for (int j = canvas.Height - 1; j >= end; j--) { for (int i = 0; i < canvas.Width; i++) { if (data2d[i, j].A > 0) { return lastTransparentRow; } } lastTransparentRow = j; } return lastTransparentRow; }; canvas.GetData<Color>(data1d); for (int i = 0; i < canvas.Width; i++) { for (int j = 0; j < canvas.Height; j++) { data2d[i, j] = data1d[i + j * canvas.Width]; } } lastTransparentColumnFromLeft = findTransparentColumnFromLeft(halfWidth); lastTransparentColumnFromRight = findTransparentColumnFromRight(halfWidth); lastTransparentRowFromTop = findTransparentRowFromTop(halfHeight); lastTransparentRowFromBottom = findTransparentRowFromBottom(halfHeight); widthTrim = Math.Min(lastTransparentColumnFromLeft, (canvas.Width - 1) - lastTransparentColumnFromRight); heightTrim = Math.Min(lastTransparentRowFromTop, (canvas.Height - 1) - lastTransparentRowFromBottom); newWidth = canvas.Width - (widthTrim * 2); newHeight = canvas.Height - (heightTrim * 2); if (newWidth < 1 || newHeight < 1) { canvas.Dispose(); canvas = new Texture2D(_graphicsDevice, 1, 1); canvas.SetData<Color>(new[] { Color.Transparent }); } newData = new Color[newWidth * newHeight]; for (int i = 0; i < newWidth; i++) { for (int j = 0; j < newHeight; j++) { newData[i + j * newWidth] = data2d[widthTrim + i, heightTrim + j]; } } canvas.Dispose(); canvas = new Texture2D(_graphicsDevice, newWidth, newHeight); canvas.SetData<Color>(newData); return canvas; }
/// <summary> /// Allows the game to run logic such as updating the world, /// checking for collisions, gathering input, and playing audio. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> public void Update(GameTime gameTime) { // Get input from the player inputController.Update(); // screencaps if (inputController.ScreenCap.JustPressed) { Draw(gameTime); Texture2D texture = new Texture2D(graphicsDevice, GraphicsConstants.VIEWPORT_WIDTH, GraphicsConstants.VIEWPORT_HEIGHT); Color[] data = new Color[texture.Width * texture.Height]; graphicsDevice.GetBackBufferData<Color>(data); texture.SetData<Color>(data); Stream stream = File.OpenWrite("output.png"); texture.SaveAsPng(stream, texture.Width, texture.Height); stream.Dispose(); texture.Dispose(); } if (currentContext.Exit || currentContext.NextContext != null) { targetOverlayAlpha = 1; if (currentOverlayAlpha == 1) { //audioPlayer.StopSong(); if (currentContext.Exit) exitGame = true; else if (!asyncStarted) { asyncStarted = true; asyncFinished = false; InitializeContextComponents(currentContext.NextContext); asyncFinished = true; } if (asyncStarted && asyncFinished) { //Thread.Sleep(1000); asyncStarted = false; targetOverlayAlpha = 0; currentContext.Dispose(); currentContext = currentContext.NextContext; } } } else { currentContext.Update(gameTime); } currentOverlayAlpha = MathHelper.Lerp(currentOverlayAlpha, targetOverlayAlpha, currentContext.FadeMultiplier); //Console.WriteLine(Math.Abs(currentOverlayAlpha - targetOverlayAlpha)); if (Math.Abs(currentOverlayAlpha - targetOverlayAlpha) < 0.001f || inputController.Zoom.Pressed) currentOverlayAlpha = targetOverlayAlpha; }
public void ScreenShot(string prefix) { int w = GraphicsDevice.PresentationParameters.BackBufferWidth; int h = GraphicsDevice.PresentationParameters.BackBufferHeight; //force a frame to be drawn (otherwise back buffer is empty) Draw(new GameTime()); //pull the picture from the buffer int[] backBuffer = new int[w * h]; GraphicsDevice.GetBackBufferData(backBuffer); //copy into a texture Texture2D texture = new Texture2D(GraphicsDevice, w, h, false, GraphicsDevice.PresentationParameters.BackBufferFormat); texture.SetData(backBuffer); //save to disk Stream stream = File.OpenWrite(prefix + ".png"); texture.SaveAsPng(stream, w, h); texture.Dispose(); stream.Close(); Console.WriteLine("Screenshot saved in the root directory."); }
public override void Render(GraphicsDevice graphicsDevice) { if (visible && size.Width > 0 && size.Height > 0) { Color drawColour = new Color(1f, 1f, 1f); if (!enabled) drawColour = new Color(.7f, .7f, .7f); else if (midClick) drawColour = new Color(.85f, .85f, .85f); //Generate 1px white texture Texture2D shade = new Texture2D(graphicsDevice, 1, 1, 1, TextureUsage.None, SurfaceFormat.Color); shade.SetData(new Color[] { Color.White }); //Draw base button SpriteBatch spriteBatch = new SpriteBatch(graphicsDevice); spriteBatch.Begin(); spriteBatch.Draw(shade, size, drawColour); //Draw button text string dispText = offText; if (clicked) dispText = onText; spriteBatch.DrawString(uiFont, dispText, new Vector2(size.X + size.Width / 2 - uiFont.MeasureString(dispText).X / 2, size.Y + size.Height / 2 - 8), Color.Black); if (text != "") { //Draw text spriteBatch.DrawString(uiFont, text, new Vector2(size.X, size.Y - 20), enabled ? Color.White : new Color(.7f, .7f, .7f));//drawColour); } /*spriteBatch.Begin(SpriteBlendMode.AlphaBlend, SpriteSortMode.Deferred, SaveStateMode.SaveState); spriteBatch.Draw(shade, new Rectangle(size.X, size.Y, size.Height, size.Height), drawColour); spriteBatch.Draw(shade, new Rectangle(size.X + size.Width - size.Height, size.Y, size.Height, size.Height), drawColour); //Draw line float sliderPercent = getPercent(); int sliderPartialWidth = size.Height / 4; int midHeight = (int)(size.Height / 2) - 1; int actualWidth = size.Width - 2 * size.Height; int actualPosition = (int)(sliderPercent * actualWidth); spriteBatch.Draw(shade, new Rectangle(size.X, size.Y + midHeight, size.Width, 1), drawColour); //Draw slider spriteBatch.Draw(shade, new Rectangle(size.X + size.Height + actualPosition - sliderPartialWidth, size.Y + midHeight - sliderPartialWidth, size.Height / 2, size.Height / 2), drawColour); //Draw amount spriteBatch.DrawString(uiFont, (((float)(int)(value * 10)) / 10).ToString(), new Vector2(size.X, size.Y - 20), drawColour); */ spriteBatch.End(); shade.Dispose(); } }
public static drawing.Bitmap ToBitmap(Texture2D texture) { drawing.Bitmap bitmap = new drawing.Bitmap(texture.Width, texture.Height, drawing.Imaging.PixelFormat.Format32bppArgb); byte blue; IntPtr safePtr; drawing.Imaging.BitmapData bitmapData; drawing.Rectangle rect = new drawing.Rectangle(0, 0, texture.Width, texture.Height); byte[] textureData = new byte[4 * texture.Width * texture.Height]; texture.GetData<byte>(textureData); for (int i = 0; i < textureData.Length; i += 4) { blue = textureData[i]; textureData[i] = textureData[i + 2]; textureData[i + 2] = blue; } bitmapData = bitmap.LockBits(rect, drawing.Imaging.ImageLockMode.WriteOnly, drawing.Imaging.PixelFormat.Format32bppArgb); safePtr = bitmapData.Scan0; Marshal.Copy(textureData, 0, safePtr, textureData.Length); bitmap.UnlockBits(bitmapData); textureData = null; texture.Dispose(); return bitmap; }
/// <summary> /// Unload and dispose by object. /// </summary> /// <param name="source"></param> public void Unload(Texture2D source) { Textures.Remove(source); source.Dispose(); }
// Takes a screenshot of the game and saves it as a png. private void SaveScreenShot() { // Screenshot function taken from http://clifton.me/screenshot-xna-csharp/ #if WINDOWS // Get the screen size int width = GraphicsDevice.PresentationParameters.BackBufferWidth; int height = GraphicsDevice.PresentationParameters.BackBufferHeight; // Force a frame to be drawn (otherwise back buffer is empty) Draw(new GameTime()); // Pull the picture from the buffer int[] backBuffer = new int[width * height]; GraphicsDevice.GetBackBufferData(backBuffer); // Copy the screen into a texture Texture2D texture = new Texture2D(GraphicsDevice, width, height, false, GraphicsDevice.PresentationParameters.BackBufferFormat); texture.SetData(backBuffer); // Get the next available indexed file name int index = 1; // Create a folder to store the screenshots in if (!File.Exists("Screenshots")) { System.IO.Directory.CreateDirectory("Screenshots"); } // Get the screenshot file name string currentPath = "Screenshots/Screenshot-" + index + ".png"; if (screenShotName.Length == 0) { while (File.Exists(currentPath)) { index++; currentPath = "Screenshots/Screenshot-" + index + ".png"; } } else { currentPath = "Screenshots/" + screenShotName + ".png"; } // Save the image to file Stream stream = File.OpenWrite(currentPath); texture.SaveAsPng(stream, width, height); stream.Close(); texture.Dispose(); #endif }
private static void Dispose(Texture2D sprite) { if (sprite != null) sprite.Dispose(); }
public override IEnumerator onBeginTransition() { // create a single pixel transparent texture so we can do our squares out to the next scene _overlayTexture = Graphics.createSingleColorTexture( 1, 1, Color.Transparent ); // populate squares yield return Core.startCoroutine( tickEffectProgressProperty( _squaresEffect, squaresInDuration, easeType ) ); // load up the new Scene yield return Core.startCoroutine( loadNextScene() ); // dispose of our previousSceneRender. We dont need it anymore. previousSceneRender.Dispose(); previousSceneRender = null; // delay yield return Coroutine.waitForSeconds( delayBeforeSquaresInDuration ); // unpopulate squares yield return Core.startCoroutine( tickEffectProgressProperty( _squaresEffect, squaresInDuration, EaseHelper.oppositeEaseType( easeType ), true ) ); transitionComplete(); // cleanup _overlayTexture.Dispose(); Core.content.unloadEffect( _squaresEffect.Name ); }
public void Unload(Texture2D texture) { if (texture != null) { texture.Dispose(); } }
static void GenerateNoiseMap(int width, int height, ref Texture2D noiseTexture, int octaves) { var data = new float[width*height]; /// track min and max noise value. Used to normalize the result to the 0 to 1.0 range. var min = float.MaxValue; var max = float.MinValue; /// rebuild the permutation table to get a different noise pattern. /// Leave this out if you want to play with changing the number of octaves while /// maintaining the same overall pattern. Noise2d.Reseed(); var frequency = 10.0f; var amplitude = 200.0f; for (var octave = 0; octave < octaves; octave++) { /// parallel loop - easy and fast. Parallel.For(0 , width * height , (offset) => { var i = offset % width; var j = offset / width; var noise = Noise2d.Noise(i * frequency * 1f / width, j * frequency * 1f / height); noise = data[j * width + i] += noise * amplitude; min = Math.Min(min, noise); max = Math.Max(max, noise); } ); frequency *= 2; amplitude /= 2; } if (noiseTexture != null && (noiseTexture.Width != width || noiseTexture.Height != height)) { noiseTexture.Dispose(); noiseTexture = null; } if (noiseTexture == null) { noiseTexture = new Texture2D(device, width, height, false, SurfaceFormat.Color); } var colors = data.Select( (f) => { var norm = (f - min) / (max - min); return new Color(norm, norm, norm, 1); } ).ToArray(); noiseTexture.SetData(colors); }
void MakeScreenshot() { int w = ROClient.Singleton.GraphicsDevice.PresentationParameters.BackBufferWidth; int h = ROClient.Singleton.GraphicsDevice.PresentationParameters.BackBufferHeight; Draw(new GameTime()); int[] backBuffer = new int[w * h]; ROClient.Singleton.GraphicsDevice.GetBackBufferData(backBuffer); //copy into a texture Texture2D texture = new Texture2D(ROClient.Singleton.GraphicsDevice, w, h, false, GraphicsDevice.PresentationParameters.BackBufferFormat); texture.SetData(backBuffer); //save to disk if (!System.IO.Directory.Exists("ScreenShot")) System.IO.Directory.CreateDirectory("ScreenShot"); Stream stream = File.OpenWrite(System.IO.Path.Combine("ScreenShot", "screen" + _counter + ".png")); texture.SaveAsPng(stream, w, h); stream.Dispose(); texture.Dispose(); _counter++; }
//void movecam() //{ // Matrix m = Matrix.CreateTranslation(p.Position) * Matrix.CreateFromQuaternion(quat) * Matrix.CreateTranslation(-p.Position); // mover = Vector3.Transform(Vector3.Forward, m); // u = Vector3.Transform(Vector3.Up, m); // pos = p.Position + (u * 2.5f); // tar = pos - Vector3.Transform(new Vector3(0, 0, 1), m); // Console.WriteLine(pos); // Console.WriteLine(tar + "," + pos + "," + u); // cam.Position = pos; // cam.Up = u; // cam.Target = tar; //} float[,] getheights(Texture2D text, out int width, out int length) { width = text.Width; length = text.Height; Texture2D texture = text; Color[] color = new Color[width * length]; texture.GetData<Color>(color); float[,] heights = new float[width, length]; for (int x = 0; x < width; x++) for (int z = 0; z < length; z++) { heights[x, z] = color[x + z * width].R; } text.Dispose(); return heights; }
public void destroyContent(Texture2D texture) { texture.Dispose(); }
public static void Screenshot(GraphicsDevice device) { byte[] screenData; screenData = new byte[device.PresentationParameters.BackBufferWidth * device.PresentationParameters.BackBufferHeight * 4]; device.GetBackBufferData<byte>(screenData); Texture2D t2d = new Texture2D(device, device.PresentationParameters.BackBufferWidth, device.PresentationParameters.BackBufferHeight, false, device.PresentationParameters.BackBufferFormat); t2d.SetData<byte>(screenData); int i = 0; string name = "ScreenShot" + i.ToString() + ".png"; while (File.Exists(name)) { i += 1; name = "ScreenShot" + i.ToString() + ".png"; } Stream st = new FileStream(name, FileMode.Create); t2d.SaveAsPng(st, t2d.Width, t2d.Height); st.Close(); t2d.Dispose(); }
protected override void Update(GameTime gt) { KeyboardState kb = Keyboard.GetState(); if(state == GameState.Menu) { if(menuMusic.State != SoundState.Playing) menuMusic.Play(); if(gameMusic.State == SoundState.Playing) gameMusic.Stop(); menu.updateMenu(); if(kb.IsKeyDown(Keys.F1) && !helpPrevPressed) state = GameState.Help; } else if(endTimer == 0 && state == GameState.InGame) { if(menuMusic.State == SoundState.Playing) menuMusic.Stop(); if(gameMusic.State != SoundState.Playing) gameMusic.Play(); playingField.update(gt); } else if(endTimer == 0) { if(kb.IsKeyDown(Keys.F1) && !helpPrevPressed) state = GameState.Menu; } else { endTimer++; if(endTimer > 100) { playingField = null; state = GameState.Menu; endTimer = 0; } } if(Controls.screenshotPressed && !screenshotPrev) { ssCount += 1; int w = GraphicsDevice.PresentationParameters.BackBufferWidth; int h = GraphicsDevice.PresentationParameters.BackBufferHeight; Draw(new GameTime()); int[] backBuffer = new int[w * h]; GraphicsDevice.GetBackBufferData(backBuffer); Texture2D texture = new Texture2D(GraphicsDevice, w, h, false, GraphicsDevice.PresentationParameters.BackBufferFormat); texture.SetData(backBuffer); Stream stream = File.OpenWrite("ss" + ssCount + ".png"); texture.SaveAsPng(stream, w, h); stream.Dispose(); texture.Dispose(); } elapsedTime += (float) gt.ElapsedGameTime.TotalSeconds; totalFrames++; if(elapsedTime >= 1.0f) { fps = totalFrames; totalFrames = 0; elapsedTime = 0; } Window.Title = "Nano Commander : " + fps + " fps"; screenshotPrev = Controls.screenshotPressed; helpPrevPressed = kb.IsKeyDown(Keys.F1); base.Update(gt); }
/// <summary> /// Dispose /// </summary> /// <param name="someObject">Some object</param> public static void Dispose(ref Texture2D someObject) { if (someObject != null) someObject.Dispose(); someObject = null; }
protected void SetTexture(Texture2D tex) { lock (this) { //Trace.WriteLine("SetTexture: " + this.Filename.ToString()); if (IsDisposed && tex != null) { tex.Dispose(); Global.RemoveTexture(tex); tex = null; } if (BodyRequestState != null) { this.BodyRequestState.Dispose(); this.BodyRequestState = null; } this._Result = tex; this.FinishedReading = true; graphicsDevice = null; if(!IsDisposed) DoneEvent.Set(); } }
public override IEnumerator onBeginTransition() { // create a single pixel transparent texture so we can do our squares out to the next scene _overlayTexture = Graphics.createSingleColorTexture( 1, 1, Color.Transparent ); // obscure the screen yield return Core.startCoroutine( tickEffectProgressProperty( _textureWipeEffect, duration, easeType ) ); // load up the new Scene yield return Core.startCoroutine( loadNextScene() ); // dispose of our previousSceneRender. We dont need it anymore. previousSceneRender.Dispose(); previousSceneRender = null; // undo the effect yield return Core.startCoroutine( tickEffectProgressProperty( _textureWipeEffect, duration, EaseHelper.oppositeEaseType( easeType ), true ) ); transitionComplete(); // cleanup _overlayTexture.Dispose(); Core.content.unloadEffect( _textureWipeEffect ); }
public static void PrintMap(SpriteBatch spriteBatch, bool drawBase, bool drawFringe, bool drawObject, Texture2D printTex) { Texture2D t2d = new Texture2D(spriteBatch.GraphicsDevice, map.Texture.Width, map.Texture.Height, false, spriteBatch.GraphicsDevice.PresentationParameters.BackBufferFormat); // check the parameters if (spriteBatch == null) { throw new ArgumentNullException("spriteBatch"); } if (!drawBase && !drawFringe && !drawObject) { return; } Rectangle destinationRectangle = new Rectangle(0, 0, map.TileSize.X/2, map.TileSize.Y/2); for (int y = 0; y < map.MapDimensions.Y; y++) { for (int x = 0; x < map.MapDimensions.X; x++) { destinationRectangle.X = x * map.TileSize.X/2; destinationRectangle.Y = y * map.TileSize.Y/2; if (true) { Point mapPosition = new Point(x, y); if (drawBase) { int baseLayerValue = map.GetBaseLayerValue(mapPosition) - 1; Rectangle sourceRectangle = new Rectangle( (baseLayerValue % map.TilesPerRow) * map.TileSize.X/2, (baseLayerValue / map.TilesPerRow) * map.TileSize.Y/2, map.TileSize.X / 2, map.TileSize.Y / 2); if (sourceRectangle != Rectangle.Empty) { if ((x > 0 && x < 64) && (y > 0 && y < 64)) { byte[] tileData = new byte[sourceRectangle.Width * sourceRectangle.Height * 4]; printTex.GetData(0, sourceRectangle, tileData, 0, tileData.Length); t2d.SetData<byte>(0, destinationRectangle, tileData, 0, tileData.Length); } } } if (drawFringe) { int fringeLayerValue = map.GetFringeLayerValue(mapPosition) - 1; Rectangle sourceRectangle = new Rectangle( (fringeLayerValue % map.TilesPerRow) * map.TileSize.X / 2, (fringeLayerValue / map.TilesPerRow) * map.TileSize.Y / 2, map.TileSize.X / 2, map.TileSize.Y / 2); if (sourceRectangle != Rectangle.Empty && fringeLayerValue >= 0) { if ((x > 0 && x < 64) && (y > 0 && y < 64)) { byte[] tileData = new byte[sourceRectangle.Width * sourceRectangle.Height * 4]; printTex.GetData(0, sourceRectangle, tileData, 0, tileData.Length); t2d.SetData<byte>(0, destinationRectangle, tileData, 0, tileData.Length); } } } if (drawObject) { int objectLayerValue = map.GetObjectLayerValue(mapPosition) - 1; Rectangle sourceRectangle = new Rectangle( (objectLayerValue % map.TilesPerRow) * map.TileSize.X / 2, (objectLayerValue / map.TilesPerRow) * map.TileSize.Y / 2, map.TileSize.X / 2, map.TileSize.Y / 2); if (sourceRectangle != Rectangle.Empty && objectLayerValue >= 0) { if ((x > 0 && x < 64) && (y > 0 && y < 64)) { byte[] tileData = new byte[sourceRectangle.Width * sourceRectangle.Height * 4]; printTex.GetData(0, sourceRectangle, tileData, 0, tileData.Length); t2d.SetData<byte>(0, destinationRectangle, tileData, 0, tileData.Length); } } } } } } int i = 0; string name = "ScreenShot" + i.ToString() + ".png"; while (File.Exists(name)) { i += 1; name = "ScreenShot" + i.ToString() + ".png"; } Stream st = new FileStream(name, FileMode.Create); t2d.SaveAsPng(st, t2d.Width, t2d.Height); st.Close(); t2d.Dispose(); }
public void screenshot() { count += 1; DateTime debugDate = DateTime.Now; string filename = debugDate.Year + "" + debugDate.Month + "" + debugDate.Day + "." + debugDate.Hour + "" + debugDate.Minute + "" + debugDate.Second + "."; filename += count.ToString(); int w = GraphicsDevice.PresentationParameters.BackBufferWidth; int h = GraphicsDevice.PresentationParameters.BackBufferHeight; //force a frame to be drawn (otherwise back buffer is empty) Draw(new GameTime()); //pull the picture from the buffer int[] backBuffer = new int[w * h]; GraphicsDevice.GetBackBufferData(backBuffer); //copy into a texture Texture2D texture = new Texture2D(GraphicsDevice, w, h, false, GraphicsDevice.PresentationParameters.BackBufferFormat); texture.SetData(backBuffer); //save to disk Stream stream = File.OpenWrite(filename + ".png"); texture.SaveAsPng(stream, w, h); stream.Dispose(); texture.Dispose(); }
public void SaveImage(string path) { Texture2D t = new Texture2D(Renderer.GD, (int)Size.X, (int)Size.Y); Color[] data = new Color[(int)Size.X * (int)Size.Y]; int i = 0; for (int y = 0; y < (int)Size.Y; y++) { for (int x = 0; x < (int)Size.X; x++) { if (GetCostArray()[x, y] == 0) data[i++] = new Color(0, 0, 0); else { data[i++] = new Color(255, 255, 255); } } } t.SetData<Color>(data); DateTime date = DateTime.Now; //Get the date for the file name if(!Directory.Exists(path + "/Mapa ")) { Directory.CreateDirectory(path + "/Mapa "); } Stream stream = File.Create(path + "/Mapa " + date.ToString("dd-MM-yy H_mm_ss") + ".png"); //Save as PNG t.SaveAsPng(stream, (int)Size.X, (int)Size.Y); Logger.Write("Saved map png"); stream.Dispose(); t.Dispose(); }