public void Draw(ISet<State> states, SpriteBatch spriteBatch, XnaRectangle position, XnaColor color)
        {
            int rowTopHeight = _centerTop.Height;
            int rowBottomHeight = _centerBottom.Height;
            int rowCenterHeight = position.Height - rowTopHeight - rowBottomHeight;

            int startY = position.Top;
            int rowCenterTop = startY + rowTopHeight;
            int rowBottomTop = startY + position.Height - rowBottomHeight;

            int colLeftWidth = _leftCenter.Width;
            int colRightWidth = _rightCenter.Width;
            int colCenterWidth = position.Width - colLeftWidth - colRightWidth;

            int startX = position.Left;
            int colCenterLeft = startX + colLeftWidth;
            int colRightLeft = startX + position.Width - colRightWidth;

            spriteBatch.Draw(_texture, new XnaRectangle(startX, startY, colLeftWidth, rowTopHeight), _leftTop, color);
            spriteBatch.Draw(_texture, new XnaRectangle(startX, rowCenterTop, colLeftWidth, rowCenterHeight), _leftCenter, color);
            spriteBatch.Draw(_texture, new XnaRectangle(startX, rowBottomTop, colLeftWidth, rowBottomHeight), _leftBottom, color);
            spriteBatch.Draw(_texture, new XnaRectangle(colCenterLeft, startY, colCenterWidth, rowTopHeight), _centerTop, color);
            spriteBatch.Draw(_texture, new XnaRectangle(colCenterLeft, rowCenterTop, colCenterWidth, rowCenterHeight), _center, color);
            spriteBatch.Draw(_texture, new XnaRectangle(colCenterLeft, rowBottomTop, colCenterWidth, rowBottomHeight), _centerBottom, color);
            spriteBatch.Draw(_texture, new XnaRectangle(colRightLeft, startY, colRightWidth, rowTopHeight), _rightTop, color);
            spriteBatch.Draw(_texture, new XnaRectangle(colRightLeft, rowCenterTop, colRightWidth, rowCenterHeight), _rightCenter, color);
            spriteBatch.Draw(_texture, new XnaRectangle(colRightLeft, rowBottomTop, colRightWidth, rowBottomHeight), _rightBottom, color);
        }
Example #2
0
 public void SetColor(Microsoft.Xna.Framework.Color color)
 {
     foreach (var rectangle in this.Rectangles)
     {
         rectangle.Color = color;
     }
 }
        public NinePatchImage(Texture2D texture)
        {
            _texture = texture;
            XnaColor[] data = new XnaColor[texture.Width * texture.Height];
            texture.GetData(data);
            Stretch = new Area(
                vertical: GetLine(texture, data, 0, 1, 0, 0),
                horizontal: GetLine(texture, data, 1, 0, 0, 0));
            Content = new Area(
                vertical: GetLine(texture, data, 0, 1, _texture.Width - 1, 0),
                horizontal: GetLine(texture, data, 1, 0, 0, _texture.Height - 1));

            Width = _texture.Width - 2;
            Height = _texture.Height - 2;

            _leftTop = new XnaRectangle(1, 1, Stretch.Horizontal.Start, Stretch.Vertical.Start);
            _leftCenter = new XnaRectangle(1, Stretch.Vertical.Start, Stretch.Horizontal.Start, Stretch.Vertical.Size);
            _leftBottom = new XnaRectangle(1, Stretch.Vertical.End, Stretch.Horizontal.Start, texture.Height - 1 - Stretch.Vertical.End);
            _centerTop = new XnaRectangle(Stretch.Horizontal.Start, 1, Stretch.Horizontal.Size, Stretch.Vertical.Start);
            _center = new XnaRectangle(Stretch.Horizontal.Start, Stretch.Vertical.Start, Stretch.Horizontal.Size, Stretch.Vertical.Size);
            _centerBottom = new XnaRectangle(Stretch.Horizontal.Start, Stretch.Vertical.End, Stretch.Horizontal.Size, texture.Height - 1 - Stretch.Vertical.End);
            _rightTop = new XnaRectangle(Stretch.Horizontal.End, 1, texture.Width - 1 - Stretch.Horizontal.End, Stretch.Vertical.Start);
            _rightCenter = new XnaRectangle(Stretch.Horizontal.End, Stretch.Vertical.Start, texture.Width - 1 - Stretch.Horizontal.End, Stretch.Vertical.Size);
            _rightBottom = new XnaRectangle(Stretch.Horizontal.End, Stretch.Vertical.End, texture.Width - 1 - Stretch.Horizontal.End, texture.Height - 1 - Stretch.Vertical.End);
        }
Example #4
0
 public Label(Func <string> textFunc, SpriteFont font, Color textColor)
 {
     Font      = font;
     TextColor = textColor;
     Renderer  = this;
     AddComponent(() => Text = textFunc());
 }
        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            Color clr = ColorTranslator.FromHtml(value.ToString());

            Microsoft.Xna.Framework.Color rColor = new Microsoft.Xna.Framework.Color(clr.R, clr.G, clr.B, clr.A);
            return(rColor);
        }
        public static Texture2D ColorToTexture(GraphicsDevice device, Color color, int width, int height)
        {
            Texture2D texture = new Texture2D(device, 1, 1);
            texture.SetData<Color>(new Microsoft.Xna.Framework.Color[] { color });

            return texture;
        }
Example #7
0
 public Label(string text, SpriteFont font, Color textColor)
 {
     Text      = text;
     Font      = font;
     TextColor = textColor;
     Renderer  = this;
 }
Example #8
0
        /// <summary>
        /// Removes the index row from the contained data.  Row 0 is the top of the texture.
        /// </summary>
        /// <param name="rowToRemove">The index of the row to remove.  Index 0 is the top row.</param>
        #endregion
        public void RemoveRow(int rowToRemove)
        {
            Color[] newData = new Color[width * height];

            int destinationY = 0;
            int destinationX = 0;

            for (int y = 0; y < height; y++)
            {
                if (y == rowToRemove)
                {
                    continue;
                }

                destinationX = 0;
                for (int x = 0; x < width; x++)
                {
                    newData[destinationY * width + destinationX] = mData[y * width + x];

                    destinationX++;
                }

                destinationY++;
            }
            height--;

            mData = newData;
        }
Example #9
0
        public ApplyValueResult TryGetValueOnUi(out object value)
        {
            var result = ApplyValueResult.UnknownError;

            value = null;
            if (!this.HasEnoughInformationToWork() || mInstancePropertyType == null)
            {
                result = ApplyValueResult.NotEnoughInformation;
            }
            else
            {
                if (mInstancePropertyType == typeof(Microsoft.Xna.Framework.Color))
                {
                    Microsoft.Xna.Framework.Color colorToReturn = new Microsoft.Xna.Framework.Color(
                        ColorPicker.SelectedColor.R,
                        ColorPicker.SelectedColor.G,
                        ColorPicker.SelectedColor.B,
                        ColorPicker.SelectedColor.A);

                    result = ApplyValueResult.Success;

                    value = colorToReturn;
                }
                else
                {
                    result = ApplyValueResult.NotSupported;
                }
            }

            return(result);
        }
        public FlappyDogeScene()
            : base()
        {
            ClearColor = new Microsoft.Xna.Framework.Color(74, 195, 206);

            container = new DisplayObject() { Y = 200 };

            container.AddNode(new Sprite("Scenes//Flappy//clouds"));
            container.AddNode(new Sprite("Scenes//Flappy//buildings") { Y = 65 });
            container.AddNode(new Sprite("Scenes//Flappy//buildings") { Y = 65, X = 180 });
            container.AddNode(new Sprite("Scenes//Flappy//buildings") { Y = 65, X = 180 * 2 });
            container.AddNode(new Sprite("Scenes//Flappy//buildings") { Y = 65, X = 180 * 3 });

            floor = new DisplayObject() { Y = 65 + 165 + 200 };

            for (int i = 0; i < 20; i++)
            {
                floor.AddNode(new Sprite("Scenes//Flappy//floor") { X = 60 * i });
            }

            doge = new Sprite("Scenes//Flappy//birds");

            AddNode(container);
            AddNode(floor);
            AddNode(doge);

            GeneratePipe();
        }
Example #11
0
 public void Parse(byte[] data, int position)
 {
     if (data.Length != 4 || data[3] != 0)
         throw new ArgumentException();
     //Format is Blue, Green, Red, [Reserved Byte]
     Colors[position] = new Color(data[2], data[1], data[0], 0);
 }
Example #12
0
 public static Color Lerp(Color value1, Color value2, double amount)
 {
     return(new Color(XnaColor.Lerp(
                          value1.AsXnaColor(),
                          value2.AsXnaColor(),
                          (float)amount)));
 }
Example #13
0
        public static Vector2 DrawParsedString(this SpriteBatch spriteBatch, SpriteFont font, StringPart text, Vector2 position, Color colour, float rotation, Vector2 origin, Vector2 scale, int wrapWidth, Justification justification)
        {
            if (wrapWidth <= 0)
                throw new ArgumentOutOfRangeException("wrapWidth", "wrapWidth must be greater than 0.");

            return DrawParsedString(spriteBatch, font, text, position, colour, rotation, origin, scale, wrapWidth, justification, true);
        }
Example #14
0
 internal Color(XnaColor c)
 {
     RedComponent   = c.R;
     GreenComponent = c.G;
     BlueComponent  = c.B;
     AlphaComponent = c.A;
 }
Example #15
0
        /// <summary>
        /// Event handler updates the spinning triangle control when
        /// one of the three vertex color combo boxes is altered.
        /// </summary>
        void vertexColor_SelectedIndexChanged(object sender, System.EventArgs e)
        {
            // Which vertex was changed?
            int vertexIndex;

            if (sender == vertexColor1)
                vertexIndex = 0;
            else if (sender == vertexColor2)
                vertexIndex = 1;
            else if (sender == vertexColor3)
                vertexIndex = 2;
            else
                return;

            // Which color was selected?
            ComboBox combo = (ComboBox)sender;

            string colorName = combo.SelectedItem.ToString();

            GdiColor gdiColor = GdiColor.FromName(colorName);

            XnaColor xnaColor = new XnaColor(gdiColor.R, gdiColor.G, gdiColor.B);

            // Update the spinning triangle control with the new color.
            spinningTriangleControl.Vertices[vertexIndex].Color = xnaColor;
        }
Example #16
0
        void DrawPath(List <PointF> path, XNAColor color, bool closed)
        {
            if (path.Count <= 1)
            {
                return;
            }

            vertexList.Clear();

            for (int i = 0; i < path.Count; i++)
            {
                vertexList.Add(new VertexPositionColorTexture(PointFToXNAVector3(path[i]), color, XNAVector2.Zero));
            }

            if (closed)
            {
                vertexList.Add(new VertexPositionColorTexture(PointFToXNAVector3(path[0]), color, XNAVector2.Zero));
            }

            bool succeed = FlushVertexList(vertexList, true, false, null);

            if (!succeed)
            {
                return;
            }

            DrawLineStrip(vertexList.Count - 1);
        }
Example #17
0
        public void RemoveColumn(int columnToRemove)
        {
            Color[] newData = new Color[width * height];

            int destinationY = 0;
            int destinationX = 0;

            int newWidth = width - 1;

            for (int y = 0; y < height; y++)
            {
                destinationX = 0;
                for (int x = 0; x < width; x++)
                {
                    if (x == columnToRemove)
                    {
                        continue;
                    }
                    newData[destinationY * newWidth + destinationX] = mData[y * width + x];

                    destinationX++;
                }

                destinationY++;
            }
            width = newWidth;

            mData = newData;
        }
        /// <summary>
        /// Captures the screen onto a Texture2D.
        /// Note: This is not a copy of the current backbuffer (displayed screen image).
        /// This is instead an entirely new rendering of the screen onto a Texture2D which is relativly slow. So performance wise, it's not something you'll want to do each frame.
        /// </summary>
        public Texture2D CaptureScreen()
        {
            if (graphicsDeviceService != null && Render != null)
            {
                bool debugDraw = EnableDebugDraw;
                EnableDebugDraw = false;

                BeginDraw();

                using (RenderTarget2D renderTarget = new RenderTarget2D(GraphicsDevice, Width, Height)) {
                    GraphicsDevice.SetRenderTarget(renderTarget);
                    OnDraw();
                    GraphicsDevice.SetRenderTarget(null);
                    EnableDebugDraw = debugDraw;

                    // Copy the rendertargets color data into a color array.
                    XNAColor[] colors = new XNAColor[Width * Height];
                    renderTarget.GetData(colors);

                    // Set the copied color data to the new Texture2D.
                    // This makes sure that the screenshot doesn't get lost with the rendertarget. This also prevents memory leaks as the rendertarget can now safely be disposed.
                    Texture2D texture = new Texture2D(GraphicsDevice, Width, Height);
                    texture.SetData(colors);

                    return(texture);
                }
            }

            return(null);
        }
Example #19
0
        public void RemoveColumns(IList <int> columnsToRemove)
        {
            Color[] newData = new Color[width * height];

            int destinationY = 0;
            int destinationX = 0;

            int newWidth = width - columnsToRemove.Count;

            for (int y = 0; y < height; y++)
            {
                destinationX = 0;
                for (int x = 0; x < width; x++)
                {
                    if (columnsToRemove.Contains(x))
                    {
                        continue;
                    }
                    newData[destinationY * newWidth + destinationX] = mData[y * width + x];

                    destinationX++;
                }

                destinationY++;
            }
            width = newWidth;

            mData = newData;
        }
Example #20
0
        /// <summary>
        /// Edits the given value.
        /// </summary>
        /// <param name="context">Context infromation.</param>
        /// <param name="provider">Service provider.</param>
        /// <param name="value">Value to be edited.</param>
        /// <returns>An edited value.</returns>
        public override object EditValue( ITypeDescriptorContext context, IServiceProvider provider, object value )
        {
            if( provider != null )
            {
                var service = (IWindowsFormsEditorService) provider.GetService( typeof( IWindowsFormsEditorService ) ) ;

                if( service == null )
                {
                    return value ;
                }

                if( _colorUi == null )
                {
                    _colorUi = new ColorUiWrapper( this ) ;
                }

                var xnaColor = (Color) value ;

                _colorUi.Start( service, System.Drawing.Color.FromArgb( xnaColor.A, xnaColor.R, xnaColor.G, xnaColor.B ) ) ;

                service.DropDownControl( _colorUi.Control ) ;

                if( ( _colorUi.Value != null ) )
                {
                    var rescolor = (System.Drawing.Color) _colorUi.Value ;

                    value = new Color( rescolor.R, rescolor.G, rescolor.B, rescolor.A ) ;
                }

                _colorUi.End( ) ;
            }

            return value ;
        }
Example #21
0
        private void DrawSegmentMeshLines(SegmentMeshInfo transform, XNAColor color)
        {
            if (transform == null || transform.arap == null)
            {
                return;
            }

            List <PointF> vts = transform.arap.GetMeshVertexList();

            vertexList.Clear();

            for (int i = 0; i < vts.Count; i += 3)
            {
                XNAVector3 pos1 = new XNAVector3(vts[i].X, -vts[i].Y, 0);
                XNAVector3 pos2 = new XNAVector3(vts[i + 1].X, -vts[i + 1].Y, 0);
                XNAVector3 pos3 = new XNAVector3(vts[i + 2].X, -vts[i + 2].Y, 0);
                vertexList.Add(new VertexPositionColorTexture(pos1, color, XNAVector2.Zero));
                vertexList.Add(new VertexPositionColorTexture(pos2, color, XNAVector2.Zero));
                vertexList.Add(new VertexPositionColorTexture(pos2, color, XNAVector2.Zero));
                vertexList.Add(new VertexPositionColorTexture(pos3, color, XNAVector2.Zero));
                vertexList.Add(new VertexPositionColorTexture(pos3, color, XNAVector2.Zero));
                vertexList.Add(new VertexPositionColorTexture(pos1, color, XNAVector2.Zero));
            }

            bool succeed = FlushVertexList(vertexList, true, false, null);

            if (!succeed)
            {
                return;
            }

            DrawLineList(vts.Count / 2);
        }
Example #22
0
 public InputBox(string name, bool selectable = false)
     : base(name, selectable)
 {
     BackGroundColor = new Microsoft.Xna.Framework.Color(Microsoft.Xna.Framework.Color.Black, 127);
     BorderColor = new Microsoft.Xna.Framework.Color(Microsoft.Xna.Framework.Color.Gray,191);
     BorderWidth = 3;
 }
Example #23
0
        internal IngameMenuWindow(Race setRace)
        {
            curRace = setRace;
             LevelGameScreen.Game.GamePaused = true;

             BackgroundColor = new Microsoft.Xna.Framework.Color (0.3f, 0.0f, 0.0f, 0.5f);

             //Width = background.Width;
             //Height = background.Height;

             UIResource res = WarFile.GetUIResource(setRace == Race.Humans ? 368 : 369);

             background = new UIImage(WWTexture.FromImageResource(WarFile.GetImageResource(res.BackgroundImageResourceIndex)));
             background.InitWithUIResource (res);
             AddComponent (background);

             background.X = 120;
             background.Y = 20;

             continueButton = (UIButton)background.Components [6];
             continueButton.OnMouseUpInside += closeButton_OnMouseUpInside;

             quitButton = (UIButton)background.Components [5];
             quitButton.OnMouseUpInside += quitButton_OnMouseUpInside;

             MouseCursor.State = MouseCursorState.Pointer;
        }
Example #24
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ImageBox"/> class.
 /// </summary>
 /// <param name="parent">This controls parent control.</param>
 /// <param name="texture">The texture.</param>
 /// <param name="colour">The colour.</param>
 /// <param name="sourceRectangle">The source rectangle.</param>
 public ImageBox(Control parent, Texture2D texture, Color colour, Rectangle? sourceRectangle)
     : base(parent)
 {
     Texture = texture;
     SourceRectangle = sourceRectangle;
     Colour = colour;
 }
Example #25
0
        private void DrawSegmentMeshes(Segment seg, SegmentMeshInfo transform, XNAColor color, bool textureEnabled)
        {
            if (seg == null || seg.bmp == null || transform == null || transform.arap == null)
            {
                return;
            }

            Texture2D texture = null;

            if (textureEnabled)
            {
                texture = ToTexture2D(seg.bmp);
                if (texture == null || texture.Width <= 0 || texture.Height <= 0)
                {
                    return;
                }
            }

            if (saveRenderedSegment)
            {
                var bmp = transform.arap.ToBitmap();
                if (bmp != null)
                {
                    bmp.Save("./" + seg.name + ".bmp");
                }
            }

            List <PointF> vts = transform.arap.GetMeshVertexList();
            List <PointF> cds = !textureEnabled ? null : transform.arap.GetMeshCoordList(texture.Width, texture.Height);

            if (textureEnabled && (cds == null || cds.Count != vts.Count))
            {
                return;
            }

            vertexList.Clear();

            for (int i = 0; i < vts.Count; i += 3)
            {
                XNAVector3 pos1   = new XNAVector3(vts[i].X, -vts[i].Y, 0);
                XNAVector3 pos2   = new XNAVector3(vts[i + 1].X, -vts[i + 1].Y, 0);
                XNAVector3 pos3   = new XNAVector3(vts[i + 2].X, -vts[i + 2].Y, 0);
                XNAVector2 coord1 = !textureEnabled ? XNAVector2.Zero : new XNAVector2(cds[i].X, cds[i].Y);
                XNAVector2 coord2 = !textureEnabled ? XNAVector2.Zero : new XNAVector2(cds[i + 1].X, cds[i + 1].Y);
                XNAVector2 coord3 = !textureEnabled ? XNAVector2.Zero : new XNAVector2(cds[i + 2].X, cds[i + 2].Y);
                vertexList.Add(new VertexPositionColorTexture(pos1, color, coord1));
                vertexList.Add(new VertexPositionColorTexture(pos2, color, coord2));
                vertexList.Add(new VertexPositionColorTexture(pos3, color, coord3));
            }

            bool succeed = FlushVertexList(vertexList, true, textureEnabled, texture);

            if (!succeed)
            {
                return;
            }

            DrawMeshes(vts.Count / 3);
        }
Example #26
0
        public TextBox(Control parent, Game game, SpriteFont font, string title, string description)
            : base(parent)
        {
            _textString = string.Empty;
            _text = new StringBuilder();
            _textString = "";
            _typing = false;
            _title = title;
            _description = description;

            _drawBuffer = new StringBuilder();
            _font = font;
            _colour = Color.White;
            _drawStartIndex = 0;
            _drawEndIndex = 0;

            _blink = new Pulser(PulserType.SquareWave, TimeSpan.FromSeconds(0.5));
            _keyRepeat = new Pulser(PulserType.Simple, TimeSpan.FromSeconds(0.1), TimeSpan.FromSeconds(0.5));
            _selectionStartIndex = 0;
            _selectionEndIndex = 0;
            _measurementBuffer = new StringBuilder();

            _blank = new Texture2D(game.GraphicsDevice, 1, 1);
            _blank.SetData(new Color[] { Color.White });

            IgnoredCharacters = new List<char>();

            SetSize(100, font.LineSpacing);

            Gestures.Bind((g, t, i) =>
                {
                    i.Owner.Focus(this);
                    BeginTyping(i.Owner.ID < 4 ? (PlayerIndex)i.Owner.ID : PlayerIndex.One);
                },
                new ButtonPressed(Buttons.A),
                new MousePressed(MouseButtons.Left));

            Gestures.Bind((g, t, i) =>
                {
                    var keyboard = (KeyboardDevice)i;
                    foreach (var character in keyboard.Characters)
                        Write(character.ToString(CultureInfo.InvariantCulture));
                },
                new CharactersEntered());

            Gestures.Bind((g, t, i) => Copy(),
                new KeyCombinationPressed(Keys.C, Keys.LeftControl),
                new KeyCombinationPressed(Keys.C, Keys.RightControl));

            Gestures.Bind((g, t, i) => Cut(),
                new KeyCombinationPressed(Keys.X, Keys.LeftControl),
                new KeyCombinationPressed(Keys.X, Keys.RightControl));

            Gestures.Bind((g, t, i) => Paste(),
                new KeyCombinationPressed(Keys.V, Keys.LeftControl),
                new KeyCombinationPressed(Keys.V, Keys.RightControl));

            FocusedChanged += control => { if (!IsFocused) _typing = false; };
        }
Example #27
0
 public static UColor Color(XColor input, ref UColor output)
 {
     output.r = input.R / 255f;
     output.g = input.G / 255f;
     output.b = input.B / 255f;
     output.a = input.A / 255f;
     return(output);
 }
Example #28
0
        void Initialize()
        {
            SpriteBatch = new SpriteBatch(GraphicsDevice);

            WhiteTexture = new Texture2D(GraphicsDevice, 1, 1);
            var whitePixels = new Microsoft.Xna.Framework.Color[] { Microsoft.Xna.Framework.Color.White };
            WhiteTexture.SetData<Microsoft.Xna.Framework.Color>(whitePixels);
        }
Example #29
0
        /// <summary>
        /// Changes the glyph, foreground, and background of a cell.
        /// </summary>
        /// <param name="x">The x location of the cell.</param>
        /// <param name="y">The y location of the cell.</param>
        /// <param name="glyph">The desired glyph.</param>
        /// <param name="foreground">The desired foreground.</param>
        public void SetGlyph(int x, int y, int glyph, Color foreground)
        {
            int index = y * textSurface.Width + x;

            textSurface.Cells[index].Foreground = foreground;
            textSurface.Cells[index].Glyph      = glyph;
            textSurface.IsDirty = true;
        }
Example #30
0
 /// <summary>
 /// Creates a TextComponent with a given <see cref="Microsoft.Xna.Framework.Graphics.SpriteFont"/>.
 /// </summary>
 /// <param name="font">SpriteFont reference containing the raw font data.</param>
 /// <param name="color">Color for each glyph to be drawn with.</param>
 /// <param name="shader">Shader used for rendering in a <see cref="Microsoft.Xna.Framework.Graphics.SpriteBatch"/>.</param>
 /// <param name="text">Text message to be rendered.</param>
 public TextComponent(SpriteFont font, Color color, Effect shader, string text = null) : base(true, null)
 {
     Color    = color;
     Font     = font;
     FontPath = null;
     Shader   = shader;
     Text     = text;
 }
Example #31
0
 private static void SetAlphaAndColorValues(Text text, RecursiveVariableFinder rvf)
 {
     Microsoft.Xna.Framework.Color color = ColorFromRvf(rvf);
     text.Red   = color.R;
     text.Green = color.G;
     text.Blue  = color.B;
     text.Alpha = color.A;  //Is alpha supported?
 }
Example #32
0
        /// <summary>
        /// Creates a new <see cref="ColorTweener"/> class instance.
        /// </summary>
        /// <param name="start">Initial value</param>
        /// <param name="finish">Final value</param>
        public ColorTweener(Microsoft.Xna.Framework.Color start, Microsoft.Xna.Framework.Color finish)
        {
            this.start  = start;
            this.finish = finish;
            this.tween  = MotionTweens.Linear;

            this.CreateTweens();
        }
 private static void PreMultiplyAlphas(Texture2D texture)
 {
     var data = new Microsoft.Xna.Framework.Color[texture.Width * texture.Height];
     texture.GetData(data);
     for (int i = 0; i != data.Length; ++i)
         data[i] = Microsoft.Xna.Framework.Color.FromNonPremultiplied(data[i].ToVector4());
     texture.SetData(data);
 }
Example #34
0
        public Microsoft.Xna.Framework.Color GetBackgroundColor()
        {
            Color curColor = colorDialog.Color;

            var bgColor = new Microsoft.Xna.Framework.Color((int)curColor.R, (int)curColor.G, (int)curColor.B, (int)curColor.A);

            return(bgColor);
        }
Example #35
0
        /// <summary>
        /// Changes the glyph, foreground, and background of a cell.
        /// </summary>
        /// <param name="x">The x location of the cell.</param>
        /// <param name="y">The y location of the cell.</param>
        /// <param name="glyph">The desired glyph.</param>
        /// <param name="foreground">The desired foreground.</param>
        /// <param name="background">The desired background.</param>
        public void SetGlyph(int x, int y, int glyph, Color foreground, Color background)
        {
            int index = y * textSurface.Width + x;

            textSurface.Cells[index].Background = background;
            textSurface.Cells[index].Foreground = foreground;
            textSurface.Cells[index].GlyphIndex = glyph;
        }
Example #36
0
        public Circle()
        {
            Radius = 1;
            Color  = Color.White;
#if SILVERLIGHT
            FillColor = new Color(0, 0, 0, 0);
#endif
        }
Example #37
0
 public static Microsoft.Xna.Framework.Graphics.Texture2D cropTexture2D(Microsoft.Xna.Framework.Graphics.GraphicsDevice GraphicsDevice, Microsoft.Xna.Framework.Graphics.Texture2D originalTexture, Microsoft.Xna.Framework.Rectangle sourceRectangle)
 {
     Microsoft.Xna.Framework.Graphics.Texture2D cropTexture = new Microsoft.Xna.Framework.Graphics.Texture2D(GraphicsDevice, sourceRectangle.Width, sourceRectangle.Height);
     Microsoft.Xna.Framework.Color[] data = new Microsoft.Xna.Framework.Color[sourceRectangle.Width * sourceRectangle.Height];
     originalTexture.GetData(0, sourceRectangle, data, 0, data.Length);
     cropTexture.SetData(data);
     return cropTexture;
 }
Example #38
0
        /// <summary>
        /// Laskee kahden värin (euklidisen) etäisyyden RGB-väriavaruudessa.
        /// Värikomponentit ovat välillä 0-255 joten suurin mahdollinen etäisyys
        /// (musta ja valkoinen) on noin 441,68.
        /// </summary>
        /// <returns>Etäisyys</returns>
        internal static double Distance(XnaColor a, XnaColor b)
        {
            double rd = Math.Pow(a.R - b.R, 2);
            double gd = Math.Pow(a.G - b.G, 2);
            double bd = Math.Pow(a.B - b.B, 2);

            return(Math.Sqrt(rd + gd + bd));
        }
Example #39
0
        public override void DrawString(SpriteFont font, string text, Point position, Color color)
        {
            XnaSpriteFont xnaFont  = font.GetSpriteFont as XnaSpriteFont;
            XnaPoint      xnaPoint = new XnaPoint(position.X, position.Y);
            XnaColor      xnaColor = new XnaColor(color.R, color.G, color.B, color.A);

            this.spriteBatch.DrawString(xnaFont, text, xnaPoint.ToVector2(), xnaColor);
        }
Example #40
0
 public static XColor Color(UColor color, ref XColor output)
 {
     output.R = (byte)(color.r * 255);
     output.G = (byte)(color.g * 255);
     output.B = (byte)(color.b * 255);
     output.A = (byte)(color.a * 255);
     return(output);
 }
Example #41
0
 public static UColor32 Color(XColor input, ref UColor32 output)
 {
     output.r = input.R;
     output.g = input.G;
     output.b = input.B;
     output.a = input.A;
     return(output);
 }
Example #42
0
        public Texture2D FromStream(Stream stream, bool preMultiplyAlpha = true)
        {
            Texture2D texture;

            if (_needsBmp)
            {
                // Load image using GDI because Texture2D.FromStream doesn't support BMP
                using (Image image = Image.FromStream(stream))
                {
                    // Now create a MemoryStream which will be passed to Texture2D after converting to PNG internally
                    using (MemoryStream ms = new MemoryStream())
                    {
                        image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                        ms.Seek(0, SeekOrigin.Begin);
                        texture = Texture2D.FromStream(_graphicsDevice, ms);
                    }
                }
            }
            else
            {
                texture = Texture2D.FromStream(_graphicsDevice, stream);
            }

            if (preMultiplyAlpha)
            {
                // Setup a render target to hold our final texture which will have premulitplied alpha values
                using (RenderTarget2D renderTarget = new RenderTarget2D(_graphicsDevice, texture.Width, texture.Height))
                {
                    Viewport viewportBackup = _graphicsDevice.Viewport;
                    _graphicsDevice.SetRenderTarget(renderTarget);
                    _graphicsDevice.Clear(Color.Black);

                    // Multiply each color by the source alpha, and write in just the color values into the final texture
                    _spriteBatch.Begin(SpriteSortMode.Immediate, BlendColorBlendState);
                    _spriteBatch.Draw(texture, texture.Bounds, Color.White);
                    _spriteBatch.End();

                    // Now copy over the alpha values from the source texture to the final one, without multiplying them
                    _spriteBatch.Begin(SpriteSortMode.Immediate, BlendAlphaBlendState);
                    _spriteBatch.Draw(texture, texture.Bounds, Color.White);
                    _spriteBatch.End();

                    // Release the GPU back to drawing to the screen
                    _graphicsDevice.SetRenderTarget(null);
                    _graphicsDevice.Viewport = viewportBackup;

                    // Store data from render target because the RenderTarget2D is volatile
                    Color[] data = new Color[texture.Width * texture.Height];
                    renderTarget.GetData(data);

                    // Unset texture from graphic device and set modified data back to it
                    _graphicsDevice.Textures[0] = null;
                    texture.SetData(data);
                }
            }

            return(texture);
        }
Example #43
0
        public static ImageData FromTexture2D(Texture2D texture2D)
        {
#if DEBUG
            if (texture2D.IsDisposed)
            {
                throw new Exception("The texture by the name " + texture2D.Name + " is disposed, so its data can't be accessed");
            }
#endif

            ImageData imageData = null;
            // Might need to make this FRB MDX as well.
#if FRB_XNA || SILVERLIGHT || WINDOWS_PHONE
            switch (texture2D.Format)
            {
#if !XNA4 && !MONOGAME
            case SurfaceFormat.Bgr32:
            {
                Color[] data = new Color[texture2D.Width * texture2D.Height];
                texture2D.GetData <Color>(data);

                // BRG doesn't have alpha, so we'll assume an alpha of 1:
                for (int i = 0; i < data.Length; i++)
                {
                    data[i].A = 255;
                }

                imageData = new ImageData(
                    texture2D.Width, texture2D.Height, data);
            }
            break;
#endif
            case SurfaceFormat.Color:
            {
                Color[] data = new Color[texture2D.Width * texture2D.Height];
                texture2D.GetData <Color>(data);

                imageData = new ImageData(
                    texture2D.Width, texture2D.Height, data);
            }
            break;

            case SurfaceFormat.Dxt3:

                Byte[] byteData = new byte[texture2D.Width * texture2D.Height];
                texture2D.GetData <byte>(byteData);

                imageData = new ImageData(texture2D.Width, texture2D.Height, byteData);

                break;

            default:
                throw new NotImplementedException("The format " + texture2D.Format + " isn't supported.");

                //break;
            }
#endif
            return(imageData);
        }
Example #44
0
        ///  <summary>
        ///     Create a Texture2D from a bitmap font.
        ///  </summary>
        /// <param name="fontName"></param>
        /// <param name="text"></param>
        ///  <param name="fontSize"></param>
        ///  <param name="color"></param>
        /// <param name="textAlignment"></param>
        /// <param name="maxWidth"></param>
        ///  <returns></returns>
        internal static Texture2D Create(string fontName, string text, int fontSize, Color color, Alignment textAlignment, int maxWidth)
        {
            // Stores the size of the text & Texture2D
            SizeF textSize;

            var alignment = GetAlignment(textAlignment);

            var font = GetCustomFont(fontName, fontSize) ?? new Font(fontName, fontSize, FontStyle.Regular);

            // Here we're creating a "virtual" graphics instance to measure
            // the size of the text.
            using (var bmp = new Bitmap(1, 1, PixelFormat.Format32bppArgb))
                using (var g = System.Drawing.Graphics.FromImage(bmp))
                    using (var format = new StringFormat())
                    {
                        g.SmoothingMode      = SmoothingMode.HighQuality;
                        g.InterpolationMode  = InterpolationMode.HighQualityBilinear;
                        g.PixelOffsetMode    = PixelOffsetMode.HighQuality;
                        g.TextRenderingHint  = TextRenderingHint.AntiAliasGridFit;
                        g.CompositingQuality = CompositingQuality.HighQuality;
                        g.PageUnit           = GraphicsUnit.Pixel;

                        format.Alignment     = alignment;
                        format.LineAlignment = alignment;

                        // Measure the string
                        textSize = g.MeasureString(text, font, maxWidth, format);
                    }

            // Create the actual bitmap using the size of the text.
            using (var bmp = new Bitmap((int)(textSize.Width + 0.5), (int)(textSize.Height + 0.5), PixelFormat.Format32bppArgb))
                using (var g = System.Drawing.Graphics.FromImage(bmp))
                    using (var brush = new SolidBrush(System.Drawing.Color.White))
                        using (var format = new StringFormat())
                        {
                            g.SmoothingMode      = SmoothingMode.HighQuality;
                            g.InterpolationMode  = InterpolationMode.HighQualityBilinear;
                            g.PixelOffsetMode    = PixelOffsetMode.HighQuality;
                            g.TextRenderingHint  = TextRenderingHint.AntiAliasGridFit;
                            g.CompositingQuality = CompositingQuality.HighQuality;
                            g.PageUnit           = GraphicsUnit.Pixel;

                            format.Alignment     = alignment;
                            format.LineAlignment = alignment;

                            var rect = new RectangleF(0, 0, textSize.Width, textSize.Height);
                            g.DrawString(text, font, brush, rect, format);

                            // Flush all graphics changes to the bitmap
                            g.Flush();

                            // Dispose of the font.
                            font.Dispose();

                            // bmp.RawFormat = ImageFormat.Png;
                            return(AssetLoader.LoadTexture2D(ImageToByte2(bmp)));
                        }
        }
Example #45
0
        public override void DrawImage(int x, int y, int w, int h, IImage image, float us, float vs, float ue, float ve, Color color, bool outLineOnly)
        {
            Texture2D texture = ((XNAImage)image).Texture;
            Microsoft.Xna.Framework.Rectangle destinationRectangle = new Microsoft.Xna.Framework.Rectangle(x, y, w, h);
            Microsoft.Xna.Framework.Color imageColor = new Microsoft.Xna.Framework.Color(color.R, color.G, color.B, color.A);
            Microsoft.Xna.Framework.Rectangle sourceRectangle = new Microsoft.Xna.Framework.Rectangle((int)(us * texture.Width), (int)(ue * texture.Height), (int)(vs * texture.Width), (int)(ve * texture.Height));

            this.spriteBatch.Draw(texture, destinationRectangle, sourceRectangle, imageColor);
        }
Example #46
0
        public static Color MutateBy(this Color baseColor, Color target)
        {
            Color newC = Color.Black;

            newC.R = Convert.ToByte((baseColor.R + target.R) / 4);
            newC.G = Convert.ToByte((baseColor.G + target.G) / 4);
            newC.B = Convert.ToByte((baseColor.B + target.B) / 4);
            return(newC);
        }
Example #47
0
 public Firework(int Frames, float Time, Microsoft.Xna.Framework.Vector2 Position, Microsoft.Xna.Framework.Color Color)
 {
     CurFrame = 0;
     MaxFrame = Frames;
     TimeForFrame = Time;
     TimeLastChange = 0;
     this.Position = Position;
     this.Color = Color;
 }
Example #48
0
        /// <summary>
        /// Parses this string into a Color.
        /// </summary>
        /// <param name="value"></param>
        /// <param name="colour">The parsed colour.</param>
        /// <returns>White if not found, the value otherwise</returns>
        public static bool ToColour(this string value, out Color colour)
        {
            if (string.IsNullOrEmpty(value))
                throw new ArgumentNullException("value");

            if (TryGetColourByName(value, out colour))
                return true;

            string[] values = value.Split(new char[] { ' ', ',', ';', ':' });

            byte[] components = new byte[4];

            if (values.Length == 1)
            {
                if (values[0].TryToByte(out components[0]))
                {
                    colour = new Color(components[0], components[0], components[0]);
                    return true;
                }
                
                if (values[0].StartsWith("0x", StringComparison.Ordinal))
                {
                    values[0] = values[0].Remove(0, 2);

                    if (values[0].Length == 6)
                        colour = values[0].FromRgb();
                    else
                        colour = values[0].FromArgb();
                    return true;
                }
            }
            else if (values.Length == 3)
            {
                if (values[0].TryToByte(out components[0]) &&
                    values[1].TryToByte(out components[1]) &&
                    values[2].TryToByte(out components[2]))
                {
                    colour = new Color(components[0], components[1], components[2]);
                    return true;
                }
            }
            else if (values.Length == 4)
            {
                if (values[0].TryToByte(out components[0]) &&
                    values[1].TryToByte(out components[1]) &&
                    values[2].TryToByte(out components[2]) &&
                    values[3].TryToByte(out components[3]))
                {
                    colour = new Color(components[0], components[1], components[2], components[3]);
                    return true;
                }
            }

            colour = Color.White;
            return false;
        }
Example #49
0
 private static XnaColor[] ConvertToXnaColors(Color[] deltaColors)
 {
     var colors = new XnaColor[deltaColors.Length];
     for (int index = 0; index < deltaColors.Length; index++)
     {
         var color = deltaColors[index];
         colors[index] = new XnaColor(color.R, color.G, color.B, color.A);
     }
     return colors;
 }
 /// <summary>
 /// CPU bound alpha premultiply - roughly 30-40ms on X51.
 /// </summary>
 /// <param name="stream"></param>
 /// <param name="preMultiplyAlpha"></param>
 /// <returns></returns>
 public Texture2D FromStream(Stream stream, bool preMultiplyAlpha = true)
 {
     Texture2D texture = Texture2D.FromStream(_graphicsDevice, stream);
     Color[] data = new Color[texture.Width * texture.Height];
     texture.GetData(data);
     for (int i = 0; i != data.Length; ++i)
         data[i] = Color.FromNonPremultiplied(data[i].ToVector4());
     texture.SetData(data);
     return texture;
 }
Example #51
0
 public Particle(Vector3 position, Vector3 velocity, float angularVelocity, float size, float lifetimeScale, Color startColour, Color endColour)
 {
     Position = position;
     Velocity = velocity;
     AngularVelocity = angularVelocity;
     Size = size;
     LifetimeScale = lifetimeScale;
     StartColour = startColour;
     EndColour = endColour;
 }
Example #52
0
 public static Microsoft.Xna.Framework.Color HexToColor(String hexString)
 {
     Microsoft.Xna.Framework.Color actColor = Microsoft.Xna.Framework.Color.White;
     if (hexString.StartsWith("#") && hexString.Length == 7)
         actColor = new Microsoft.Xna.Framework.Color(
             int.Parse(hexString.Substring(1,2), System.Globalization.NumberStyles.HexNumber),
             int.Parse(hexString.Substring(3,2), System.Globalization.NumberStyles.HexNumber),
             int.Parse(hexString.Substring(5,2), System.Globalization.NumberStyles.HexNumber)
             );
     return actColor;
 }
Example #53
0
        /// <summary>
        /// Initializes a new instance of the <see cref="TextMultiButton"/> class.
        /// </summary>
        /// <param name="parent">This controls parent control.</param>
        /// <param name="font">The font.</param>
        /// <param name="options">The options.</param>
        public TextMultiButton(Control parent, SpriteFont font, string[] options)
            : base(parent)
        {
            if (options == null)
                throw new ArgumentNullException("options");
            if (options.Length == 0)
                throw new ArgumentException("There must be at least one option.", "options");

            Colour = Color.White;
            Highlight = Color.CornflowerBlue;
            _options = options;
            OptionsCount = options.Length;

            _leftArrow = new Label(this, font) {Text = "<"};
            _leftArrow.SetPoint(Points.TopLeft, 0, 0);
            _rightArrow = new Label(this, font) {Text = ">"};
            _rightArrow.SetPoint(Points.TopRight, 0, 0);

            _centreText = new Label(this, font) {Justification = Justification.Centre};
            _centreText.SetPoint(Points.TopLeft, _leftArrow.Area.Width, 0);
            _centreText.SetPoint(Points.TopRight, -_rightArrow.Area.Width, 0);
            _centreText.Text = options[0];

            ControlEventHandler recalcSize = delegate
            {
                Vector2 maxSize = Vector2.Zero;
                for (int i = 0; i < options.Length; i++)
                {
                    var size = font.MeasureString(options[i]);
                    maxSize.X = Math.Max(maxSize.X, size.X);
                    maxSize.Y = Math.Max(maxSize.Y, size.Y);
                }
                int arrowSize = (int)font.MeasureString("<").X;
                maxSize.X += arrowSize * 2;
                SetSize((int)maxSize.X, (int)maxSize.Y);
                _leftArrow.SetSize(arrowSize, font.LineSpacing);
                _rightArrow.SetSize(arrowSize, font.LineSpacing);
            };

            ControlEventHandler highlight = delegate(Control c)
            {
                ((Label)c).Colour = (c.IsFocused || c.IsWarm) ? Highlight : Colour;
            };

            _leftArrow.WarmChanged += highlight;
            _rightArrow.WarmChanged += highlight;
            recalcSize(this);

            SelectionChanged += delegate {
                _centreText.Text = this[SelectedOption];
            };

            BindGestures();
        }
 public PixelObject(string name,GraphicsDevice device, Color color)
     : base(name)
 {
     _ready = true;
     _color = color;
     _texture = new Texture2D(device, 1, 1);
     Color[] data = new Color[]
     {
         color
     };
     _texture.SetData(data);
 }
Example #55
0
        protected void OnButtonOkClicked (object sender, EventArgs e)
        {
            var color = new Microsoft.Xna.Framework.Color ();

            color.R = (byte)Convert.ToInt32(colorselection1.CurrentColor.Red);
            color.G = (byte)Convert.ToInt32(colorselection1.CurrentColor.Green);
            color.B = (byte)Convert.ToInt32(colorselection1.CurrentColor.Blue);
            color.A = (byte)(colorselection1.CurrentAlpha / 257);

            data = color.ToString ();
            Respond(Gtk.ResponseType.Ok);
        }
Example #56
0
        private static bool TryUppercase(StringPart text, out Color value)
        {
            var name = text.ToString().ToUpper();

            if (Colours.TryGetValue(name, out value))
            {
                Colours.Add(text, value);
                return true;
            }

            return false;
        }
Example #57
0
        public static Texture2D CreateRect(GraphicsDevice device, Microsoft.Xna.Framework.Color color, int width, int height)
        {
            Texture2D texture = new Texture2D(device, width, height, false, SurfaceFormat.Color);

            Microsoft.Xna.Framework.Color[] data = new Microsoft.Xna.Framework.Color[width * height];
            for (int i = 0; i < data.Length; i++)
                data[i] = color;

            texture.SetData<Microsoft.Xna.Framework.Color>(data);

            return texture;
        }
Example #58
0
        private static bool TryComponents(StringPart text, out Color value)
        {
            var name = text.ToString().ToUpper();
            var parts = name.Split(new char[] { ' ', ',', ';', ':' });

            if (ReadColourComponents(parts, out value))
            {
                Colours.Add(text, value);
                return true;
            }

            return false;
        }
Example #59
0
        /// <summary>
        /// Initializes a new instance of the <see cref="StatisticTextLog"/> class.
        /// </summary>
        public StatisticTextLog(Control parent, SpriteFont font, bool autoAdd = false)
            : base(parent)
        {
            _autoAdd = autoAdd;
            _font = font;
            _textColour = Color.White;
            RespectSafeArea = true;
            _stats = new Dictionary<string, StatisticText>();
            SetPoint(Points.TopLeft, 0, 0);
            SetPoint(Points.Right, 0, 0);

            //AreaChanged += delegate(Control c) { UpdatePositions(); };
        }
Example #60
0
        /// <summary>
        /// Creates a rectangle texture from a specified color.
        /// </summary>
        /// <param name="color">The color.</param>
        /// <returns></returns>
        public static Texture2D CreateFromColor( BaseFluxGame game, Microsoft.Xna.Framework.Color color, int width, int height )
        {
            var texture = new Texture2D ( game.GraphicsDevice, width, height, true, SurfaceFormat.Color );

            Microsoft.Xna.Framework.Color[] colors = new Microsoft.Xna.Framework.Color[ (int) ( width * height ) ];
            for ( int i = 0; i < colors.Length; i++ ) {
                colors[ i ] = color;
            }

            texture.SetData ( colors );

            return texture;
        }