Ejemplo n.º 1
0
 public unsafe void Draw(DrawMethod drawMethod)
 {
     fixed(uint *bmpAddress = Bitmap)
     {
         drawMethod(bmpAddress, Width, Height);
     }
 }
Ejemplo n.º 2
0
        // -------------------------------------------------------------------
        // Draw
        // -------------------------------------------------------------------

        public void Draw(Graphics g, DrawMethod drawMethod, float zoom = 1.0f)
        {
            // Setting coords
            int x       = X;
            int x_width = 0;

            if (Width < 0)
            {
                x      += Width + SquareWidth;
                Width   = -Width;
                x_width = Width - SquareWidth;
            }

            int y        = Y;
            int y_height = 0;

            if (Height < 0)
            {
                y       += Height + SquareHeight;
                Height   = -Height;
                y_height = Height - SquareHeight;
            }

            if (SquareWidth != 0 && SquareHeight != 0)
            {
                drawMethod(g, x, y, zoom);
            }

            RealX = X - x_width;
            RealY = Y - y_height;
        }
Ejemplo n.º 3
0
 public void Add(DrawMethod drawMethod)
 {
     if (drawActionDelegate == null)
         drawActionDelegate = drawMethod;
     else
         drawActionDelegate += drawMethod;
 }
Ejemplo n.º 4
0
 public static unsafe void Draw(this IImage img, DrawMethod drawMethod)
 {
     fixed(uint *bmpAddress = img.Bitmap)
     {
         drawMethod(bmpAddress, img.Width, img.Height);
     }
 }
Ejemplo n.º 5
0
        /// <summary>
        /// 次の描画方法に変更します。
        /// </summary>
        void MoveToNextTechnique()
        {
            drawMethod = (DrawMethod)(drawMethod + 1);
            if (drawMethod == DrawMethod.MaxCount)
            {
                drawMethod = 0;
            }

            UpdateStatusString();
        }
Ejemplo n.º 6
0
 public void Add(DrawMethod drawMethod)
 {
     if (drawActionDelegate == null)
     {
         drawActionDelegate = drawMethod;
     }
     else
     {
         drawActionDelegate += drawMethod;
     }
 }
Ejemplo n.º 7
0
 public ObjectEvents(ObjectClick onClick, ObjectClick onEnter, ObjectClick onLeave, ObjectClick onMouseDown, ObjectClick onMouseUp, DrawMethod drawMethod, BoundingBox b)
 {
     this.MouseClick  = onClick;
     this.MouseEnter  = onEnter;
     this.MouseLeave  = onLeave;
     this.MouseDown   = onMouseDown;
     this.MouseUp     = onMouseUp;
     this.Draw        = drawMethod;
     this.IsIn        = false;
     this.IsMouseDown = false;
     this.Bounds      = b;
 }
Ejemplo n.º 8
0
 public ObjectEvents(ObjectClick onClick, ObjectClick onEnter, ObjectClick onLeave, ObjectClick onMouseDown, ObjectClick onMouseUp, DrawMethod drawMethod, BoundingBox b)
 {
     this.MouseClick = onClick;
     this.MouseEnter = onEnter;
     this.MouseLeave = onLeave;
     this.MouseDown = onMouseDown;
     this.MouseUp = onMouseUp;
     this.Draw = drawMethod;
     this.IsIn = false;
     this.IsMouseDown = false;
     this.Bounds = b;
 }
Ejemplo n.º 9
0
        /// <summary>
        /// Event handler for an assert.
        /// </summary>
        /// <param name="sender">Because Debug is a static class, this is always NULL.</param>
        /// <param name="args">Info about the assert.</param>
        private void HandleAssert(object sender, DebugEventArgs args)
        {
            updateMethod = Update_Assert;
            drawMethod   = Draw_Assert;

            // This method is running on the thread that asserted, so start a new thread for the
            // handler so it can kill off all the worker threads without killing itself.
            //handleAssertThread = new Thread(new ParameterizedThreadStart(HandleAssertThread));
            //handleAssertThread.Name = "HandleAssert";
            //handleAssertThread.IsBackground = true;
            //handleAssertThread.Start(args);
            HandleAssertThread(args);
        }
Ejemplo n.º 10
0
        private void button3_Click(object sender, EventArgs e)
        {
            //br = new SolidBrush(panel2.BackColor);
            //G.FillRectangle(br, 0, 0, B.Width, B.Height);

            P1.X = Convert.ToInt32(tbXb.Text);
            P1.Y = Convert.ToInt32(tbYb.Text);
            P2.X = Convert.ToInt32(tbXe.Text);
            P2.Y = Convert.ToInt32(tbYe.Text);
            Point      O1       = new Point(B.Width / 2, B.Height / 2);;
            int        number   = Convert.ToInt32(tbSegNumber.Text);
            double     ang      = 2 * Math.PI / number;
            DrawMethod DrawFunc = null;

            switch (cmbMethod.SelectedIndex)
            {
            case 0:
                DrawFunc = DDA;
                break;

            case 1:
                DrawFunc = BresenhamReal;
                break;

            case 2:
                DrawFunc = BresenhamInt;
                break;

            case 3:
                DrawFunc = BresenhamSmooth;
                break;

            case 4:
                DrawFunc = Standart;
                break;
            }
            double t_ang = 0;
            double l     = Convert.ToDouble(tbSegLength.Text);
            Point  PP2   = new Point();

            for (int i = 0; i < number; i++)
            {
                PP2.X = O1.X + (int)Math.Round(Math.Cos(t_ang) * l);
                PP2.Y = O1.Y + (int)Math.Round(Math.Sin(t_ang) * l);
                DrawFunc(O1, PP2, LineColor);
                t_ang = t_ang + ang;
            }
            pictBox.Refresh();
        }
Ejemplo n.º 11
0
        public void RunDrawer()
        {
            Board dboard = new Board(this.curveDrawer, drawSettings.BoardSizeX, drawSettings.BoardSizeY, drawSettings.StartCoordinateX, drawSettings.StartCoordinateY);

            phraseProvider.ReadResourceFile();


            string exit = String.Empty;

            do
            {
                iO.Clear();
                iO.SetCursor(drawSettings.StartCoordinateX, drawSettings.StartCoordinateY);
                Point2D current = dboard.GetCurrenttPosition();
                current.XCoordinate = drawSettings.StartCoordinateX;
                current.YCoordinate = drawSettings.StartCoordinateY;
                dboard.DrawBoard(drawSettings.HorizontalFiller, drawSettings.VerticalFiller, drawSettings.CornerFiller);
                iO.SetCursor(0, drawSettings.InfoCoordinateY);
                iO.WriteOutput(phraseProvider.GetPhrase("rules"));

                iO.SetCursor(settingsProvider.GetDrawSettings().StartCoordinateX + 1, settingsProvider.GetDrawSettings().StartCoordinateY + 1);
                DrawMethod draw = null;

                for (int i = 0; i < drawers.Count(); i++)
                {
                    int number = this.GetUserNumber();
                    dboard.inputes.Push(i + 1);

                    if (i != 0)
                    {
                        foreach (KeyValuePair <int, DrawMethod> kv in drawers)

                        {
                            draw -= this.drawers[kv.Key];
                        }
                    }

                    draw += this.drawers[number];
                    draw(dboard);
                    iO.SetCursor(drawSettings.StartCoordinateX, drawSettings.StartCoordinateY);
                }



                iO.SetCursor(0, drawSettings.ExitCoordinateY);
                iO.WriteOutput(phraseProvider.GetPhrase("Exit"));
                exit = iO.ReadInput();
            }while (exit != settingsProvider.GetDrawSettings().Exit);
        }
Ejemplo n.º 12
0
        public VolumetricRendererGame()
        {
            Debug.OnAssert += new EventHandler <DebugEventArgs>(HandleAssert);
            //Debug.BlockAfterAssert = true;

            // Set up and run initial threads.
            //mainThread = Thread.CurrentThread;
            //mainThread.Name = "Main";

            //updateLock = new object();
            //updateThread = new Thread(new ThreadStart(UpdateThread));
            //updateThread.Name = "Update";
            //updateThread.IsBackground = true;
            //updateThread.Start();

            //drawLock = new object();
            //drawThread = new Thread(new ThreadStart(DrawThread));
            //drawThread.Name = "Draw";
            //drawThread.IsBackground = true;
            //drawThread.Start();

            // Set up the game.
            updateMethod  = Update_Normal;
            drawMethod    = Draw_Normal;
            assertHandled = false;

            Content.RootDirectory = "Content";

            graphicsDM = new GraphicsDeviceManager(this);
            graphicsDM.PreferredBackBufferWidth       = 1280;
            graphicsDM.PreferredBackBufferHeight      = 960;
            graphicsDM.PreferMultiSampling            = false;
            graphicsDM.SynchronizeWithVerticalRetrace = false;
            graphicsDM.IsFullScreen = false;

            input         = new InputState();
            screenManager = new ScreenManager(this, input);
            Components.Add(screenManager);

            IsMouseVisible = true;
        }
Ejemplo n.º 13
0
        protected void Render(Graphics graphics, Image sourceImage, DrawMethod drawMethod, int leadingSize, int trailingSize, int distance)
        {
            // If we don't have an image to render just bug out, this allows us to call Render without checking sourceImage first.
            if (sourceImage == null)
            {
                return;
            }

            //
            // Draw the first segment of the image as defined by leadingSize, this is always drawn at (0, 0).
            //
            ProgressBar.DrawImage(
                graphics,
                sourceImage,
                new Rectangle(0, 0, leadingSize, this.Height),
                new Rectangle(0, 0, leadingSize, sourceImage.Height + 1));

            //
            // Figure out where the last segment of the image should be drawn, this is always to the right of the first segment
            // and then at the given distance minus the width of the last segment.
            //
            int trailerLeftPosition = Math.Max(leadingSize, distance - trailingSize);

            ProgressBar.DrawImage(
                graphics,
                sourceImage,
                new Rectangle(trailerLeftPosition, 0, trailingSize, this.Height),
                new Rectangle(sourceImage.Width - trailingSize, 0, trailingSize, sourceImage.Height + 1));


            //
            // We only draw the middle segment if the width of the first and last are less than what we need to display.
            //
            if (distance > leadingSize + trailingSize)
            {
                RenderCenterSegment(graphics, sourceImage, drawMethod, leadingSize, trailingSize, distance, trailerLeftPosition);
            }
        }
Ejemplo n.º 14
0
        private void RenderCenterSegment(Graphics graphics, Image sourceImage, DrawMethod drawMethod, int leadingSize, int trailingSize, int distance, int trailerLeftPosition)
        {
            switch (drawMethod)
            {
            case DrawMethod.Stretch:     // This draws the middle segment stretched to fill the area between the first and last segment.
                ProgressBar.DrawImage(
                    graphics,
                    sourceImage,
                    new Rectangle(leadingSize, 0, distance - (leadingSize + trailingSize), this.Height),
                    new Rectangle(leadingSize, 0, sourceImage.Width - (leadingSize + trailingSize), sourceImage.Height + 1));
                break;

            case DrawMethod.Tile:     // This draws the middle segment un-stretched as many times as required to fill the area between the first and last segment.
            {
                Region clipRegion = graphics.Clip;
                int    tileLeft   = leadingSize;
                int    tileWidth  = sourceImage.Width - (leadingSize + trailingSize);

                // By setting clip we don't have to change the size of either the source rectangle or the destination rectangle,
                // the clip will make sure the overflow is cropped away.
                graphics.Clip = new Region(new Rectangle(tileLeft, 0, trailerLeftPosition - tileLeft, this.Height));
                while (tileLeft < trailerLeftPosition)
                {
                    ProgressBar.DrawImage(
                        graphics,
                        sourceImage,
                        new Rectangle(tileLeft, 0, tileWidth, this.Height),
                        new Rectangle(leadingSize, 0, tileWidth, sourceImage.Height));

                    tileLeft += tileWidth;
                }
                graphics.Clip = clipRegion;
            }
            break;
            }
        }
Ejemplo n.º 15
0
	// returns a rectangle because it's possible that the top,left are outside of the 0,0 requested position.
	public static Rectangle Measure(String text, Graphics graphics, Font font, DrawMethod drawMethod = DrawMethod.Graphics, TextFormatFlags textFormatFlags = TextFormatFlags.Default, Rectangle? rect = null) {
		if (String.IsNullOrEmpty(text))
			return Rectangle.Empty;


		MultiKey mk = new MultiKey(text, graphics.TextRenderingHint, font, drawMethod, textFormatFlags, rect);
		//if (drawMethod == DrawMethod.Graphics)
		//	mk = new MultiKey(text, graphics.TextRenderingHint, font, drawMethod);
		//else {
		//	mk = new 

		Object o = ht[mk];
		if (o != null)
			return (Rectangle) o;

		Size size = Size.Empty;
		if (rect.HasValue) {
			var r2 = rect.Value;
			size = r2.Size;
			r2.Location = Point.Empty;
			rect = r2;
		}
		else
			size = (drawMethod == DrawMethod.Graphics ? graphics.MeasureString(text, font).ToSize() : TextRenderer.MeasureText(graphics, text, font, Size.Empty, textFormatFlags));

		int w = size.Width;
		int h = size.Height;
		if (w == 0 || h == 0) return Rectangle.Empty;
		Bitmap bitmap = new Bitmap(w, h, graphics);

		Graphics g2 = Graphics.FromImage(bitmap);
		g2.TextRenderingHint = graphics.TextRenderingHint;
		g2.SmoothingMode = graphics.SmoothingMode;
		g2.Clear(Color.White);
		if (drawMethod == DrawMethod.Graphics) {
			g2.DrawString(text, font, Brushes.Black, 0, 0);
		}
		else {
			// always specify a bounding rectangle. Otherwise if flags contains VerticalCenter it will be half cutoff above point (0,0)
			Rectangle r2 = (rect.HasValue ? rect.Value : new Rectangle(Point.Empty, size));
			TextRenderer.DrawText(g2, text, font, r2, Color.Black, Color.White, textFormatFlags);
		}

		int left, right, top, bottom;
		left = right = top = bottom = -1;

		// scanning saves about 50-60% of having to scan the entire image

		for (int i = 0; i < w; i++) {
			for (int j = 0; j < h; j++) {
				Color c = bitmap.GetPixel(i, j);
				if (c.R != 255 || c.G != 255 || c.B != 255) {
					left = i;
					break;
				}
			}
			if (left >= 0) break;
		}

		if (left == -1)
			return Rectangle.Empty;

		for (int i = w - 1; i >= 0; i--) {
			for (int j = 0; j < h; j++) {
				Color c = bitmap.GetPixel(i, j);
				if (c.R != 255 || c.G != 255 || c.B != 255) {
					right = i;
					break;
				}
			}
			if (right >= 0) break;
		}

		for (int j = 0; j < h; j++) {
			for (int i = left; i <= right; i++) {
				Color c = bitmap.GetPixel(i, j);
				if (c.R != 255 || c.G != 255 || c.B != 255) {
					top = j;
					break;
				}
			}
			if (top >= 0) break;
		}

		for (int j = h - 1; j >= 0; j--) {
			for (int i = left; i <= right; i++) {
				Color c = bitmap.GetPixel(i, j);
				if (c.R != 255 || c.G != 255 || c.B != 255) {
					bottom = j;
					break;
				}
			}
			if (bottom >= 0) break;
		}

		g2.Dispose();
		bitmap.Dispose();

		var r = new Rectangle(left, top, (right - left) + 1, (bottom - top) + 1);
		ht[mk] = r;
		return r;
	}
Ejemplo n.º 16
0
 private void eraserStripButton_Click(object sender, EventArgs e)
 {
     currentDrawMethod = DrawMethods.Eraser;
     selectTool((ToolStripButton)sender);
 }
Ejemplo n.º 17
0
 private void pensilStripButton_Click(object sender, EventArgs e)
 {
     currentDrawMethod = DrawMethods.DrawByPen;
     selectTool((ToolStripButton)sender);
 }
Ejemplo n.º 18
0
 private void starStripButton_Click(object sender, EventArgs e)
 {
     currentDrawMethod = null;
     afterMouseUp      = DrawMethods.DrawStar;
     selectTool((ToolStripButton)sender);
 }
        private void RenderCenterSegment(Graphics graphics, Image sourceImage, DrawMethod drawMethod, int leadingSize, int trailingSize, int distance, int trailerLeftPosition)
        {
            switch (drawMethod)
            {
                case DrawMethod.Stretch: // This draws the middle segment stretched to fill the area between the first and last segment.
                    ProgressBar.DrawImage(
                        graphics,
                        sourceImage,
                        new Rectangle(leadingSize, 0, distance - (leadingSize + trailingSize), this.Height),
                        new Rectangle(leadingSize, 0, sourceImage.Width - (leadingSize + trailingSize), sourceImage.Height + 1));
                    break;
                case DrawMethod.Tile: // This draws the middle segment un-stretched as many times as required to fill the area between the first and last segment.
                    {
                        Region clipRegion = graphics.Clip;
                        int tileLeft = leadingSize;
                        int tileWidth = sourceImage.Width - (leadingSize + trailingSize);

                        // By setting clip we don't have to change the size of either the source rectangle or the destination rectangle,
                        // the clip will make sure the overflow is cropped away.
                        graphics.Clip = new Region(new Rectangle(tileLeft, 0, trailerLeftPosition - tileLeft, this.Height));
                        while (tileLeft < trailerLeftPosition)
                        {
                            ProgressBar.DrawImage(
                                graphics,
                                sourceImage,
                                new Rectangle(tileLeft, 0, tileWidth, this.Height),
                                new Rectangle(leadingSize, 0, tileWidth, sourceImage.Height));

                            tileLeft += tileWidth;
                        }
                        graphics.Clip = clipRegion;
                    }
                    break;
            }
        }
Ejemplo n.º 20
0
 /// <summary>
 /// Draw sequental vertices in one call
 /// </summary>
 /// <param name="vertices">Array of vertices to draw</param>
 /// <param name="textureCoords">Array of texture coordinates for vertices</param>
 /// <param name="color">Array of colors for vertices</param>
 /// <param name="count">Numer of vertices to draw</param>
 /// <param name="method">Drawing mode</param>
 public static void DrawArray(float[] vertices, float[] textureCoords, float[] color, uint count, DrawMethod method)
 {
     renderer_draw_array(vertices, textureCoords, color, count, (uint)method);
 }
Ejemplo n.º 21
0
 public Scenario(DrawMethod method, CanvasSpriteSortMode sortMode)
 {
     Method = method;
     SortMode = sortMode;
     Reset();
 }
Ejemplo n.º 22
0
        private void button4_Click(object sender, EventArgs e)
        {
            br = new SolidBrush(panel2.BackColor);
            G.FillRectangle(br, 0, 0, B.Width, B.Height);
            float  x1    = (float)Convert.ToDouble(tbX1.Text);
            float  x2    = (float)Convert.ToDouble(tbX2.Text);
            float  bx    = 20;
            float  by    = 20;
            int    nstep = B.Width - (int)Math.Round(2 * bx);
            float  xstep = (x2 - x1) / (float)(nstep);
            PointF min   = new PointF(x1, F(x1));
            PointF max   = new PointF(min.X, min.Y);
            float  x     = x1 + xstep;

            while (x <= x2)
            {
                if (min.Y > F(x))
                {
                    min.X = x;
                    min.Y = F(x);
                }
                if (max.Y < F(x))
                {
                    max.X = x;
                    max.Y = F(x);
                }
                x += xstep;
            }
            float ycoef = ((float)B.Height - 2 * by) / (max.Y - min.Y);

            DrawMethod DrawFunc = null;

            switch (cmbMethod.SelectedIndex)
            {
            case 0:
                DrawFunc = DDA;
                break;

            case 1:
                DrawFunc = BresenhamReal;
                break;

            case 2:
                DrawFunc = BresenhamInt;
                break;

            case 3:
                DrawFunc = BresenhamSmooth;
                break;

            case 4:
                DrawFunc = Standart;
                break;
            }

            Pen pen = new Pen(LineColor);

            pen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dash;
            Point P1 = new Point((int)Math.Round(bx), B.Height - (int)Math.Round((-min.Y) * ycoef + (by)));
            Point P2 = new Point(B.Width - P1.X, P1.Y);

            G.DrawLine(pen, P1, P2);
            P1 = new Point((int)Math.Round(((float)B.Width - 2 * bx) * -x1 / (x2 - x1) + bx), (int)Math.Round(by));
            P2 = new Point(P1.X, B.Height - P1.Y);
            G.DrawLine(pen, P1, P2);

            x = x1;
            int   i  = (int)Math.Round(bx);
            Point PE = new Point();
            Point PB = new Point(i, B.Height - (int)Math.Round((F(x) - min.Y) * ycoef + (by)));

            i++;
            x += xstep;
            while (x <= x2)
            {
                PE.X = i;
                PE.Y = B.Height - (int)Math.Round((F(x) - min.Y) * ycoef + (by));
                DrawFunc(PB, PE, LineColor);
                PB.X = PE.X;
                PB.Y = PE.Y;
                x   += xstep;
                i++;
            }
            pictBox.Refresh();
        }
Ejemplo n.º 23
0
        public void Draw(SpriteBatch spriteBatch, Camera camera, DrawMethod playerDraw = null)
        {
            Point cameraPoint = VectorToCell(camera.Position * (1 / camera.Zoom));
            Point viewPoint =
                VectorToCell(new Vector2((camera.Position.X + camera.Viewport.Width) * (1 / camera.Zoom),
                                         (camera.Position.Y + camera.Viewport.Height) * (1 / camera.Zoom)));
            var min = new Point
            {
                X = Math.Max(0, cameraPoint.X - 1),
                Y = Math.Max(0, cameraPoint.Y - 1)
            };

            var destination = new Rectangle(0, 0, TileWidth, TileHeight);

            bool playerDrawn = false;

            foreach (var layer in _layers)
            {
                if (playerDraw != null && !playerDrawn && layer.Name == "player")
                {
                    playerDraw(layer.LayerDepth);
                    playerDrawn = true;
                }

                if (!layer.Visible)
                    continue;

                var tileLayer = layer as TileLayer;

                if (tileLayer == null)
                    continue;

                var max = new Point
                {
                    X = Math.Min(viewPoint.X + 1, tileLayer.Width),
                    Y = Math.Min(viewPoint.Y + 1, tileLayer.Height)
                };

                var color = new Color(1.0f, 1.0f, 1.0f, tileLayer.Opacity);

                for (int y = min.Y; y < max.Y; y++)
                {
                    for (int x = min.X; x < max.X; x++)
                    {
                        Tile tile = tileLayer.Tiles[y * tileLayer.Width + x];

                        if (tile == null)
                            continue;

                        destination.X = x * TileWidth;
                        destination.Y = y * TileHeight - tile.SourceRectangle.Height + TileHeight;
                        destination.Width = tile.SourceRectangle.Width;
                        destination.Height = tile.SourceRectangle.Height;
                        spriteBatch.Draw(
                            tile.Texture,
                            destination,
                            tile.SourceRectangle,
                            color,
                            0.0f,
                            Vector2.Zero,
                            tile.SpriteEffects,
                            layer.LayerDepth
                        );
                    }
                }
            }
        }
Ejemplo n.º 24
0
        /// <summary>
        /// 次の描画方法に変更します。
        /// </summary>
        void MoveToNextTechnique()
        {
            drawMethod = (DrawMethod) (drawMethod + 1);
            if (drawMethod == DrawMethod.MaxCount) drawMethod = 0;

            UpdateStatusString();
        }
Ejemplo n.º 25
0
        public VolumetricRendererGame()
        {
            Debug.OnAssert += new EventHandler<DebugEventArgs>(HandleAssert);
            //Debug.BlockAfterAssert = true;

            // Set up and run initial threads.
            //mainThread = Thread.CurrentThread;
            //mainThread.Name = "Main";

            //updateLock = new object();
            //updateThread = new Thread(new ThreadStart(UpdateThread));
            //updateThread.Name = "Update";
            //updateThread.IsBackground = true;
            //updateThread.Start();

            //drawLock = new object();
            //drawThread = new Thread(new ThreadStart(DrawThread));
            //drawThread.Name = "Draw";
            //drawThread.IsBackground = true;
            //drawThread.Start();

            // Set up the game.
            updateMethod = Update_Normal;
            drawMethod = Draw_Normal;
            assertHandled = false;

            Content.RootDirectory = "Content";

            graphicsDM = new GraphicsDeviceManager(this);
            graphicsDM.PreferredBackBufferWidth = 1280;
            graphicsDM.PreferredBackBufferHeight = 960;
            graphicsDM.PreferMultiSampling = false;
            graphicsDM.SynchronizeWithVerticalRetrace = false;
            graphicsDM.IsFullScreen = false;

            input = new InputState();
            screenManager = new ScreenManager(this, input);
            Components.Add(screenManager);

            IsMouseVisible = true;
        }
        // returns a rectangle because it's possible that the top,left are outside of the 0,0 requested position.
        public static Bitmap CreateIcon(String text, Font font, Color?foreColor = null, DrawMethod drawMethod = DrawMethod.Graphics, bool antialias = true)
        {
            if (String.IsNullOrEmpty(text))
            {
                return(new Bitmap(1, 1));
            }

            if (foreColor == null)
            {
                foreColor = Color.Black;
            }

            Bitmap   bm       = new Bitmap(1, 1);
            Graphics graphics = Graphics.FromImage(bm);

            graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
            Size size = (drawMethod == DrawMethod.Graphics ? graphics.MeasureString(text, font).ToSize() : TextRenderer.MeasureText(text, font));
            int  w    = size.Width;
            int  h    = size.Height;

            if (w == 0 || h == 0)
            {
                return(new Bitmap(1, 1));
            }
            Bitmap bitmap = new Bitmap(w, h, graphics);

            bm.Dispose();

            Graphics g2 = Graphics.FromImage(bitmap);

            if (antialias)
            {
                g2.TextRenderingHint = graphics.TextRenderingHint;
            }
            if (drawMethod == DrawMethod.Graphics)
            {
                using (var b = new SolidBrush(foreColor.Value))
                    g2.DrawString(text, font, b, 0, 0);
            }
            else
            {
                TextRenderer.DrawText(g2, text, font, new Point(0, 0), foreColor.Value, Color.White);
            }

            int left, right, top, bottom;

            left = right = top = bottom = -1;

            // scanning saves about 50-60% of having to scan the entire image

            for (int i = 0; i < w; i++)
            {
                for (int j = 0; j < h; j++)
                {
                    Color c = bitmap.GetPixel(i, j);
                    if (c.A != 0 || c.R != 0 || c.G != 0 || c.B != 0)
                    {
                        left = i;
                        break;
                    }
                }
                if (left >= 0)
                {
                    break;
                }
            }

            if (left == -1)
            {
                return(new Bitmap(1, 1));
            }

            for (int i = w - 1; i >= 0; i--)
            {
                for (int j = 0; j < h; j++)
                {
                    Color c = bitmap.GetPixel(i, j);
                    if (c.A != 0 || c.R != 0 || c.G != 0 || c.B != 0)
                    {
                        right = i;
                        break;
                    }
                }
                if (right >= 0)
                {
                    break;
                }
            }

            for (int j = 0; j < h; j++)
            {
                for (int i = left; i <= right; i++)
                {
                    Color c = bitmap.GetPixel(i, j);
                    if (c.A != 0 || c.R != 0 || c.G != 0 || c.B != 0)
                    {
                        top = j;
                        break;
                    }
                }
                if (top >= 0)
                {
                    break;
                }
            }

            for (int j = h - 1; j >= 0; j--)
            {
                for (int i = left; i <= right; i++)
                {
                    Color c = bitmap.GetPixel(i, j);
                    if (c.A != 0 || c.R != 0 || c.G != 0 || c.B != 0)
                    {
                        bottom = j;
                        break;
                    }
                }
                if (bottom >= 0)
                {
                    break;
                }
            }

            var r = new Rectangle(left, top, (right - left) + 1, (bottom - top) + 1);
            //g2.DrawRectangle(Pens.Red, r.X, r.Y, r.Width - 1, r.Height - 1);
            Bitmap b2 = bitmap.Clone(r, bitmap.PixelFormat);

            bitmap.Dispose();
            graphics.Dispose();
            g2.Dispose();
            return(b2);
        }
Ejemplo n.º 27
0
    /**
     * Draws a texture with given parameter
     *
     * @param uvFrame frame for UVs in texels.
     */
    private static void DrawMaster(Rect screenRect, Texture texture, Rect uvFrame, DrawParameters dp, RectOffset origionalBorder = null)
    {
        //3ms for these 4 lines
        if (!isRepaint)
        {
            return;
        }
        if (texture == null)
        {
            return;
        }
        if (!dp.IsVisibile(texture))
        {
            return;
        }
        if (dp.Scale.x * dp.Scale.y == 0)
        {
            return;
        }

        screenRect.width  *= dp.Scale.x;
        screenRect.height *= dp.Scale.y;

        Material material = dp.GetPreparedMaterial(texture);

        // --------------------------------------
        // Transform and clip.

        Vector4 clipping = Vector4.zero;

        Rect transformedRect = TransformTheRect(screenRect);
        Rect clippedRect     = transformedRect;
        Rect sourceRect      = new Rect(uvFrame);

        int borderLeft   = origionalBorder == null ? 0 : origionalBorder.left;
        int borderRight  = origionalBorder == null ? 0 : origionalBorder.right;
        int borderTop    = origionalBorder == null ? 0 : origionalBorder.top;
        int borderBottom = origionalBorder == null ? 0 : origionalBorder.bottom;

        // No clipping for rotated sprites yet.
        bool disableClip = dp.Rotation != 0;

        if (!disableClip)
        {
            clippedRect = ClipTheRect(transformedRect, ref clipping);
            bool hasClipped = (clipping != Vector4.zero);

            //stub:

            /*
             * if (hasClipped) {
             *      SmartUI.Color = Color.red;
             *      if (screenRect.Contains(new Vector2(InputEx.mousePosition.x, InputEx.mousePosition.y)))
             *              Trace.LogDebug("Clipped {0} to {1}", transformedRect, clippedRect);
             * } else
             *      SmartUI.Color = Color.green;
             */

            if ((clippedRect.width <= 0) || (clippedRect.height <= 0))
            {
                return;
            }

            if (hasClipped)
            {
                // Calculate clipped UVs.
                sourceRect     = new Rect();
                sourceRect.min = PixelToUV(transformedRect, uvFrame, clippedRect.min, origionalBorder);
                sourceRect.max = PixelToUV(transformedRect, uvFrame, clippedRect.max, origionalBorder);

                // Upside down swap.  This has something todo with the fact that the screen has (0,0) at the top left
                // and the texture has (0,0) at the bottom left.
                float newMin = uvFrame.yMin + (uvFrame.yMax - sourceRect.yMax);
                float newMax = uvFrame.yMax + (uvFrame.yMin - sourceRect.yMin);
                sourceRect.yMin = newMin;
                sourceRect.yMax = newMax;


                // Adjust border for clipping.
                if (origionalBorder != null)
                {
                    clipping[0] /= dp.Scale.x;
                    clipping[2] /= dp.Scale.x;
                    clipping[1] /= dp.Scale.y;
                    clipping[3] /= dp.Scale.y;

                    borderLeft  = Util.ClampInt(borderLeft - (int)clipping[0], 0, int.MaxValue);
                    borderRight = Util.ClampInt(borderRight - (int)clipping[2], 0, int.MaxValue);

                    borderTop    = Util.ClampInt(borderTop - (int)clipping[1], 0, int.MaxValue);
                    borderBottom = Util.ClampInt(borderBottom - (int)clipping[3], 0, int.MaxValue);
                }
            }
        }

        // Convert source rect to normalised.
        sourceRect.xMin *= texture.texelSize.x;
        sourceRect.xMax *= texture.texelSize.x;
        sourceRect.yMin *= texture.texelSize.y;
        sourceRect.yMax *= texture.texelSize.y;

        // Work out the best way to draw this.
        DrawMethod drawMethod = DrawMethod.Standard;

        if (origionalBorder != null)
        {
            drawMethod = DrawMethod.Bordered;
        }

        if ((origionalBorder != null) && (texture.HighDPI()))
        {
            drawMethod = DrawMethod.Native;
        }

        if (ShowGuiMaterial && !dp.IsDebugDraw)
        {
            drawMethod = DrawMethod.DebugColor;
        }

        // Apply rotation
        if (dp.Rotation != 0)
        {
            Engine.PushGUI();
            var rotationMatrix =
                Extentions.GetTranslationMatrix(clippedRect.center.x, clippedRect.center.y, 0) *
                Extentions.GetRotationMatrix(0, 0, dp.Rotation) *
                Extentions.GetTranslationMatrix(-clippedRect.center.x, -clippedRect.center.y, 0);

            GUI.matrix *= rotationMatrix;
        }

        // Draw the thing.
        switch (drawMethod)
        {
        case DrawMethod.DebugColor:
            Color = dp.DebugColor;
            DrawMaster(screenRect, StockTexture.White, new Rect(0, 0, 2, 2), DrawParameters.DebugDraw);
            break;

        case DrawMethod.Standard:
            Graphics.DrawTexture(clippedRect, texture, sourceRect, 0, 0, 0, 0, SmartUI.Color, material);
            break;

        case DrawMethod.Bordered:
            Graphics.DrawTexture(clippedRect, texture, sourceRect, borderLeft, borderRight, borderTop, borderBottom, SmartUI.Color, material);
            break;

        // The native draw will reverse the DPI scaling on the Gui matrix and then draw the object at an adjusted size.
        // This allows things like bordered gui objects to display correctly without distortion.

        case DrawMethod.Native:
            const float scale = 2;
            Engine.PushGUI();
            GUI.matrix *= Matrix4x4.Scale(Vector3.one / scale);
            clippedRect = clippedRect.Scaled(scale);
            Graphics.DrawTexture(clippedRect, texture, sourceRect, (int)(borderLeft * scale), (int)(borderRight * scale), (int)(borderTop * scale), (int)(borderBottom * scale), SmartUI.Color, material);
            Engine.PopGUI();
            break;
        }

        if (ShowGuiBounds && !dp.IsDebugDraw)
        {
            Color = Color.red;
            DrawMaster(screenRect, StockTexture.SimpleRect, new Rect(0, 0, 4, 4), DrawParameters.DebugDraw, BORDER_2PX);
        }

        if (dp.Rotation != 0)
        {
            Engine.PopGUI();
        }

        Color = Color.white;
    }
        // returns a rectangle because it's possible that the top,left are outside of the 0,0 requested position.
        public static Rectangle Measure(String text, Graphics graphics, Font font, DrawMethod drawMethod = DrawMethod.Graphics, TextFormatFlags textFormatFlags = TextFormatFlags.Default, Rectangle?rect = null)
        {
            if (String.IsNullOrEmpty(text))
            {
                return(Rectangle.Empty);
            }


            MultiKey mk = new MultiKey(text, graphics.TextRenderingHint, font, drawMethod, textFormatFlags, rect);
            //if (drawMethod == DrawMethod.Graphics)
            //	mk = new MultiKey(text, graphics.TextRenderingHint, font, drawMethod);
            //else {
            //	mk = new

            Object o = ht[mk];

            if (o != null)
            {
                return((Rectangle)o);
            }

            Size size = Size.Empty;

            if (rect.HasValue)
            {
                var r2 = rect.Value;
                size        = r2.Size;
                r2.Location = Point.Empty;
                rect        = r2;
            }
            else
            {
                size = (drawMethod == DrawMethod.Graphics ? graphics.MeasureString(text, font).ToSize() : TextRenderer.MeasureText(graphics, text, font, Size.Empty, textFormatFlags));
            }

            int w = size.Width;
            int h = size.Height;

            if (w == 0 || h == 0)
            {
                return(Rectangle.Empty);
            }
            Bitmap bitmap = new Bitmap(w, h, graphics);

            Graphics g2 = Graphics.FromImage(bitmap);

            g2.TextRenderingHint = graphics.TextRenderingHint;
            g2.SmoothingMode     = graphics.SmoothingMode;
            g2.Clear(Color.White);
            if (drawMethod == DrawMethod.Graphics)
            {
                g2.DrawString(text, font, Brushes.Black, 0, 0);
            }
            else
            {
                // always specify a bounding rectangle. Otherwise if flags contains VerticalCenter it will be half cutoff above point (0,0)
                Rectangle r2 = (rect.HasValue ? rect.Value : new Rectangle(Point.Empty, size));
                TextRenderer.DrawText(g2, text, font, r2, Color.Black, Color.White, textFormatFlags);
            }

            int left, right, top, bottom;

            left = right = top = bottom = -1;

            // scanning saves about 50-60% of having to scan the entire image

            for (int i = 0; i < w; i++)
            {
                for (int j = 0; j < h; j++)
                {
                    Color c = bitmap.GetPixel(i, j);
                    if (c.R != 255 || c.G != 255 || c.B != 255)
                    {
                        left = i;
                        break;
                    }
                }
                if (left >= 0)
                {
                    break;
                }
            }

            if (left == -1)
            {
                return(Rectangle.Empty);
            }

            for (int i = w - 1; i >= 0; i--)
            {
                for (int j = 0; j < h; j++)
                {
                    Color c = bitmap.GetPixel(i, j);
                    if (c.R != 255 || c.G != 255 || c.B != 255)
                    {
                        right = i;
                        break;
                    }
                }
                if (right >= 0)
                {
                    break;
                }
            }

            for (int j = 0; j < h; j++)
            {
                for (int i = left; i <= right; i++)
                {
                    Color c = bitmap.GetPixel(i, j);
                    if (c.R != 255 || c.G != 255 || c.B != 255)
                    {
                        top = j;
                        break;
                    }
                }
                if (top >= 0)
                {
                    break;
                }
            }

            for (int j = h - 1; j >= 0; j--)
            {
                for (int i = left; i <= right; i++)
                {
                    Color c = bitmap.GetPixel(i, j);
                    if (c.R != 255 || c.G != 255 || c.B != 255)
                    {
                        bottom = j;
                        break;
                    }
                }
                if (bottom >= 0)
                {
                    break;
                }
            }

            g2.Dispose();
            bitmap.Dispose();

            var r = new Rectangle(left, top, (right - left) + 1, (bottom - top) + 1);

            ht[mk] = r;
            return(r);
        }
        public static Bitmap DrawTextToBitmap(string text, Font font, Color color, DrawMethod mode, RectangleF rectanglef)
        {
            StringFormat drawFormat = new StringFormat();
            Bitmap       bmp;

            switch (mode)
            {
            case DrawMethod.AutosizeAccordingToText:
            {
                Size size = MeasureDrawTextBitmapSize(text, font);

                if (size.Width == 0 || size.Height == 0)
                {
                    bmp = new Bitmap(1, 1);
                }
                else
                {
                    bmp = new Bitmap(size.Width, size.Height);
                }

                using (Graphics g = Graphics.FromImage(bmp))
                {
                    SetGraphicsHighQualityForTextRendering(g);

                    g.DrawString(text, font, new SolidBrush(color), 0, 0);

                    return(bmp);
                }
            }

            case DrawMethod.AutoWarpInConstantRectangle:
            {
                Rectangle rect = Rectangle.Ceiling(rectanglef);
                bmp = new Bitmap(rect.Width, rect.Height);

                if (rect.Width == 0 || rect.Height == 0)
                {
                    bmp = new Bitmap(1, 1);
                }
                else
                {
                    bmp = new Bitmap(rect.Width, rect.Height);
                }

                using (Graphics g = Graphics.FromImage(bmp))
                {
                    SetGraphicsHighQualityForTextRendering(g);

                    g.DrawString(text, font, new SolidBrush(color), rectanglef, drawFormat);

                    return(bmp);
                }
            }

            case DrawMethod.AutoFitInConstantRectangleWithoutWarp:
            {
                Rectangle rect = Rectangle.Ceiling(rectanglef);

                bmp = new Bitmap(rect.Width, rect.Height);

                if (rect.Width == 0 || rect.Height == 0)
                {
                    bmp = new Bitmap(1, 1);
                }
                else
                {
                    bmp = new Bitmap(rect.Width, rect.Height);
                }

                using (Graphics g = Graphics.FromImage(bmp))
                {
                    int fontSize = GetMaximumFontSizeFitInRectangle(text, font, rectanglef, false);

                    SetGraphicsHighQualityForTextRendering(g);

                    g.DrawString(text, new Font(font.FontFamily, fontSize, font.Style, GraphicsUnit.Point), new SolidBrush(color), rectanglef, drawFormat);


                    return(bmp);
                }
            }

            case DrawMethod.AutoFitInConstantRectangleWithWarp:
            {
                Rectangle rect = Rectangle.Ceiling(rectanglef);

                if (rect.Width == 0 || rect.Height == 0)
                {
                    bmp = new Bitmap(1, 1);
                }
                else
                {
                    bmp = new Bitmap(rect.Width, rect.Height);
                }

                using (Graphics g = Graphics.FromImage(bmp))
                {
                    int fontSize = GetMaximumFontSizeFitInRectangle(text, font, rectanglef, true);

                    SetGraphicsHighQualityForTextRendering(g);

                    g.DrawString(text, new Font(font.FontFamily, fontSize, font.Style, GraphicsUnit.Point), new SolidBrush(color), rectanglef, drawFormat);


                    return(bmp);
                }
            }
            }
            return(null);
        }
 public Scenario(DrawMethod method, CanvasSpriteSortMode sortMode)
 {
     Method   = method;
     SortMode = sortMode;
     Reset();
 }
Ejemplo n.º 31
0
        /// <summary>
        /// Event handler for an assert.
        /// </summary>
        /// <param name="sender">Because Debug is a static class, this is always NULL.</param>
        /// <param name="args">Info about the assert.</param>
        private void HandleAssert(object sender, DebugEventArgs args)
        {
            updateMethod = Update_Assert;
            drawMethod = Draw_Assert;

            // This method is running on the thread that asserted, so start a new thread for the
            // handler so it can kill off all the worker threads without killing itself.
            //handleAssertThread = new Thread(new ParameterizedThreadStart(HandleAssertThread));
            //handleAssertThread.Name = "HandleAssert";
            //handleAssertThread.IsBackground = true;
            //handleAssertThread.Start(args);
            HandleAssertThread(args);
        }
        protected void Render(Graphics graphics, Image sourceImage, DrawMethod drawMethod, int leadingSize, int trailingSize, int distance)
        {
            // If we don't have an image to render just bug out, this allows us to call Render without checking sourceImage first.
            if (sourceImage == null)
                return;

            //
            // Draw the first segment of the image as defined by leadingSize, this is always drawn at (0, 0).
            // 
            ProgressBar.DrawImage(
                graphics,
                sourceImage,
                new Rectangle(0, 0, leadingSize, this.Height),
                new Rectangle(0, 0, leadingSize, sourceImage.Height + 1));

            //
            // Figure out where the last segment of the image should be drawn, this is always to the right of the first segment 
            // and then at the given distance minus the width of the last segment.
            //
            int trailerLeftPosition = Math.Max(leadingSize, distance - trailingSize);

            ProgressBar.DrawImage(
                graphics,
                sourceImage,
                new Rectangle(trailerLeftPosition, 0, trailingSize, this.Height),
                new Rectangle(sourceImage.Width - trailingSize, 0, trailingSize, sourceImage.Height + 1));


            //
            // We only draw the middle segment if the width of the first and last are less than what we need to display.
            //
            if (distance > leadingSize + trailingSize)
            {
                RenderCenterSegment(graphics, sourceImage, drawMethod, leadingSize, trailingSize, distance, trailerLeftPosition);
            }
        }