本文整理汇总了C#中Microsoft.Xna.Framework.Graphics.RenderTarget2D.SaveAsPng方法的典型用法代码示例。如果您正苦于以下问题:C# RenderTarget2D.SaveAsPng方法的具体用法?C# RenderTarget2D.SaveAsPng怎么用?C# RenderTarget2D.SaveAsPng使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Microsoft.Xna.Framework.Graphics.RenderTarget2D
的用法示例。
在下文中一共展示了RenderTarget2D.SaveAsPng方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: LeakRepro
void LeakRepro()
{
for (int i = 0; i < 50; i++)
{
var rt = new RenderTarget2D(
GraphicsDevice,
800, 480,
false, SurfaceFormat.Color,
DepthFormat.None, 0,
RenderTargetUsage.PreserveContents);
GraphicsDevice.SetRenderTarget(rt);
GraphicsDevice.Clear(Color.Green);
GraphicsDevice.SetRenderTarget(null);
MemoryStream ms = new MemoryStream();
rt.SaveAsPng(ms, 800, 480);
ms.Close();
rt.Dispose();
}
GC.Collect();
List<string> buttons = new List<string>();
buttons.Add("Close");
var message = string.Format(
"Total memory: {0}\n" +
"Used memory: {1}\n",
DeviceExtendedProperties.GetValue("DeviceTotalMemory").ToString(),
DeviceExtendedProperties.GetValue("ApplicationCurrentMemoryUsage").ToString()
);
IAsyncResult ar = Guide.BeginShowMessageBox("Info",
message,
buttons, 0,
MessageBoxIcon.None, null, null);
Guide.EndShowMessageBox(ar);
}
示例2: Generate
public void Generate(Block[,,] blocks, ChunkInfo info)
{
while (RuntimeGame.DeviceForStateValidationOutput == null)
continue;
lock (RuntimeGame.LockForStateValidationOutput)
{
Console.Write("Locked graphics. Rendering graph to file...");
RainfallInformation rainfall = info.Objects.First(val => val is RainfallInformation) as RainfallInformation;
TemperatureInformation temperature = info.Objects.First(val => val is TemperatureInformation) as TemperatureInformation;
PresentationParameters pp = RuntimeGame.DeviceForStateValidationOutput.PresentationParameters;
RenderTarget2D renderTarget = new RenderTarget2D(RuntimeGame.DeviceForStateValidationOutput, 200, 200, true, RuntimeGame.DeviceForStateValidationOutput.DisplayMode.Format, DepthFormat.Depth24);
RuntimeGame.DeviceForStateValidationOutput.SetRenderTarget(renderTarget);
RuntimeGame.ContextForStateValidationOutput.SpriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.PointClamp, DepthStencilState.Default, RasterizerState.CullNone);//, SaveStateMode.None, Matrix.Identity);
//graphics.GraphicsDevice.SamplerStates[0].MagFilter = TextureFilter.Point;
//graphics.GraphicsDevice.SamplerStates[0].MinFilter = TextureFilter.Point;
//graphics.GraphicsDevice.SamplerStates[0].MipFilter = TextureFilter.Point;
XnaGraphics graphics = new XnaGraphics(RuntimeGame.ContextForStateValidationOutput);
if (File.Exists("state.png"))
{
using (StreamReader reader = new StreamReader("state.png"))
{
Texture2D tex = Texture2D.FromStream(RuntimeGame.DeviceForStateValidationOutput, reader.BaseStream);
RuntimeGame.ContextForStateValidationOutput.SpriteBatch.Draw(tex, new Rectangle(0, 0, 200, 200), Color.White);
}
}
else
{
graphics.FillRectangle(0, 0, 200, 200, Color.Red);
graphics.FillRectangle(0, 0, 100, 100, Color.White);
}
for (int x = 0; x < info.Bounds.Width; x++)
for (int y = 0; y < info.Bounds.Height; y++)
{
int r = 100 - (int)(rainfall.Rainfall[x, y] * 100);
int t = 100 - (int)(temperature.Temperature[x, y] * 100);
graphics.DrawLine(r, t, r + 1, t + 1, 1, new Color(0f, 0f, 0f, 0.1f).ToPremultiplied());
}
RuntimeGame.ContextForStateValidationOutput.SpriteBatch.End();
RuntimeGame.DeviceForStateValidationOutput.SetRenderTarget(null);
using (StreamWriter writer = new StreamWriter("state.png"))
{
renderTarget.SaveAsPng(writer.BaseStream, 200, 200);
}
Console.WriteLine(" done.");
}
}
示例3: OnClick
void OnClick()
{
Directory.CreateDirectory("Chunks");
IsometricLighting lighting = new IsometricLighting();
MouseOverList mouseOverNull = new MouseOverList(new MousePicking());
SpriteBatch3D spritebatch = Service.Get<SpriteBatch3D>();
RenderTarget2D render = new RenderTarget2D(spritebatch.GraphicsDevice, Width + WidthExtra * 2, Height + HeightExtra * 2 + HeightExtra2);
Map map = new Map(0);
for (int chunky = 0; chunky < 10; chunky++)
{
for (int chunkx = 0; chunkx < 10; chunkx++)
{
spritebatch.GraphicsDevice.SetRenderTarget(render);
spritebatch.Reset();
uint cx = (uint)chunkx + 200;
uint cy = (uint)chunky + 200;
map.CenterPosition = new Point((int)(cx << 3), (int)(cy << 3));
MapChunk chunk = map.GetMapChunk(cx, cy);
chunk.LoadStatics(map.MapData, map);
int z = 0;
for (int i = 0; i < 64; i++)
{
int y = (i / 8);
int x = (i % 8);
int sy = y * 22 + x * 22 + HeightExtra + HeightExtra2;
int sx = 22 * 8 - y * 22 + x * 22 + WidthExtra;
MapTile tile = chunk.Tiles[i];
tile.ForceSort();
for (int j = 0; j < tile.Entities.Count; j++)
{
AEntity e = tile.Entities[j];
AEntityView view = e.GetView();
view.Draw(spritebatch, new Vector3(sx, sy, 0), mouseOverNull, map, false);
}
}
spritebatch.SetLightIntensity(lighting.IsometricLightLevel);
spritebatch.SetLightDirection(lighting.IsometricLightDirection);
spritebatch.GraphicsDevice.Clear(Color.Transparent);
spritebatch.FlushSprites(true);
spritebatch.GraphicsDevice.SetRenderTarget(null);
render.SaveAsPng(new FileStream($"Chunks/{cy}-{cx}.png", FileMode.Create), render.Width, render.Height);
}
}
}
示例4: UpdateWindow
public void UpdateWindow()
{
tempTextureToConvert = GameFiles.TextureEditorRenderTarget2D;
MemoryStream tempMemoryStream = new MemoryStream();
tempTextureToConvert.SaveAsPng(tempMemoryStream, tempTextureToConvert.Width, tempTextureToConvert.Height);
tempMemoryStream.Seek(0, SeekOrigin.Begin);
Image tempImageToUpdate = System.Drawing.Bitmap.FromStream(tempMemoryStream);
tempMemoryStream.Close();
tempMemoryStream = null;
iTextureGraphic.Image = tempImageToUpdate;
Invalidate();
/*
if (FileManager.Get().GizmoSelection != null && FileManager.Get().GizmoSelection.Count >= 1)
{
tempTextureToConvert = FileManager.Get().GizmoSelection[0].RenderTarget;
MemoryStream tempMemoryStream = new MemoryStream();
tempTextureToConvert.SaveAsPng(tempMemoryStream, tempTextureToConvert.Width, tempTextureToConvert.Height);
tempMemoryStream.Seek(0, SeekOrigin.Begin);
Image tempImageToUpdate = System.Drawing.Bitmap.FromStream(tempMemoryStream);
tempMemoryStream.Close();
tempMemoryStream = null;
iTextureGraphic.Image = tempImageToUpdate;
Invalidate();
}
*/
}
示例5: ExportAnimation
public static void ExportAnimation(string folderPath, string nameStarter, int width, int height,
float framesPerSecond, float totalTime, GraphicsDevice gd, Action<float> update,
Action<SpriteBatch, Rectangle> draw, int antialiasingMultiplier = 1)
{
var width1 = width*antialiasingMultiplier;
var height1 = height*antialiasingMultiplier;
var renderTarget = new RenderTarget2D(gd, width1, height1, false, SurfaceFormat.Rgba64, DepthFormat.Depth16,
8, RenderTargetUsage.PlatformContents);
var spriteBatch1 = new SpriteBatch(gd);
gd.PresentationParameters.MultiSampleCount = 8;
var currentRenderTarget = Utils.GetCurrentRenderTarget();
gd.SetRenderTarget(renderTarget);
var num1 = 1f/framesPerSecond;
var num2 = 0.0f;
var num3 = 0;
if (!Directory.Exists(folderPath))
Directory.CreateDirectory(folderPath);
var spriteBatch2 = GuiData.spriteBatch;
GuiData.spriteBatch = spriteBatch1;
var rectangle = new Rectangle(0, 0, width1, height1);
while (num2 < (double) totalTime)
{
gd.Clear(Color.Transparent);
spriteBatch1.Begin();
draw(spriteBatch1, rectangle);
spriteBatch1.End();
update(num1);
gd.SetRenderTarget(null);
var str = string.Concat(nameStarter, "_", num3, ".png");
using (var fileStream = File.Create(folderPath + "/" + str))
renderTarget.SaveAsPng(fileStream, width, height);
gd.SetRenderTarget(renderTarget);
++num3;
num2 += num1;
}
GuiData.spriteBatch = spriteBatch2;
gd.SetRenderTarget(currentRenderTarget);
}
示例6: CreateTexture
private void CreateTexture()
{
Vector2 textSize = spriteFont.MeasureString(text);
int textureWidth = (int)Math.Pow(2, Math.Ceiling(Math.Log(textSize.X, 2)));
int textureHeight = (int)Math.Pow(2, Math.Ceiling(Math.Log(textSize.Y, 2)));
fontTexture = new Texture2D(spriteBatch.GraphicsDevice, textureWidth, textureHeight);
RenderTarget2D target = new RenderTarget2D(spriteBatch.GraphicsDevice, textureWidth, textureHeight);
BasicEffect effect = new BasicEffect(spriteBatch.GraphicsDevice);
effect.TextureEnabled = true;
effect.VertexColorEnabled = true;
effect.CurrentTechnique.Passes[0].Apply();
spriteBatch.GraphicsDevice.SetRenderTarget(target);
spriteBatch.GraphicsDevice.Clear(Color.Transparent);
spriteBatch.Begin();
spriteBatch.DrawString(spriteFont, text, Vector2.Zero, Color.Black);
spriteBatch.End();
spriteBatch.GraphicsDevice.SetRenderTarget(null);
target.SaveAsPng(new FileStream("testText.png", FileMode.Create), textureWidth, textureHeight);
Color[] textureData = new Color[textureWidth * textureHeight];
target.GetData<Color>(textureData);
fontTexture.SetData<Color>(textureData);
effect.TextureEnabled = true;
effect.Texture = fontTexture;
//screenPoints[0].TextureCoordinate = new Vector2(0, 0);
//screenPoints[1].TextureCoordinate = new Vector2(1, 0);
//screenPoints[2].TextureCoordinate = new Vector2(1, 1);
//screenPoints[3].TextureCoordinate = new Vector2(0, 1);
screenPoints[0].TextureCoordinate = new Vector2(0, 0);
screenPoints[1].TextureCoordinate = new Vector2(textSize.X / textureWidth, 0);
screenPoints[2].TextureCoordinate = new Vector2(textSize.X / textureWidth, textSize.Y / textureHeight);
screenPoints[3].TextureCoordinate = new Vector2(0, textSize.Y / textureHeight);
}
示例7: SavePictureOfMap
public void SavePictureOfMap(string loc) {
GraphicsDevice graphicsdevice = World.ViewData.GraphicsDevice;
RenderTarget2D target = new RenderTarget2D(graphicsdevice, CurrentMap.Width << 4, CurrentMap.Height << 4);
graphicsdevice.SetRenderTarget(target);
Vector2 cScrolling = World.Camera.Location;
float cScale = World.Camera.Scale;
float cRotation = World.Camera.Rotation;
World.Camera.Reset();
RenderMap(CurrentMap);
World.Camera.Location = cScrolling;
World.Camera.Scale = cScale;
World.Camera.Rotation = cRotation;
graphicsdevice.SetRenderTarget(null);
using (FileStream fs = File.OpenWrite(loc)) {
target.SaveAsPng(fs, target.Width, target.Height);
}
}
示例8: MenuExtrasMapPreview_Click
private void MenuExtrasMapPreview_Click(object sender, EventArgs e) {
if (mTileMap == null || mTileMap.Width == 0 || mTileMap.Height == 0) {
return;
}
var watch = Stopwatch.StartNew();
var pp = GraphicsDevice.PresentationParameters;
var renderTarget = new RenderTarget2D(GraphicsDevice, pp.BackBufferWidth, pp.BackBufferHeight);
var toDelete = new List<string>();
var mapBmp = new Bitmap(mTileMap.WidthInPixels, mTileMap.HeightInPixels);
var g = Graphics.FromImage(mapBmp);
Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + "Preview");
// reset MapView to always display first Screen
SetZoom(1.0f);
MapVScrollBar.Value = 0;
MapHScrollBar.Value = 0;
mCamera.X = 0;
mCamera.Y = 0;
var end = Point2D.Zero;
var viewable = new Point2D(RenderDisplayMap.Width / mCamera.TileWidth, RenderDisplayMap.Height / mCamera.TileHeight);
for (var mapX = 0; mapX < mTileMap.Width; mapX += viewable.X) {
for (var mapY = 0; mapY < mTileMap.Height; mapY += viewable.Y) {
GraphicsDevice.SetRenderTarget(renderTarget);
GraphicsDevice.Clear(Color.Black);
var start = new Point2D(mapX, mapY);
end.X = Math.Min(start.X + viewable.X, mTileMap.Width);
end.Y = Math.Min(start.Y + viewable.Y, mTileMap.Height);
mSpriteBatch.Begin();
mTileMap.Draw(mSpriteBatch, mCamera, mGameTime.ElapsedGameTime.TotalSeconds, (ETileDrawType.BackGround | ETileDrawType.ForeGround | ETileDrawType.Animation), start, end, true);
mSpriteBatch.End();
GraphicsDevice.SetRenderTarget(null);
var texPath = String.Format(@"{0}Preview\{1}_{2}x{3}.png", AppDomain.CurrentDomain.BaseDirectory, mTileMap.Name, mapX, mapY);
renderTarget.SaveAsPng(File.OpenWrite(texPath), renderTarget.Width, renderTarget.Height);
using (var img = Image.FromFile(texPath)) {
g.DrawImage(img, new Point(mapX * mCamera.TileWidth, mapY * mCamera.TileHeight));
}
//mapBmp.Save( String.Format( @"{0}Preview\{1}_Full_{2}x{3}.png", AppDomain.CurrentDomain.BaseDirectory, mTileMap.Name, mapX, mapY ), System.Drawing.Imaging.ImageFormat.Png );
toDelete.Add(texPath);
}
}
// save & clean
try {
g.Save();
mapBmp.Save(AppDomain.CurrentDomain.BaseDirectory + @"Preview\" + mTileMap.Name + "_Full.png", ImageFormat.Png);
mapBmp.Dispose();
g.Dispose();
} catch (Exception ex) {
Debug.WriteLine(ex);
}
foreach (var filepath in toDelete) {
try {
File.Delete(filepath);
} catch {
}
}
toDelete.Clear();
MessageBox.Show("Preview erstellt!\nBenötigte Zeit: " + (watch.ElapsedMilliseconds / 1000) + "sec");
watch.Stop();
}
示例9: DumpAll
public void DumpAll(string dumploc) {
for (int i = 0; i < BUFFER_SIZE; i++) {
Selection selection = Buffer[i];
Rectangle selrect = selection.Region;
if (selrect != Rectangle.Empty) {
RenderTarget2D target = new RenderTarget2D(GraphicsDevice, selrect.Width, selrect.Height);
GraphicsDevice.SetRenderTarget(target);
GraphicsDevice.Clear(Color.Transparent);
SpriteBatch spriteBatch = new SpriteBatch(GraphicsDevice);
spriteBatch.Begin();
spriteBatch.Draw(Texture, new Rectangle(0, 0, selrect.Width, selrect.Height), new Rectangle(selrect.X, selrect.Y, selrect.Width, selrect.Height), Color.White);
spriteBatch.End();
GraphicsDevice.SetRenderTarget(null);
using (FileStream stream = File.OpenWrite(dumploc + "\\" + i + ".png")) {
target.SaveAsPng(stream, target.Width, target.Height);
stream.Flush();
stream.Close();
}
}
}
}
示例10: ComputeLightMap
public void ComputeLightMap(SpriteBatch batch, Map map, string Path)
{
Camera cam = new Camera(Vector2.Zero, map.MapBoundaries);
cam.Zoom(-1);
Vector2 viewFieldDiagonal = new Vector2(cam.ViewSpace.Width *0.5f, cam.ViewSpace.Height *0.5f);
cam.SetPos(viewFieldDiagonal);
lightMapTarget = new RenderTarget2D(device, map.MapBoundaries.Width, map.MapBoundaries.Height,false, SurfaceFormat.Color, DepthFormat.Depth24Stencil8);
Matrix baseProjection = cam.ProjectionMatrix;
map.SetUpLightMapPrecomputeLights();
device.SetRenderTarget(lightMapTarget);
//Clear Target first
device.DepthStencilState = clearStencil;
device.RasterizerState = RasterizerState.CullNone;
device.BlendState = BlendState.Opaque;
shadowEffect.Parameters["View"].SetValue(cam.ViewMatrix);
shadowEffect.Parameters["Projection"].SetValue(Matrix.Identity);
shadowEffect.Parameters["shadowDarkness"].SetValue(0.9f - 1);
shadowEffect.Parameters["viewDistance"].SetValue((float)(1 / (0.001f + 0.999 )));
shadowEffect.CurrentTechnique = shadowEffect.Techniques["Clear"];
device.SetVertexBuffer(clearVBuffer);
device.Indices = clearIBuffer;
shadowEffect.CurrentTechnique.Passes[0].Apply();
device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, 4, 0, 2);
//Matrix UpperLeftShift = Matrix.CreateTranslation(-1+(float)cam.ViewSpace.Width / (float)map.MapBoundaries.Width, 1-(float)cam.ViewSpace.Height / (float)map.MapBoundaries.Height, 0);
//cam.ProjectionMatrix = baseProjection * Matrix.CreateScale((float)cam.ViewSpace.Width / map.MapBoundaries.Width, (float)cam.ViewSpace.Height / map.MapBoundaries.Height, 1) * UpperLeftShift * Matrix.CreateTranslation(cam.ViewSpace.Left / map.MapBoundaries.Width, cam.ViewSpace.Top / map.MapBoundaries.Height, 0);
DrawLights(1, cam, batch, lightMapTarget);
//cam.Move(new Vector2(0, viewFieldDiagonal.Y * 2));
RenderTarget2D blurTarget = new RenderTarget2D(device,lightMapTarget.Width,lightMapTarget.Height);
shadowEffect.Parameters["xTexelDist"].SetValue(1.0f / (blurTarget.Width / lightMapDownSample));
shadowEffect.Parameters["yTexelDist"].SetValue(1.0f / (blurTarget.Height / lightMapDownSample));
BlurShadowTarget(batch, lightMapTarget, blurTarget);
BlurShadowTarget(batch, lightMapTarget, blurTarget);
shadowEffect.Parameters["xTexelDist"].SetValue(1.0f / (device.PresentationParameters.BackBufferWidth / lightMapDownSample));
shadowEffect.Parameters["yTexelDist"].SetValue(1.0f / (device.PresentationParameters.BackBufferHeight / lightMapDownSample));
device.SetRenderTarget(null);
Clear();
System.IO.FileStream fs = System.IO.File.Open(Path, System.IO.FileMode.Create);
lightMapTarget.SaveAsPng(fs, lightMapTarget.Width, lightMapTarget.Height);
fs.Close();
lightMap = lightMapTarget;
_hasLightmap = true;
}
示例11: SaveResults
public void SaveResults(string loc) {
List<Texture2D> result = new List<Texture2D>();
for (int i = 0; i < points.Length; i++) {
List<Vector2> _points = points[i];
if (_points.Count > 0) {
int xmin = Int32.MaxValue;
int xmax = -1;
int ymin = Int32.MaxValue;
int ymax = -1;
foreach (Vector2 point in _points) {
if (point.X < xmin)
xmin = (int)point.X;
if (point.Y < ymin)
ymin = (int)point.Y;
if (point.X > xmax)
xmax = (int)point.X;
if (point.Y > ymax)
ymax = (int)point.Y;
}
int w = xmax * 16 - xmin * 16;
int h = ymax * 16 - ymin * 16;
w += 16;
h += 16;
RenderTarget2D target = new RenderTarget2D(GraphicsDevice, w, h);
GraphicsDevice.SetRenderTarget(target);
GraphicsDevice.Clear(Color.Transparent);
SpriteBatch batch = new SpriteBatch(GraphicsDevice);
batch.Begin();
foreach (Vector2 point in _points) {
Rectangle rect = new Rectangle((int)point.X << 4, (int)point.Y << 4, 16, 16);
batch.Draw(Tileset.Texture.Texture, new Vector2(((int)point.X << 4) - xmin * 16, ((int)point.Y << 4) - ymin * 16), rect, Color.White);
}
batch.End();
GraphicsDevice.SetRenderTarget(null);
using (FileStream stream = File.OpenWrite(loc + "\\" + i + ".png")) {
target.SaveAsPng(stream, target.Width, target.Height);
stream.Flush();
stream.Close();
}
}
}
}
示例12: save
void save(RenderTarget2D r, string n = "ololo")
{
var t = graphics.GraphicsDevice.GetRenderTargets();
graphics.GraphicsDevice.SetRenderTarget(null);
using (var fstr = File.OpenWrite(n + ".png"))
{
r.SaveAsPng(fstr, graphics.PreferredBackBufferWidth, graphics.PreferredBackBufferHeight);
}
graphics.GraphicsDevice.SetRenderTargets(t);
}
示例13: OutputRendertarget
public static void OutputRendertarget(RenderTarget2D rt2dSource, string sDirectory, string sFileName)
{
if (!Directory.Exists("sDirectory"))
{
Directory.CreateDirectory("sDirectory");
}
FileStream mos = new FileStream(sDirectory + "/" + sFileName, FileMode.Create, FileAccess.Write);
rt2dSource.SaveAsPng(mos, rt2dSource.Width, rt2dSource.Height);
mos.Close();
}
示例14: CheckKeyboardMouseInput
private void CheckKeyboardMouseInput()
{
#region take these out
if(MainGame.GlobalInputHelper.CurrentKeyboardState.IsKeyDown(Keys.Up))
{
MainGame.GameCamera.Move(new Vector2i(0, -1));
}
if (MainGame.GlobalInputHelper.CurrentKeyboardState.IsKeyDown(Keys.Right))
{
MainGame.GameCamera.Move(new Vector2i(1, 0));
}
if (MainGame.GlobalInputHelper.CurrentKeyboardState.IsKeyDown(Keys.Down))
{
MainGame.GameCamera.Move(new Vector2i(0, 1));
}
if (MainGame.GlobalInputHelper.CurrentKeyboardState.IsKeyDown(Keys.Left))
{
MainGame.GameCamera.Move(new Vector2i(-1, 0));
}
if(MainGame.GlobalInputHelper.CurrentKeyboardState.IsKeyDown(Keys.R))
{
world.GetClientPlayer().Move(new Vector2(22 * 32, 16 * 32));
}
#endregion
if (MainGame.GlobalInputHelper.IsMouseInsideWindow())
{
#if DEBUG
if(MainGame.GlobalInputHelper.IsNewPress(Keys.F4))
{
MainGame.GameOptions.LightsDisabled = !MainGame.GameOptions.LightsDisabled;
}
if(MainGame.GlobalInputHelper.IsNewPress(Keys.L))
{
MainMessageQueue.AddMessage(new Minecraft2DMessage { Sender = "GAME", Content = "Test", Global = true });
}
#endif
if (MainGame.GlobalInputHelper.IsNewPress(Keys.F2))
{
if (!Directory.Exists("Screenshots"))
Directory.CreateDirectory("Screenshots");
DateTime nnow = DateTime.Now;
if (MainGame.GlobalInputHelper.CurrentKeyboardState.IsKeyDown(Keys.LeftAlt))
{
using (FileStream f = File.Create(Path.Combine("Screenshots", $"Screenshot_{nnow.Month}-{nnow.Day}-{nnow.Year}-{nnow.Hour}-{nnow.Minute}-{nnow.Second}.png")))
{
worldRenderTarget.SaveAsPng(f,
MainGame.GlobalGraphicsDeviceManager.PreferredBackBufferWidth, MainGame.GlobalGraphicsDeviceManager.PreferredBackBufferHeight);
f.Close();
}
MainMessageQueue.AddMessage(new Minecraft2DMessage { Content = "Screenshot captured!", Global = false, To = MainGame.GameOptions.Username });
}
else
{
RenderTarget2D allTogether = new RenderTarget2D(MainGame.GlobalGraphicsDevice, MainGame.GlobalGraphicsDeviceManager.PreferredBackBufferWidth, MainGame.GlobalGraphicsDeviceManager.PreferredBackBufferHeight);
MainGame.GlobalGraphicsDevice.SetRenderTarget(allTogether);
MainGame.GlobalGraphicsDevice.Clear(Color.White);
MainGame.GlobalSpriteBatch.Begin(SpriteSortMode.Texture, MainGame.Multiply, SamplerState.PointClamp, DepthStencilState.Default, RasterizerState.CullNone);
MainGame.GlobalSpriteBatch.Draw(worldRenderTarget, new Rectangle(0, 0, MainGame.GlobalGraphicsDeviceManager.PreferredBackBufferWidth, MainGame.GlobalGraphicsDeviceManager.PreferredBackBufferHeight), Color.White);
MainGame.GlobalSpriteBatch.Draw(worldLightmapPass, new Rectangle(0, 0, MainGame.GlobalGraphicsDeviceManager.PreferredBackBufferWidth, MainGame.GlobalGraphicsDeviceManager.PreferredBackBufferHeight), Color.White);
MainGame.GlobalSpriteBatch.End();
MainGame.GlobalGraphicsDevice.SetRenderTarget(null);
using (FileStream f = File.Create(Path.Combine("Screenshots", $"Screenshot_{nnow.Month}-{nnow.Day}-{nnow.Year}-{nnow.Hour}-{nnow.Minute}-{nnow.Second}.png")))
{
allTogether.SaveAsPng(f,
MainGame.GlobalGraphicsDeviceManager.PreferredBackBufferWidth, MainGame.GlobalGraphicsDeviceManager.PreferredBackBufferHeight);
f.Close();
}
MainMessageQueue.AddMessage(new Minecraft2DMessage { Content = "Screenshot captured!", Global = false, Sender = "GAME", To = MainGame.GameOptions.Username });
}
}
if (MainGame.GlobalInputHelper.CurrentMouseState.ScrollWheelValue > MainGame.GlobalInputHelper.LastMouseState.ScrollWheelValue)
{
currentTileIndex++;
if (currentTileIndex >= TilesList.Length)
currentTileIndex = 0;
PlacingTile = TilesList[currentTileIndex];
}
if (MainGame.GlobalInputHelper.CurrentMouseState.ScrollWheelValue < MainGame.GlobalInputHelper.LastMouseState.ScrollWheelValue)
{
currentTileIndex--;
if (currentTileIndex < 0)
currentTileIndex = TilesList.Length - 1;
PlacingTile = TilesList[currentTileIndex];
}
if (MainGame.GlobalInputHelper.CurrentMouseState.LeftButton == ButtonState.Pressed)
{
if (MainGame.GameCamera != null)
{
Matrix inverseViewMatrix = Matrix.Invert(MainGame.GameCamera.get_transformation(MainGame.GlobalGraphicsDevice));
Vector2 worldMousePosition = Vector2.Transform(new Vector2(MainGame.GlobalInputHelper.CurrentMouseState.X, MainGame.GlobalInputHelper.CurrentMouseState.Y), inverseViewMatrix);
Tile airP = PresetBlocks.TilesList.Find(x => x.Name == "minecraft:air").AsTile();
//.........这里部分代码省略.........
示例15: saveScreenShot
public void saveScreenShot(string filename)
{
Rectangle rect = new Rectangle(sx(0), sy(0), Maze.width, Maze.height);
int w = GraphicsDevice.PresentationParameters.BackBufferWidth;
int h = GraphicsDevice.PresentationParameters.BackBufferHeight;
RenderTarget2D screenShot = new RenderTarget2D(GraphicsDevice, w, h);
GraphicsDevice.SetRenderTarget(screenShot);
Draw(new GameTime());
GraphicsDevice.SetRenderTarget(null);
GraphicsDevice gd = screenShot.GraphicsDevice;
RenderTarget2D cropped = new RenderTarget2D(gd, Maze.width, Maze.height);
SpriteBatch sb = new SpriteBatch(gd);
gd.SetRenderTarget(cropped);
gd.Clear(new Color(0, 0, 0, 0));
sb.Begin();
sb.Draw(screenShot, Vector2.Zero, rect, Color.White);
sb.End();
gd.SetRenderTarget(null);
screenShot.Dispose();
using (FileStream stream = new FileStream(filename, FileMode.Create))
{
cropped.SaveAsPng(stream, cropped.Width, cropped.Height);
cropped.Dispose();
}
}