public Texture2D GetTexture(string name) { if (!_initialized) Initialize(); if (_textures.ContainsKey(name)) return _textures[name]; else { Rectangle r = RectangleFromName(name); if (r.Width > 1) { Color[] colors = new Color[_width * _height]; _texture.GetData<Color>(0, r, colors, 0, _width * _height); Texture2D tex = new Texture2D(MainApplication.Instance.GraphicsDevice, _width, _height); tex.SetData<Color>(0, new Rectangle(0, 0, _width, _height), colors, 0, _width * _height); _textures.Add(name, tex); return tex; } return null; } }
public static void Load(ContentManager content) { Player = content.Load<Texture2D>("Player"); Pixel = new Texture2D(Player.GraphicsDevice, 1, 1); Pixel.SetData(new[] { Color.White }); }
public Inventory(int SCREEN_WIDTH, int SCREEN_HEIGHT, Pantheon gameReference) { locationBoxes = new List<Rectangle>(); equippedBoxes = new List<Rectangle>(); types = new List<int>(); infoBox = new Rectangle(); movingBox = new Rectangle(); trashBox = new Rectangle(); tempStorage = new Item(); this.SCREEN_WIDTH = SCREEN_WIDTH; this.SCREEN_HEIGHT = SCREEN_HEIGHT; SetBoxes(); selected = -1; hoveredOver = -1; color = new Color(34, 167, 222, 50); trashColor = Color.White; inventorySelector = gameReference.Content.Load<Texture2D>("Inventory/InvSelect"); trashCan = gameReference.Content.Load<Texture2D>("Inventory/TrashCan"); nullImage = new Texture2D(gameReference.GraphicsDevice, 1,1); nullImage.SetData(new[] { new Color(0,0,0,0) }); }
public static Texture2D ApplyBorderLabel(this Texture2D texture, BorderStyle style) { Texture2D newTexture = new Texture2D(texture.GraphicsDevice, texture.Width, texture.Height); Color[] data = texture.GetColorData(); switch (style) { case (BorderStyle.FixedSingle): for (int y = 0; y < texture.Height; y++) { for (int x = 0; x < texture.Width; x++) { if (y == 0 || x == 0 || y == texture.Height - 1 || x == texture.Width - 1) { data[x + y * texture.Width] = Color.DimGray; } } } newTexture.SetData(data); return newTexture; case (BorderStyle.Fixed3D): for (int y = 0; y < texture.Height; y++) { for (int x = 0; x < texture.Width; x++) { if (y == 0 || x == 0) data[x + y * texture.Width] = Color.DarkSlateGray; else if (y == texture.Height - 1 || x == texture.Width - 1) data[x + y * texture.Width] = Color.White; } } newTexture.SetData(data); return newTexture; default: return texture; } }
public static Texture2D ApplyBorderButton(this Texture2D texture, ButtonStyle type) { Texture2D newTexture = new Texture2D(texture.GraphicsDevice, texture.Width, texture.Height); Color[] data = texture.GetColorData(); switch (type) { case (ButtonStyle.Default): for (int y = 0; y < texture.Height; y++) { for (int x = 0; x < texture.Width; x++) { if (y == 0 || x == 0 || y == texture.Height - 1 || x == texture.Width - 1) { data[x + y * texture.Width] = Color.CornflowerBlue; } } } newTexture.SetData(data); return newTexture; case (ButtonStyle.Hover): for (int y = 0; y < texture.Height; y++) { for (int x = 0; x < texture.Width; x++) { if (y == 0 || x == 0 || y == texture.Height - 1 || x == texture.Width - 1) { data[x + y * texture.Width] = Color.DimGray; } } } newTexture.SetData(data); return newTexture; case (ButtonStyle.Click): for (int y = 0; y < texture.Height; y++) { for (int x = 0; x < texture.Width; x++) { if (y == 0 || x == 0 || y == texture.Height - 1 || x == texture.Width - 1) { data[x + y * texture.Width] = Color.Black; } else data[x + y * texture.Width] = data[x + y * texture.Width].Add(0, -10, -10, -10); } } newTexture.SetData(data); return newTexture; default: return texture; } }
public override void SetData <T>(T[] data, int mipLevel, Rectangle?subimage, int startIndex, int elementCount) { if (subimage.HasValue) { XNA.Rectangle rect; Rectangle v = subimage.Value; XNAHelper.ConvertRectangle(ref v, out rect); _texture2D.SetData <T>(mipLevel, rect, data, startIndex, elementCount); } else { _texture2D.SetData <T>(mipLevel, null, data, startIndex, elementCount); } }
public void LoadContent(ContentManager content) { GraphicsDevice graphics = button.GraphicsDevice; texture = new RenderTarget2D(graphics, 1, 1); Color[] data = {new Color(225, 225, 225, 255)}; texture.SetData(data); }
/// <summary> /// /// </summary> /// <param name="batch"></param> /// <returns></returns> public static Texture2D GetCustomTexture2D(SpriteBatch batch,Color color) { Texture2D lineTexture = new Texture2D(batch.GraphicsDevice, 1, 1); int[] intColor = { (int)color.PackedValue }; lineTexture.SetData(intColor); return lineTexture; }
public Planet(Vector3 Position, float Scale, float ParentMass, Vector3 OrbitalPlaneNormal) : base() { Body.CreateUVSphere(32, 32, out ModelVertices, out ModelIndices); effect = Manager.TexturedEffect; NoiseMap = Manager.WrappedNoiseTextures[MyGame.random.Next(Manager.WrappedNoiseTextures.Length)]; Color[] StaticNoise = Manager.GenerateStaticNoise(5, 5); for (int i = 0; i < StaticNoise.Length; i++) { StaticNoise[i] = Color.Lerp(planetColors[MyGame.random.Next(planetColors.Length)] , StaticNoise[i] , 0.1f * (float)MyGame.random.NextDouble()); } ColorMap = new Texture2D(MyGame.graphics.GraphicsDevice, 5, 5); ColorMap.SetData<Color>(StaticNoise); RotationAxis = Manager.GetRandomNormal(); RotationTime = (float)MyGame.random.NextDouble(); Bounds = new BoundingSphere(Position, 2.0f * Scale); this.Transforms = new ScalePositionRotation( Scale , Position , Matrix.CreateFromAxisAngle(RotationAxis, RotationTime)); Mass = 10.0f * (float)(4.0 / 3.0 * Math.PI * Math.Pow(Transforms.Scale, 3.0)); this.Velocity = Body.GetRandomInitialOrbitVelocity(Position, OrbitalPlaneNormal, ParentMass, Mass); }
public Food(GraphicsDevice graphicsdevice, Vector2 ScreenSize) { this.GridPosition = new Vector2(randGen.Next(0, (int)(ScreenSize.X + 1)),randGen.Next(0, (int)(ScreenSize.Y + 1))); texture = new Texture2D(graphicsdevice, 1, 1, false, SurfaceFormat.Color); texture.SetData<Color>(new Color[] { Color.Green }); }
public static XGraphics.Texture2D FromFile(GraphicsDevice device, string file, bool premultiplyAlpha) { XGraphics.Texture2D tex = null; using (FileStream fs = File.OpenRead(file)) { tex = XGraphics.Texture2D.FromStream(device, fs); } if (premultiplyAlpha) { byte[] data = new byte[tex.Width * tex.Height * 4]; tex.GetData(data); for (int i = 0; i < data.Length; i += 4) { int a = data[i + 3]; data[i + 0] = (byte)(data[i + 0] * a / 255); data[i + 1] = (byte)(data[i + 1] * a / 255); data[i + 2] = (byte)(data[i + 2] * a / 255); } tex.SetData(data); } return(tex); }
// Methods public static void init(GraphicsDevice graphDev, SpriteBatch spriteBatch) { // init pointTexture pointTexture = new Texture2D(graphDev, 1, 1, false, SurfaceFormat.Color); pointTexture.SetData<Color>(new Color[] { defaultColor }); // init circleTexture circleTexture = new Texture2D(graphDev, circleRadius, circleRadius); Color[] colorData = new Color[circleRadius * circleRadius]; float diam = circleRadius / 2f; float diamsq = diam * diam; for (int x = 0; x < circleRadius; x++) { for (int y = 0; y < circleRadius; y++) { int index = x * circleRadius + y; Vector2 pos = new Vector2(x - diam, y - diam); if (pos.LengthSquared() <= diamsq) { colorData[index] = defaultColor; } else { colorData[index] = Color.Transparent; } } } circleTexture.SetData(colorData); // spriteBatch reference sb = spriteBatch; }
public void Draw(SpriteBatch spriteBatch) { if (BGTexture == null) { BGTexture = new Texture2D(spriteBatch.GraphicsDevice, 1, 1); BGTexture.SetData(new Color[] {Color.White}); } // draw the background Rectangle bg = new Rectangle(Game1.ScreenWidth / 4, Game1.ScreenHeight / 4, Game1.ScreenWidth / 2, Game1.ScreenHeight / 2); spriteBatch.Draw(BGTexture, bg, Color.Black); // draw each option int yOffset = bg.Height / Options.Length; int yPos = bg.Top + (yOffset / 2); foreach (String opt in Options) { Vector2 size = Game1.Font.MeasureString(opt); Vector2 pos = new Vector2((Game1.ScreenWidth / 2) - (size.X / 2), yPos - (size.Y / 2)); spriteBatch.DrawString(Game1.Font, opt, pos, Color.White); yPos += yOffset; } // draw the selection box Vector2 selTextSize = Game1.Font.MeasureString(Options[Position]); int selThickness = yOffset / 10; Rectangle selArea = new Rectangle(bg.Left, bg.Top + yOffset * Position, bg.Width, yOffset); Border b = new Border(selArea, selThickness, Color.Green); b.Draw(spriteBatch); }
public Texture2D CreateCircle(int radius) { int outerRadius = radius * 2 + 2; // So circle doesn't go out of bounds Texture2D texture = new Texture2D(ScreenManager.GraphicsDevice, outerRadius, outerRadius); Color[] data = new Color[outerRadius * outerRadius]; // Colour the entire texture transparent first. for (int i = 0; i < data.Length; i++) data[i] = Color.Transparent; // Work out the minimum step necessary using trigonometry + sine approximation. double angleStep = 1f / radius; for (double angle = 0; angle < Math.PI * 2; angle += angleStep) { // Use the parametric definition of a circle: http://en.wikipedia.org/wiki/Circle#Cartesian_coordinates int x = (int)Math.Round(radius + radius * Math.Cos(angle)); int y = (int)Math.Round(radius + radius * Math.Sin(angle)); data[y * outerRadius + x + 1] = Color.White; } texture.SetData(data); return texture; }
/// <summary> /// Gets a 1x1 texture with a clear transparent pixel in it. /// </summary> /// <param name="batch">The batch to create the texture from.</param> /// <returns>The texture</returns> public static Texture2D GetClearTexture2D(SpriteBatch batch) { Texture2D lineTexture = new Texture2D(batch.GraphicsDevice, 1, 1); int[] intColor = { (int)Color.White.PackedValue }; lineTexture.SetData(intColor); return lineTexture; }
public FirstBossSprite(Game1 game, Texture2D textureImage, Vector2 position, Point frameSize, int collisionOffset, Point currentFrame, Point sheetSize, Vector2 speed, bool animate, int life, int millisecondsPerFrame) : base(game, textureImage, position, frameSize, collisionOffset, currentFrame, sheetSize, speed, animate, life * (int)InGameScreen.difficulty, millisecondsPerFrame) { alive = true; scoreAmount = 60; warningTexture = new Texture2D(game.GraphicsDevice, 1, 1); warningTexture.SetData<Color>(colorData); laserStruckTarget = false; //Creates the left hitbox. hitBox.X = 37 + (int)position.X; hitBox.Y = 156 + (int)position.Y; hitBox.Width = 30; hitBox.Height = 47; //Creates the right hitbox. nonMoveableBossHitbox.X = 121 + (int)position.X; nonMoveableBossHitbox.Y = 147 + (int)position.Y; nonMoveableBossHitbox.Width = 30; nonMoveableBossHitbox.Height = 47; }
//Source http://gamedev.stackexchange.com/questions/44015/how-can-i-draw-a-simple-2d-line-in-xna-without-using-3d-primitives-and-shders private void LoadContent(GraphicsDevice gd) { // create 1x1 texture for line drawing t = new Texture2D(gd, 1, 1); t.SetData<Color>( new Color[] { Color.White });// fill the texture with white }
public void drawCircle(SpriteBatch spriteBatch, Color c, Rectangle rec, double percent) { int radius = 20; int outerRadius = radius * 2 + 2; Texture2D texture = new Texture2D(Program.game.GraphicsDevice, outerRadius, outerRadius); Color[] data = new Color[outerRadius * outerRadius]; for (int i = 0; i < data.Length; i++) data[i] = Color.Transparent; double angleStep = 1f / radius; for (double angle = 0; angle < Math.PI * 2 * percent; angle += angleStep) { int x = (int)Math.Round(radius + radius * Math.Cos(angle + 3 * Math.PI / 2)); int y = (int)Math.Round(radius + radius * Math.Sin(angle + 3 * Math.PI / 2)); data[y * outerRadius + x + 1] = Color.White; } texture.SetData(data); spriteBatch.Draw(texture, rec, c); }
/// <summary> /// Create a texture with a color and a size specified in parameter /// </summary> /// <param name="color">Color of the texture</param> /// <param name="width">Width of the texture</param> /// <param name="height">Height of the texture</param> /// <returns></returns> public static Texture2D CreateTexture(Color color, int width, int height) { Texture2D texture2D = new Texture2D(YnG.GraphicsDevice, width, height); texture2D.SetData(CreateColor(color, width, height)); return texture2D; }
private static void _Copy16(SpanBitmap src, XNA.Texture2D dst, bool fit) { if (dst == null) { throw new ArgumentNullException(nameof(dst)); } var fmt = ToInteropFormat(dst.Format); if (fmt.ByteCount != 2) { throw new ArgumentException("invalid pixel size", nameof(dst)); } var l = dst.Width * dst.Height; if (_16BitBuffer == null || _16BitBuffer.Length < l) { Array.Resize(ref _16BitBuffer, l); } var dstx = new SpanBitmap <ushort>(_16BitBuffer, dst.Width, dst.Height, fmt); fit &= !(src.Width == dst.Width && src.Height == dst.Height); if (fit) { dstx.AsTypeless().FitPixels(src); } else { dstx.AsTypeless().SetPixels(0, 0, src); } dst.SetData(_16BitBuffer); return; }
public override void Draw(SpriteBatch spriteBatch, GraphicsDevice graphics) { Texture2D redPixel = new Texture2D(graphics, 1, 1); Texture2D blackPixel = new Texture2D(graphics, 1, 1); Color[] redData = { Color.Red }; Color[] blackData = { Color.Black }; redPixel.SetData<Color>(redData); blackPixel.SetData<Color>(blackData); Rectangle healthContainer = new Rectangle((int)position.X, (int)position.Y - 10, width, 5); int borderWidth = 1; // Draw health segments inside of health container for (int i = 0; i < healthPoints; i++) { int segmentWidth = (int)Math.Ceiling((double)width / maxHealthPoints); int left = (int)position.X + (int)(i * segmentWidth); if (i + 1 == maxHealthPoints) segmentWidth = width - (i * segmentWidth); Rectangle segment = new Rectangle(left, (int)position.Y - 10, segmentWidth, 5); spriteBatch.Draw(redPixel, segment, Color.White); } spriteBatch.Draw(blackPixel, new Rectangle(healthContainer.Left, healthContainer.Top, borderWidth, healthContainer.Height), Color.White); // Left spriteBatch.Draw(blackPixel, new Rectangle(healthContainer.Right, healthContainer.Top, borderWidth, healthContainer.Height), Color.White); // Right spriteBatch.Draw(blackPixel, new Rectangle(healthContainer.Left, healthContainer.Top, healthContainer.Width, borderWidth), Color.White); // Top spriteBatch.Draw(blackPixel, new Rectangle(healthContainer.Left, healthContainer.Bottom, healthContainer.Width, borderWidth), Color.White); // Bottom }
public StatisticGraph(Control parent, SpriteFont font, Statistic statistic, TimeSpan accessInterval) : base(parent) { if (statistic == null) throw new ArgumentNullException("statistic"); if (accessInterval == TimeSpan.Zero) accessInterval = TimeSpan.FromMilliseconds(16); Strata = new ControlStrata() { Layer = Layer.Overlay }; _tracker = new StatisticTracker(statistic, accessInterval); _graph = new Graph(Device, (int)(15f / (float)accessInterval.TotalSeconds)); //(byte)MathHelper.Clamp(15f / (float)accessInterval.TotalSeconds, 15, 15 * 60)); _label = new Label(this, font) { Text = statistic.Name, Justification = Justification.Centre }; _label.SetPoint(Points.TopLeft, 2, 2); _label.SetPoint(Points.TopRight, -2, 2); _value = new Label(this, font) { Text = "0", Justification = Justification.Centre }; _value.SetPoint(Points.BottomLeft, 2, -2); _value.SetPoint(Points.BottomRight, -2, -2); _texture = new Texture2D(Device, 1, 1); _texture.SetData<Color>(new Color[] { new Color(0, 0, 0, 0.8f) }); SetSize(200, 120); }
// Methods public static void init(GraphicsDevice graphDev, SpriteBatch spriteBatch) { pointTexture = new Texture2D(graphDev, 1, 1, false, SurfaceFormat.Color); pointTexture.SetData<Color>(new Color[] { defaultColor }); sb = spriteBatch; }
private static Texture2D CreateWhitePixel(GraphicsDevice graphicsDevice) { whitePixel = new Texture2D(graphicsDevice, 1, 1); whitePixel.SetData(new[] { Color.White }); return whitePixel; }
private void drawFade() { Texture2D texture = new Texture2D(device, 1, 1, false, SurfaceFormat.Color); Color[] color = { Color.FromNonPremultiplied(255, 255, 255, 180) }; texture.SetData<Color>(color); spriteBatch.Draw(texture, fadeRectangle, Color.Black); }
public override void Draw(GameTime gameTime) { Rectangle aPositionAdjusted; if (drawRoadmap) { Texture2D blank = new Texture2D(game.GraphicsDevice, 1, 1, false, SurfaceFormat.Color); blank.SetData(new[] { Color.White }); spriteBatch.Begin(); foreach (Configuration conf in samples) { aPositionAdjusted = new Rectangle((int)conf.X + (int)(conf.Width / 2), (int)conf.Y + (int)(conf.Height / 2), (int)conf.Width, (int)conf.Height); spriteBatch.Draw(game.obstacleTexture, aPositionAdjusted, new Rectangle(0, 0, 2, 6), Color.Magenta, conf.Rotation, new Vector2(2 / 2, 6 / 2), SpriteEffects.None, 0); foreach (Configuration nbConf in conf.neighbors) { float angle = (float)Math.Atan2(nbConf.CollisionRectangle.position.Y - conf.CollisionRectangle.position.Y, nbConf.CollisionRectangle.position.X - conf.CollisionRectangle.position.X); float length = Vector2.Distance(conf.CollisionRectangle.position, nbConf.CollisionRectangle.position); spriteBatch.Draw(blank, new Vector2(conf.CollisionRectangle.position.X + conf.Width/2, conf.CollisionRectangle.position.Y+ conf.Height/2), null, Color.Black, angle, Vector2.Zero, new Vector2(length, (float)1), SpriteEffects.None, 0); } } spriteBatch.End(); } base.Draw(gameTime); }
protected override void LoadContent() { base.LoadContent(); sb = new SpriteBatch(GraphicsDevice); bgcolor = new Texture2D(GraphicsDevice, 1, 1); bgcolor.SetData(new Color[] { Color.Purple }); zones.Add(Game.Content.Load<Texture2D>("zoneTitle")); zones.Add(Game.Content.Load<Texture2D>("zoneCandyMunching")); zones.Add(Game.Content.Load<Texture2D>("zoneHumanRepellant")); zones.Add(Game.Content.Load<Texture2D>("zoneCallship")); zones.Add(Game.Content.Load<Texture2D>("zoneLanding")); zones.Add(Game.Content.Load<Texture2D>("zoneUp")); zones.Add(Game.Content.Load<Texture2D>("zoneLeft")); zones.Add(Game.Content.Load<Texture2D>("zoneRight")); zones.Add(Game.Content.Load<Texture2D>("zoneDown")); zones.Add(Game.Content.Load<Texture2D>("zoneCallElliott")); zones.Add(Game.Content.Load<Texture2D>("zonePitfall")); zones.Add(Game.Content.Load<Texture2D>("zoneQuestion")); pieces.Add(Game.Content.Load<Texture2D>("pieces0")); pieces.Add(Game.Content.Load<Texture2D>("pieces1")); pieces.Add(Game.Content.Load<Texture2D>("pieces2")); pieces.Add(Game.Content.Load<Texture2D>("pieces3")); etGame.Components.Add(clock); currentZone = zones[0]; }
/// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. spriteBatch = new SpriteBatch(GraphicsDevice); font = Content.Load<SpriteFont>("Font"); font_big = Content.Load<SpriteFont>("font_big"); t_wall = new Texture2D(GraphicsDevice,1,1); t_wall.SetData(new Color[] {Color.Black}); t_goal = new Texture2D(GraphicsDevice, 1, 1); t_goal.SetData(new Color[] { Color.Pink }); Dictionary<Keys, Command> p1Dict = new Dictionary<Keys, Command>(); player1 = new Player(Content.Load<Texture2D>(@"png/bar"), new Vector2(0, 0), 1,p1Dict); player1.Position = new Vector2(boundingBoxLeft.Width, boundingBoxTop.Y + boundingBoxTop.Height); //player1.Position = new Vector2(boundingBoxLeft.Width, boundingBoxTop.Y + boundingBoxTop.Height + HEIGHT / 2 - player1.BoundingBox.Height); p1Dict.Add(Keys.W, new MoveUpCommand(player1)); p1Dict.Add(Keys.S, new MoveDownCommand(player1)); Dictionary<Keys, Command> p2Dict = new Dictionary<Keys, Command>(); player2 = new Player(Content.Load<Texture2D>(@"png/bar"), new Vector2(0, 0), 2, p2Dict); player2.Position = new Vector2(WIDTH - boundingBoxRight.Width - player2.BoundingBox.Width, boundingBoxTop.Y + boundingBoxTop.Height); // player2.Position = new Vector2(WIDTH-boundingBoxRight.Width-player2.BoundingBox.Width, boundingBoxTop.Y + boundingBoxTop.Height + HEIGHT/2 - player2.BoundingBox.Height ); p2Dict.Add(Keys.Up, new MoveUpCommand(player2)); p2Dict.Add(Keys.Down, new MoveDownCommand(player2)); ball = new Ball(Content.Load<Texture2D>(@"png/ball"),new Vector2(300, boundingBoxTop.Y + boundingBoxTop.Height + player1.BoundingBox.Height/2 - 10),300f); ball.setToStartPosition(player1); }
public override void Initialize(Game game, SpriteBatch spriteBatch, Components.ICamera2D camera) { SpriteBatch = spriteBatch; DrawRectangle = new Rectangle(0, 0, (int) camera.ViewportWidth, (int) camera.ViewportHeight); Texture = new Texture2D(game.GraphicsDevice, 1, 1); Texture.SetData(new[] { new Color(255, 255, 255, 0) }); }
public void Draw() { if (textEnabled) { Color myTransparentColor = new Color(0, 0, 0, 127); Vector2 stringDimensions = spriteFont.MeasureString(textLabel + ": " + textValue); float width = stringDimensions.X; float height = stringDimensions.Y; Rectangle backgroundRectangle = new Rectangle(); backgroundRectangle.Width = (int)width + 10; backgroundRectangle.Height = (int)height + 10; backgroundRectangle.X = (int)position.X - 5; backgroundRectangle.Y = (int)position.Y - 5; Texture2D dummyTexture = new Texture2D(graphicsDevice, 1, 1); dummyTexture.SetData(new Color[] { myTransparentColor }); spriteBatch.Begin(); spriteBatch.Draw(dummyTexture, backgroundRectangle, myTransparentColor); spriteBatch.DrawString(spriteFont, textLabel + ": " + textValue, position, textColor); spriteBatch.End(); } }
public CityIsoGrid(GraphicsDevice graphicsDevice, double gridAngle, int edgeLength, float diameter,Vector2 position) { this.angle = gridAngle; this.edge = edgeLength; this.size = diameter; this.position = position; this.usage = new int[(int)diameter, (int)diameter]; // fill grid with free spaces, except corners for (int i=0;i<size;i++) { for (int j=0;j<size;j++) { if (Math.Pow((double)(i - (size / 2.0)), 2) + Math.Pow((double)(j - (size / 2.0)), 2) >= Math.Pow((double)(size / 2.0), 2)) { usage[i,j] = 1; } else { usage[i,j] = 0; } } } blank = new Texture2D(graphicsDevice, 1, 1, false, SurfaceFormat.Color); blank.SetData(new[] { Microsoft.Xna.Framework.Color.White }); }
public static void DrawRectangle(Rectangle rectangleToDraw, Color fillColor, Color borderColor, int thicknessOfBorder = 2 ) { // Draw top line Texture2D pixel1 = new Texture2D(Engine.Instance.Game.GraphicsDevice, 1, 1); pixel1.SetData(new Color[] { fillColor }); Engine.Instance.SpriteBatch.Draw(pixel1, rectangleToDraw, fillColor); Texture2D pixel = new Texture2D(Engine.Instance.Game.GraphicsDevice, 1, 1); pixel.SetData(new Color[] { borderColor }); Engine.Instance.SpriteBatch.Draw(pixel, new Rectangle(rectangleToDraw.X, rectangleToDraw.Y, rectangleToDraw.Width, thicknessOfBorder), borderColor); // Draw left line Engine.Instance.SpriteBatch.Draw(pixel, new Rectangle(rectangleToDraw.X, rectangleToDraw.Y, thicknessOfBorder, rectangleToDraw.Height), borderColor); // Draw right line Engine.Instance.SpriteBatch.Draw(pixel, new Rectangle((rectangleToDraw.X + rectangleToDraw.Width - thicknessOfBorder), rectangleToDraw.Y, thicknessOfBorder, rectangleToDraw.Height), borderColor); // Draw bottom line Engine.Instance.SpriteBatch.Draw(pixel, new Rectangle(rectangleToDraw.X, rectangleToDraw.Y + rectangleToDraw.Height - thicknessOfBorder, rectangleToDraw.Width, thicknessOfBorder), borderColor); }
public Line(GraphicsDeviceManager graphics) { pixel = new Texture2D(graphics.GraphicsDevice, 1, 1, false, SurfaceFormat.Color); pixel.SetData(new[] { Color.White }); point1 = Vector2.Zero; point2 = Vector2.Zero; }
/// <summary> /// Loads spine texture from the specified WZ path /// </summary> /// <param name="page"></param> /// <param name="path"></param> public void Load(AtlasPage page, string path) { WzObject frameNode = this.ParentNode[path]; if (frameNode == null) { return; } WzCanvasProperty canvasProperty = null; WzImageProperty imageChild = (WzImageProperty)ParentNode[path]; if (imageChild is WzUOLProperty uolProperty) { WzObject uolLink = uolProperty.LinkValue; if (uolLink is WzCanvasProperty uolPropertyLink) { canvasProperty = uolPropertyLink; } else { // other unimplemented prop? } } else if (imageChild is WzCanvasProperty property) { canvasProperty = property; } if (canvasProperty != null) { Bitmap bitmap = canvasProperty.GetLinkedWzCanvasBitmap(); if (bitmap != null && graphicsDevice != null) { Texture2D tex = new Texture2D(graphicsDevice, bitmap.Width, bitmap.Height, true, SurfaceFormat.Color); BitmapData data = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, bitmap.PixelFormat); int bufferSize = data.Height * data.Stride; //create data buffer byte[] bytes = new byte[bufferSize]; // copy bitmap data into buffer Marshal.Copy(data.Scan0, bytes, 0, bytes.Length); // copy our buffer to the texture tex.SetData(bytes); // unlock the bitmap data bitmap.UnlockBits(data); page.rendererObject = tex; page.width = bitmap.Width; page.height = bitmap.Height; } } }
public unsafe AnimationFrame(GraphicsDevice graphics, uint[] palette, BinaryFileReader reader) { int xCenter = reader.ReadShort(); int yCenter = reader.ReadShort(); int width = reader.ReadUShort(); int height = reader.ReadUShort(); // Fix for animations with no IO. if ((width == 0) || (height == 0)) { m_Texture = null; return; } uint[] data = new uint[width * height]; int header; int xBase = xCenter - 0x200; int yBase = (yCenter + height) - 0x200; fixed(uint *pData = data) { uint *dataRef = pData; int delta = width; int dataRead = 0; dataRef += xBase; dataRef += (yBase * delta); while ((header = reader.ReadInt()) != 0x7FFF7FFF) { header ^= DoubleXor; uint *cur = dataRef + ((((header >> 12) & 0x3FF) * delta) + ((header >> 22) & 0x3FF)); uint *end = cur + (header & 0xFFF); int filecounter = 0; byte[] filedata = reader.ReadBytes(header & 0xFFF); while (cur < end) { *cur++ = palette[filedata[filecounter++]]; } dataRead += header & 0xFFF; } Metrics.ReportDataRead(dataRead); } m_Center = new Microsoft.Xna.Framework.Point(xCenter, yCenter); m_Texture = new Texture2D(graphics, width, height); m_Texture.SetData <uint>(data); }
/// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. _spriteBatch = new SpriteBatch(GraphicsDevice); // Load dummy texture (1x1) for line and panel drawing _dummyTexture = new Texture2D(GraphicsDevice, 1, 1); _dummyTexture.SetData(new[] { Color.White }); }
protected override Microsoft.Xna.Framework.Graphics.Texture2D CreateTexture( ) { // check whether the rectangle draws itself and not a created texture var renderShape = (this.RadiusX == 0 && this.RadiusY == 0 && (this.Fill == null || this.Fill is SolidColorBrush)); if (renderShape) { return(null); } if (dicTextures.ContainsKey(this)) { return(dicTextures[this]); } // Image-Scaling 2x - looks better var width = (int)Math.Ceiling(this.ActualWidth); var height = (int)Math.Ceiling(this.ActualHeight); var rcBorder = new Rect( 0, 0, width, height); var rcBackground = new Rect( (int)Math.Ceiling(this.StrokeThickness), (int)Math.Ceiling(this.StrokeThickness), (int)(Math.Ceiling((double)width) - this.StrokeThickness - this.StrokeThickness), (int)(Math.Ceiling((double)height) - this.StrokeThickness - this.StrokeThickness)); var borderRects = GetRects(GetPoints(rcBorder, this.RadiusX, this.RadiusY)); var bgRects = GetRects(GetPoints(rcBackground, this.RadiusX, this.RadiusY)); var tex = new Microsoft.Xna.Framework.Graphics.Texture2D(ScreenHelper.Device, width, height); var pixels = new int[width * height]; pixels.Fill((int)Colors.Transparent.PackedValue); if (this.Stroke != null && this.StrokeThickness > 0) { FillPixels( this.Stroke, borderRects, width, height, ref pixels); } if (this.Fill != null) { FillPixels( this.Fill, bgRects, width, height, ref pixels); } tex.SetData(pixels); dicTextures [this] = tex; return(tex); }
public static void ToTexture(this System.Drawing.Bitmap bitmap, Texture2D texture, Point origin) { var rect = new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height); var bmpData = bitmap.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); byte[] buffer = new byte[bmpData.Stride * bmpData.Height]; Marshal.Copy(bmpData.Scan0, buffer, 0, buffer.Length); bitmap.UnlockBits(bmpData); texture.SetData(0, 0, new Rectangle(origin.X, origin.Y, rect.Width, rect.Height), buffer, 0, buffer.Length); }
public static Texture2D ToTexture(this System.Drawing.Bitmap bitmap, GraphicsDevice device) { var rect = new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height); var bmpData = bitmap.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); byte[] buffer = new byte[bmpData.Stride * bmpData.Height]; Marshal.Copy(bmpData.Scan0, buffer, 0, buffer.Length); bitmap.UnlockBits(bmpData); var t2d = new Texture2D(device, rect.Width, rect.Height, false, SurfaceFormat.Bgra32); t2d.SetData(buffer); return(t2d); }
protected override void LoadContent() { spriteBatch = new SpriteBatch(GraphicsDevice); _spriteFont = Game.Content.Load <SpriteFont>("debug"); // Create single pixel texture _pixel = new Texture2D(GraphicsDevice, 1, 1, false, SurfaceFormat.Color); _pixel.SetData(new[] { Color.White }); _consoleWindow = new Texture2D(GraphicsDevice, 1, 1); _consoleWindow.SetData(new[] { new Color(0, 0, 0, 0.7f) }); _consoleBounds = new Rectangle(0, 0, GraphicsDevice.Viewport.Width, (int)(GraphicsDevice.Viewport.Height * 0.37)); _messageLog = new List <string>(); _tracking = new List <IGameObject>(); base.LoadContent(); }
public unsafe AnimationFrame(GraphicsDevice graphics, uint[] palette, byte[] frame, int width, int height, int xCenter, int yCenter) { palette[0] = 0xFFFFFFFF; uint[] data = new uint[width * height]; fixed(uint *pData = data) { uint *dataRef = pData; int frameIndex = 0; while (frameIndex < frame.Length) { *dataRef++ = palette[frame[frameIndex++]]; } } m_Center = new Microsoft.Xna.Framework.Point(xCenter, yCenter); m_Texture = new Texture2D(graphics, width, height); m_Texture.SetData <uint>(data); palette[0] = 0; }
public static Texture2D CreateMosaic(GraphicsDevice device, Color c0, Color c1, int blockSize) { var t2d = new Texture2D(device, blockSize * 2, blockSize * 2, false, SurfaceFormat.Color); Color[] colorData = new Color[blockSize * blockSize * 4]; int offset = blockSize * blockSize * 2; for (int i = 0; i < blockSize; i++) { colorData[i] = c0; colorData[blockSize + i] = c1; colorData[offset + i] = c1; colorData[offset + blockSize + i] = c0; } for (int i = 1; i < blockSize; i++) { Array.Copy(colorData, 0, colorData, blockSize * 2 * i, blockSize * 2); Array.Copy(colorData, offset, colorData, offset + blockSize * 2 * i, blockSize * 2); } t2d.SetData(colorData); return(t2d); }
private static Texture2D PlatformFromStream(GraphicsDevice graphicsDevice, CGImage cgImage) { var width = cgImage.Width; var height = cgImage.Height; var data = new byte[width * height * 4]; var colorSpace = CGColorSpace.CreateDeviceRGB(); var bitmapContext = new CGBitmapContext(data, width, height, 8, width * 4, colorSpace, CGBitmapFlags.PremultipliedLast); bitmapContext.DrawImage(new RectangleF(0, 0, width, height), cgImage); bitmapContext.Dispose(); colorSpace.Dispose(); Texture2D texture = null; Threading.BlockOnUIThread(() => { texture = new Texture2D(graphicsDevice, (int)width, (int)height, false, SurfaceFormat.Color); texture.SetData(data); }); return(texture); }
private static void _Copy32(SpanBitmap src, XNA.Texture2D dst, bool fit) { if (dst == null) { throw new ArgumentNullException(nameof(dst)); } var fmt = dst.Format == XNA.SurfaceFormat.Bgr32 ? Pixel.BGRA32.Format : ToInteropFormat(dst.Format); if (fmt.ByteCount != 4) { throw new ArgumentException("invalid pixel size", nameof(dst)); } var l = dst.Width * dst.Height; if (_32BitBuffer == null || _32BitBuffer.Length < l) { Array.Resize(ref _32BitBuffer, l); } var dstx = new SpanBitmap <UInt32>(_32BitBuffer, dst.Width, dst.Height, fmt); fit &= !(src.Width == dst.Width && src.Height == dst.Height); if (fit) { dstx.AsTypeless().FitPixels(src); } else { dstx.AsTypeless().SetPixels(0, 0, src); } dst.SetData(_32BitBuffer); }
private static Texture2D PlatformFromStream(GraphicsDevice graphicsDevice, Stream stream) { #if WINDOWS_PHONE WriteableBitmap bitmap = null; Threading.BlockOnUIThread(() => { BitmapImage bitmapImage = new BitmapImage(); bitmapImage.SetSource(stream); bitmap = new WriteableBitmap(bitmapImage); }); // Convert from ARGB to ABGR ConvertToABGR(bitmap.PixelHeight, bitmap.PixelWidth, bitmap.Pixels); Texture2D texture = new Texture2D(graphicsDevice, bitmap.PixelWidth, bitmap.PixelHeight); texture.SetData <int>(bitmap.Pixels); return(texture); #endif #if !WINDOWS_PHONE // For reference this implementation was ultimately found through this post: // http://stackoverflow.com/questions/9602102/loading-textures-with-sharpdx-in-metro Texture2D toReturn = null; SharpDX.WIC.BitmapDecoder decoder; using (var bitmap = LoadBitmap(stream, out decoder)) using (decoder) { SharpDX.Direct3D11.Texture2D sharpDxTexture = CreateTex2DFromBitmap(bitmap, graphicsDevice); toReturn = new Texture2D(graphicsDevice, bitmap.Size.Width, bitmap.Size.Height); toReturn._texture = sharpDxTexture; } return(toReturn); #endif }
private static Texture2D PlatformFromStream(GraphicsDevice graphicsDevice, Bitmap image) { var width = image.Width; var height = image.Height; int[] pixels = new int[width * height]; if ((width != image.Width) || (height != image.Height)) { using (Bitmap imagePadded = Bitmap.CreateBitmap(width, height, Bitmap.Config.Argb8888)) { Canvas canvas = new Canvas(imagePadded); canvas.DrawARGB(0, 0, 0, 0); canvas.DrawBitmap(image, 0, 0, null); imagePadded.GetPixels(pixels, 0, width, 0, 0, width, height); imagePadded.Recycle(); } } else { image.GetPixels(pixels, 0, width, 0, 0, width, height); } image.Recycle(); // Convert from ARGB to ABGR ConvertToABGR(height, width, pixels); Texture2D texture = null; Threading.BlockOnUIThread(() => { texture = new Texture2D(graphicsDevice, width, height, false, SurfaceFormat.Color); texture.SetData <int>(pixels); }); return(texture); }
private static void CreateThePixel(SpriteBatch spriteBatch) { pixel = new Texture2D(spriteBatch.GraphicsDevice, 1, 1, false, SurfaceFormat.Color); pixel.SetData(new[] { Color.White }); }
public T GetAsset <T>(BaseAssets key) where T : class { object returnObj = null; if (typeof(T) == typeof(Texture2D) && Texture2D.ContainsKey(key.ToString())) { returnObj = Texture2D[key.ToString()]; } if (typeof(T) == typeof(Texture3D) && Texture3D.ContainsKey(key.ToString())) { returnObj = Texture3D[key.ToString()]; } if (typeof(T) == typeof(Effect) && Effects.ContainsKey(key.ToString())) { returnObj = Effects[key.ToString()]; } if (returnObj == null && typeof(T) == typeof(Song) && Songs.ContainsKey(key.ToString())) { returnObj = Songs[key.ToString()]; } if (returnObj == null && typeof(T) == typeof(SoundEffect) && SoundEffects.ContainsKey(key.ToString())) { returnObj = SoundEffects[key.ToString()]; } if (returnObj == null && typeof(T) == typeof(SpriteFont) && Fonts.ContainsKey(key.ToString())) { returnObj = Fonts[key.ToString()]; } if (returnObj == null && typeof(T) == typeof(Model) && Models.ContainsKey(key.ToString())) { returnObj = Models[key.ToString()]; } if (returnObj == null && typeof(T) == typeof(TextureCube) && TextureCubes.ContainsKey(key.ToString())) { returnObj = TextureCubes[key.ToString()]; } if (returnObj == null) { switch (key) { case BaseAssets.BlankTexture: Texture2D bt = new Microsoft.Xna.Framework.Graphics.Texture2D(Game.GraphicsDevice, 1, 1); bt.SetData <Color>(new Color[] { Color.Black }); AddAsset <T>(key.ToString(), bt); returnObj = GetAsset <T>(key); break; case BaseAssets.WhiteTexture: Texture2D wt = new Microsoft.Xna.Framework.Graphics.Texture2D(Game.GraphicsDevice, 1, 1); wt.SetData <Color>(new Color[] { Color.White }); AddAsset <T>(key.ToString(), wt); returnObj = GetAsset <T>(key); break; case BaseAssets.NormalTexture: Texture2D nt = new Microsoft.Xna.Framework.Graphics.Texture2D(Game.GraphicsDevice, 1, 1); nt.SetData <Color>(new Color[] { new Color(128, 128, 255) }); AddAsset <T>(key.ToString(), nt); returnObj = GetAsset <T>(key); break; } } return((T)returnObj); }
protected virtual bool init(DisposableI parent, string fileName, Image image, int width, int height, bool generateMipmaps, MultiSampleTypes multiSampleType, SurfaceFormats surfaceFormat, RenderTargetUsage renderTargetUsage, BufferUsages usage, bool isRenderTarget, Loader.LoadedCallbackMethod loadedCallback) { try { if (usage == BufferUsages.Read && !isRenderTarget) { Debug.ThrowError("Texture2D", "Only RenderTargets may be readable"); } video = parent.FindParentOrSelfWithException <Video>(); if (!isRenderTarget) { if (fileName != null || image != null) { #if SILVERLIGHT texture = new X.Texture2D(video.Device, image.Size.Width, image.Size.Height, image.Mipmaps.Length != 0, Video.surfaceFormat(surfaceFormat)); for (int i = 0; i != image.Mipmaps.Length; ++i) { var mipmap = image.Mipmaps[i]; texture.SetData <byte>(i, null, mipmap.Data, 0, mipmap.Data.Length); } #else texture = parent.FindParentOrSelfWithException <RootDisposable>().Content.Load <X.Texture2D>(Streams.StripFileExt(fileName)); loadedFromContentManager = true; #endif } else { texture = new X.Texture2D(video.Device, width, height, generateMipmaps, Video.surfaceFormat(surfaceFormat)); } Size = new Size2(texture.Width, texture.Height); PixelByteSize = Image.CalculatePixelByteSize(surfaceFormat, texture.Width, texture.Height); } else { Size = new Size2(width, height); PixelByteSize = Image.CalculatePixelByteSize(surfaceFormat, width, height); } TexelOffset = (1 / Size.ToVector2()) * .5f; SizeF = Size.ToVector2(); } catch (Exception e) { FailedToLoad = true; Loader.AddLoadableException(e); Dispose(); if (loadedCallback != null) { loadedCallback(this, false); } return(false); } if (!isRenderTarget) { Loaded = true; if (loadedCallback != null) { loadedCallback(this, true); } } return(true); }
public static Texture2D DDSFromStreamEXT( GraphicsDevice graphicsDevice, Stream stream ) { Texture2D result; // Begin BinaryReader, ignoring a tab! using (BinaryReader reader = new BinaryReader(stream)) { int width, height, levels; bool isCube; SurfaceFormat format; Texture.ParseDDS( reader, out format, out width, out height, out levels, out isCube ); if (isCube) { throw new FormatException("This file contains cube map data!"); } // Allocate/Load texture result = new Texture2D( graphicsDevice, width, height, levels > 1, format ); byte[] tex = null; if (stream is MemoryStream && ((MemoryStream)stream).TryGetBuffer(out tex)) { for (int i = 0; i < levels; i += 1) { int levelSize = Texture.CalculateDDSLevelSize( width >> i, height >> i, format ); result.SetData( i, null, tex, (int)stream.Seek(0, SeekOrigin.Current), levelSize ); stream.Seek( levelSize, SeekOrigin.Current ); } } else { for (int i = 0; i < levels; i += 1) { tex = reader.ReadBytes(Texture.CalculateDDSLevelSize( width >> i, height >> i, format )); result.SetData( i, null, tex, 0, tex.Length ); } } // End BinaryReader } // Finally. return(result); }
public override void SetData <T>(T[] data, int mipLevel, int left, int right, int startIndex, int elementCount) { _texture2D.SetData <T>(mipLevel, new Microsoft.Xna.Framework.Rectangle(0, 0, left, right), data, startIndex, elementCount); }
private static Texture2D PlatformFromStream(GraphicsDevice graphicsDevice, Stream stream) { #if IOS || MONOMAC #if IOS using (var uiImage = UIImage.LoadFromData(NSData.FromStream(stream))) #elif MONOMAC using (var nsImage = NSImage.FromStream(stream)) #endif { #if IOS var cgImage = uiImage.CGImage; #elif MONOMAC var rectangle = RectangleF.Empty; var cgImage = nsImage.AsCGImage(ref rectangle, null, null); #endif return(PlatformFromStream(graphicsDevice, cgImage)); } #endif #if ANDROID using (Bitmap image = BitmapFactory.DecodeStream(stream, null, new BitmapFactory.Options { InScaled = false, InDither = false, InJustDecodeBounds = false, InPurgeable = true, InInputShareable = true, })) { var width = image.Width; var height = image.Height; int[] pixels = new int[width * height]; if ((width != image.Width) || (height != image.Height)) { using (Bitmap imagePadded = Bitmap.CreateBitmap(width, height, Bitmap.Config.Argb8888)) { Canvas canvas = new Canvas(imagePadded); canvas.DrawARGB(0, 0, 0, 0); canvas.DrawBitmap(image, 0, 0, null); imagePadded.GetPixels(pixels, 0, width, 0, 0, width, height); imagePadded.Recycle(); } } else { image.GetPixels(pixels, 0, width, 0, 0, width, height); } image.Recycle(); // Convert from ARGB to ABGR ConvertToABGR(height, width, pixels); Texture2D texture = null; Threading.BlockOnUIThread(() => { texture = new Texture2D(graphicsDevice, width, height, false, SurfaceFormat.Color); texture.SetData <int>(pixels); }); return(texture); } #endif #if WINDOWS || LINUX || ANGLE Bitmap image = (Bitmap)Bitmap.FromStream(stream); try { // Fix up the Image to match the expected format image = (Bitmap)image.RGBToBGR(); var data = new byte[image.Width * image.Height * 4]; BitmapData bitmapData = image.LockBits(new System.Drawing.Rectangle(0, 0, image.Width, image.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); if (bitmapData.Stride != image.Width * 4) { throw new NotImplementedException(); } Marshal.Copy(bitmapData.Scan0, data, 0, data.Length); image.UnlockBits(bitmapData); Texture2D texture = null; texture = new Texture2D(graphicsDevice, image.Width, image.Height); texture.SetData(data); return(texture); } finally { image.Dispose(); } #endif }
private static Texture2D PlatformFromStream(GraphicsDevice graphicsDevice, Stream stream) { #if IOS || MONOMAC #if IOS using (var uiImage = UIImage.LoadFromData(NSData.FromStream(stream))) #elif MONOMAC using (var nsImage = NSImage.FromStream(stream)) #endif { #if IOS var cgImage = uiImage.CGImage; #elif MONOMAC #if PLATFORM_MACOS_LEGACY var rectangle = RectangleF.Empty; #else var rectangle = CGRect.Empty; #endif var cgImage = nsImage.AsCGImage(ref rectangle, null, null); #endif return(PlatformFromStream(graphicsDevice, cgImage)); } #endif #if ANDROID using (Bitmap image = BitmapFactory.DecodeStream(stream, null, new BitmapFactory.Options { InScaled = false, InDither = false, InJustDecodeBounds = false, InPurgeable = true, InInputShareable = true, })) { return(PlatformFromStream(graphicsDevice, image)); } #endif #if DESKTOPGL || ANGLE Bitmap image = (Bitmap)Bitmap.FromStream(stream); try { // Fix up the Image to match the expected format image = (Bitmap)image.RGBToBGR(); var data = new byte[image.Width * image.Height * 4]; BitmapData bitmapData = image.LockBits(new System.Drawing.Rectangle(0, 0, image.Width, image.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); if (bitmapData.Stride != image.Width * 4) { throw new NotImplementedException(); } Marshal.Copy(bitmapData.Scan0, data, 0, data.Length); image.UnlockBits(bitmapData); Texture2D texture = null; texture = new Texture2D(graphicsDevice, image.Width, image.Height); texture.SetData(data); return(texture); } finally { image.Dispose(); } #endif }
public static Texture2D FromStream(GraphicsDevice graphicsDevice, Stream stream) { //todo: partial classes would be cleaner #if IOS || MONOMAC #if IOS using (var uiImage = UIImage.LoadFromData(NSData.FromStream(stream))) #elif MONOMAC using (var nsImage = NSImage.FromStream (stream)) #endif { #if IOS var cgImage = uiImage.CGImage; #elif MONOMAC var rectangle = RectangleF.Empty; var cgImage = nsImage.AsCGImage (ref rectangle, null, null); #endif var width = cgImage.Width; var height = cgImage.Height; var data = new byte[width * height * 4]; var colorSpace = CGColorSpace.CreateDeviceRGB(); var bitmapContext = new CGBitmapContext(data, width, height, 8, width * 4, colorSpace, CGBitmapFlags.PremultipliedLast); bitmapContext.DrawImage(new RectangleF(0, 0, width, height), cgImage); bitmapContext.Dispose(); colorSpace.Dispose(); Texture2D texture = null; Threading.BlockOnUIThread(() => { texture = new Texture2D(graphicsDevice, width, height, false, SurfaceFormat.Color); texture.SetData(data); }); return texture; } #elif ANDROID using (Bitmap image = BitmapFactory.DecodeStream(stream, null, new BitmapFactory.Options { InScaled = false, InDither = false, InJustDecodeBounds = false, InPurgeable = true, InInputShareable = true, })) { var width = image.Width; var height = image.Height; int[] pixels = new int[width * height]; if ((width != image.Width) || (height != image.Height)) { using (Bitmap imagePadded = Bitmap.CreateBitmap(width, height, Bitmap.Config.Argb8888)) { Canvas canvas = new Canvas(imagePadded); canvas.DrawARGB(0, 0, 0, 0); canvas.DrawBitmap(image, 0, 0, null); imagePadded.GetPixels(pixels, 0, width, 0, 0, width, height); imagePadded.Recycle(); } } else { image.GetPixels(pixels, 0, width, 0, 0, width, height); } image.Recycle(); // Convert from ARGB to ABGR for (int i = 0; i < width * height; ++i) { uint pixel = (uint)pixels[i]; pixels[i] = (int)((pixel & 0xFF00FF00) | ((pixel & 0x00FF0000) >> 16) | ((pixel & 0x000000FF) << 16)); } Texture2D texture = null; Threading.BlockOnUIThread(() => { texture = new Texture2D(graphicsDevice, width, height, false, SurfaceFormat.Color); texture.SetData<int>(pixels); }); return texture; } #elif WINDOWS_PHONE throw new NotImplementedException(); #elif WINDOWS_STOREAPP || DIRECTX // For reference this implementation was ultimately found through this post: // http://stackoverflow.com/questions/9602102/loading-textures-with-sharpdx-in-metro Texture2D toReturn = null; SharpDX.WIC.BitmapDecoder decoder; using(var bitmap = LoadBitmap(stream, out decoder)) using (decoder) { SharpDX.Direct3D11.Texture2D sharpDxTexture = CreateTex2DFromBitmap(bitmap, graphicsDevice); toReturn = new Texture2D(graphicsDevice, bitmap.Size.Width, bitmap.Size.Height); toReturn._texture = sharpDxTexture; } return toReturn; #elif PSM return new Texture2D(graphicsDevice, stream); #else using (Bitmap image = (Bitmap)Bitmap.FromStream(stream)) { // Fix up the Image to match the expected format image.RGBToBGR(); var data = new byte[image.Width * image.Height * 4]; BitmapData bitmapData = image.LockBits(new System.Drawing.Rectangle(0, 0, image.Width, image.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); if (bitmapData.Stride != image.Width * 4) throw new NotImplementedException(); Marshal.Copy(bitmapData.Scan0, data, 0, data.Length); image.UnlockBits(bitmapData); Texture2D texture = null; texture = new Texture2D(graphicsDevice, image.Width, image.Height); texture.SetData(data); return texture; } #endif }
public static Texture2D DDSFromStreamEXT( Stream stream ) { Texture2D result; // Begin BinaryReader, ignoring a tab! using (BinaryReader reader = new BinaryReader(stream)) { int width, height, levels, levelSize, blockSize; SurfaceFormat format; Texture.ParseDDS( reader, out format, out width, out height, out levels, out levelSize, out blockSize ); // Allocate/Load texture result = new Texture2D( width, height, levels > 1, format ); byte[] tex = null; if (stream is MemoryStream && ((MemoryStream)stream).TryGetBuffer(out tex)) { for (int i = 0; i < levels; i += 1) { result.SetData( i, null, tex, (int)stream.Seek(0, SeekOrigin.Current), levelSize ); stream.Seek( levelSize, SeekOrigin.Current ); levelSize = Math.Max( levelSize >> 2, blockSize ); } } else { for (int i = 0; i < levels; i += 1) { tex = reader.ReadBytes(levelSize); result.SetData( i, null, tex, 0, tex.Length ); levelSize = Math.Max( levelSize >> 2, blockSize ); } } // End BinaryReader } // Finally. return(result); }
// DDS loading extension, based on MojoDDS public static Texture2D DDSFromStreamEXT( GraphicsDevice graphicsDevice, Stream stream ) { // A whole bunch of magic numbers, yay DDS! const uint DDS_MAGIC = 0x20534444; const uint DDS_HEADERSIZE = 124; const uint DDS_PIXFMTSIZE = 32; const uint DDSD_CAPS = 0x1; const uint DDSD_HEIGHT = 0x2; const uint DDSD_WIDTH = 0x4; const uint DDSD_PITCH = 0x8; const uint DDSD_FMT = 0x1000; const uint DDSD_LINEARSIZE = 0x80000; const uint DDSD_REQ = ( DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH | DDSD_FMT ); const uint DDSCAPS_MIPMAP = 0x400000; const uint DDSCAPS_TEXTURE = 0x1000; const uint DDPF_FOURCC = 0x4; const uint DDPF_RGB = 0x40; const uint FOURCC_DXT1 = 0x31545844; const uint FOURCC_DXT3 = 0x33545844; const uint FOURCC_DXT5 = 0x35545844; // const uint FOURCC_DX10 = 0x30315844; const uint pitchAndLinear = ( DDSD_PITCH | DDSD_LINEARSIZE ); Texture2D result; // Begin BinaryReader, ignoring a tab! using (BinaryReader reader = new BinaryReader(stream)) { // File should start with 'DDS ' if (reader.ReadUInt32() != DDS_MAGIC) { return(null); } // Texture info uint size = reader.ReadUInt32(); if (size != DDS_HEADERSIZE) { return(null); } uint flags = reader.ReadUInt32(); if ((flags & DDSD_REQ) != DDSD_REQ) { return(null); } if ((flags & pitchAndLinear) == pitchAndLinear) { return(null); } int height = reader.ReadInt32(); int width = reader.ReadInt32(); reader.ReadUInt32(); // dwPitchOrLinearSize, unused reader.ReadUInt32(); // dwDepth, unused int levels = reader.ReadInt32(); // "Reserved" reader.ReadBytes(4 * 11); // Format info uint formatSize = reader.ReadUInt32(); if (formatSize != DDS_PIXFMTSIZE) { return(null); } uint formatFlags = reader.ReadUInt32(); uint formatFourCC = reader.ReadUInt32(); uint formatRGBBitCount = reader.ReadUInt32(); uint formatRBitMask = reader.ReadUInt32(); uint formatGBitMask = reader.ReadUInt32(); uint formatBBitMask = reader.ReadUInt32(); uint formatABitMask = reader.ReadUInt32(); // dwCaps "stuff" uint caps = reader.ReadUInt32(); if ((caps & DDSCAPS_TEXTURE) == 0) { return(null); } uint caps2 = reader.ReadUInt32(); if (caps2 != 0) { return(null); } reader.ReadUInt32(); // dwCaps3, unused reader.ReadUInt32(); // dwCaps4, unused // "Reserved" reader.ReadUInt32(); // Mipmap sanity check if ((caps & DDSCAPS_MIPMAP) != DDSCAPS_MIPMAP) { levels = 1; } // Determine texture format SurfaceFormat format; int levelSize; int blockSize = 0; if ((formatFlags & DDPF_FOURCC) == DDPF_FOURCC) { if (formatFourCC == FOURCC_DXT1) { format = SurfaceFormat.Dxt1; blockSize = 8; } else if (formatFourCC == FOURCC_DXT3) { format = SurfaceFormat.Dxt3; blockSize = 16; } else if (formatFourCC == FOURCC_DXT5) { format = SurfaceFormat.Dxt5; blockSize = 16; } else { throw new NotSupportedException( "Unsupported DDS texture format" ); } levelSize = ( ((width > 0 ? ((width + 3) / 4) : 1) * blockSize) * (height > 0 ? ((height + 3) / 4) : 1) ); } else if ((formatFlags & DDPF_RGB) == DDPF_RGB) { if (formatRGBBitCount != 32 || formatRBitMask != 0x00FF0000 || formatGBitMask != 0x0000FF00 || formatBBitMask != 0x000000FF || formatABitMask != 0xFF000000) { throw new NotSupportedException( "Unsupported DDS texture format" ); } format = SurfaceFormat.ColorBgraEXT; levelSize = (int)( (((width * formatRGBBitCount) + 7) / 8) * height ); } else { throw new NotSupportedException( "Unsupported DDS texture format" ); } // Allocate/Load texture result = new Texture2D( graphicsDevice, width, height, levels > 1, format ); byte[] tex = null; if (stream is MemoryStream && ((MemoryStream)stream).TryGetBuffer(out tex)) { for (int i = 0; i < levels; i += 1) { result.SetData( i, null, tex, (int)stream.Seek(0, SeekOrigin.Current), levelSize ); stream.Seek( levelSize, SeekOrigin.Current ); levelSize = Math.Max( levelSize >> 2, blockSize ); } } else { for (int i = 0; i < levels; i += 1) { tex = reader.ReadBytes(levelSize); result.SetData( i, null, tex, 0, tex.Length ); levelSize = Math.Max( levelSize >> 2, blockSize ); } } // End BinaryReader } // Finally. return(result); }