System.Drawing.Graphics.DrawString(string, System.Drawing.Font, System.Drawing.Brush, System.Drawing.RectangleF, System.Drawing.StringFormat)

Here are the examples of the csharp api System.Drawing.Graphics.DrawString(string, System.Drawing.Font, System.Drawing.Brush, System.Drawing.RectangleF, System.Drawing.StringFormat) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

901 Examples 7

19 View Source File : FProgressBar.cs
License : MIT License
Project Creator : 0xLaileb

private void Draw_Text(Graphics graphics)
        {
            graphics.DrawString(
                ((Value / (Maximum / 100))).ToString() + "%",
                Font,
                new SolidBrush(ForeColor),
                new Rectangle(rectangle_region.X, rectangle_region.Y, rectangle_region.Width, rectangle_region.Height),
                stringFormat);
        }

19 View Source File : FButton.cs
License : MIT License
Project Creator : 0xLaileb

private void Draw_Text(Graphics graphics)
        {
            graphics.DrawString(
                TextButton,
                Font,
                new SolidBrush(ForeColor),
                new Rectangle(rectangle_region.X, rectangle_region.Y, rectangle_region.Width, rectangle_region.Height),
                stringFormat);
        }

19 View Source File : GraphicsManager.cs
License : GNU General Public License v3.0
Project Creator : aglab2

public void DrawIntro(bool isEmulatorLoaded, bool isHackLoaded, bool isOffsetsInitialized)
        {
            Font drawFont = new Font(FontFamily, BigFontSize);
            SolidBrush whiteBrush = new SolidBrush(Color.White);
            SolidBrush greenBrush = new SolidBrush(Color.Green);

            RectangleF drawRect = new RectangleF(0, 0, Width, SHeight * (float)2.5);
            StringFormat drawFormat = new StringFormat
            {
                Alignment = StringAlignment.Center,
                LineAlignment = StringAlignment.Center
            };
            graphics.DrawString("Welcome to Star Display!", drawFont, whiteBrush, new RectangleF(0, 0, Width, SHeight * (float)2.5), drawFormat);

            bool success = isEmulatorLoaded && isHackLoaded && isOffsetsInitialized;

            drawFormat.Alignment = StringAlignment.Near;
            graphics.DrawString("1) Run Emulator", drawFont, isEmulatorLoaded ? greenBrush : whiteBrush, new RectangleF(SWidth, SHeight * 3, Width - SWidth, SHeight * 2), drawFormat);
            graphics.DrawString("2) Load your hack", drawFont, isHackLoaded ? greenBrush : whiteBrush, new RectangleF(SWidth, SHeight * 6, Width - SWidth, SHeight * 2), drawFormat);
            graphics.DrawString("3) Let Star Display init", drawFont, isOffsetsInitialized ? greenBrush : whiteBrush, new RectangleF(SWidth, SHeight * 9, Width - SWidth, SHeight * 2), drawFormat);
            graphics.DrawString("4) Enjoy!", drawFont, success ? greenBrush : whiteBrush, new RectangleF(SWidth, SHeight * 12, Width - SWidth, SHeight * 2), drawFormat);

        }

19 View Source File : GraphicsManager.cs
License : GNU General Public License v3.0
Project Creator : aglab2

public static void DrawStringWithOutline(this Graphics g, string s, FontFamily fontFamily, float fontSize, Brush brush, Pen pen, RectangleF drawRect, StringFormat format)
        {
            g.SmoothingMode = SmoothingMode.HighQuality;
            GraphicsPath path = new GraphicsPath();
            path.AddString(s, fontFamily, (int)FontStyle.Regular, g.DpiY * fontSize / 72, drawRect, format);
            g.DrawPath(new Pen(Color.Black, 3) { LineJoin = LineJoin.Round }, path);
            Font font = new Font(fontFamily, fontSize);
            g.DrawString(s, font, brush, drawRect, format);
        }

19 View Source File : Map.cs
License : GNU General Public License v3.0
Project Creator : AHeroicLlama

public static void Draw()
		{
			// Reset the current image to the background layer
			finalImage = (Image)backgroundLayer.Clone();

			Graphics imageGraphic = Graphics.FromImage(finalImage);
			imageGraphic.SmoothingMode = SmoothingMode.AntiAlias;
			Font font = new Font(fontCollection.Families[0], fontSize, GraphicsUnit.Pixel);

			CellScaling cellScaling = null;

			// Prepare the game version and watermark to be printed later
			string infoText = (SettingsPlot.IsTopographic() ? "Topographic View\n" : string.Empty) + "Game version " + IOManager.GetGameVersion() + "\nMade with Mappalachia - github.com/AHeroicLlama/Mappalachia";

			// Additional steps for cell mode (Add further text to watermark text, get cell height boundings)
			if (SettingsMap.IsCellModeActive())
			{
				Cell currentCell = SettingsCell.GetCell();

				// replacedign the CellScaling property
				cellScaling = currentCell.GetScaling();

				infoText =
					currentCell.displayName + " (" + currentCell.editorID + ")\n" +
					"Height distribution: " + SettingsCell.minHeightPerc + "% - " + SettingsCell.maxHeightPerc + "%\n" +
					"Scale: 1:" + Math.Round(cellScaling.scale, 2) + "\n\n" +
					infoText;
			}

			// Gather resources for drawing informational watermark text
			Brush brushWhite = new SolidBrush(Color.White);
			RectangleF infoTextBounds = new RectangleF(plotXMin, 0, mapDimension - plotXMin, mapDimension);
			StringFormat stringFormatBottomRight = new StringFormat() { Alignment = StringAlignment.Far, LineAlignment = StringAlignment.Far }; // Align the text bottom-right
			StringFormat stringFormatBottomLeft = new StringFormat() { Alignment = StringAlignment.Near, LineAlignment = StringAlignment.Far }; // Align the text bottom-left

			// Draws bottom-right info text
			imageGraphic.DrawString(infoText, font, brushWhite, infoTextBounds, stringFormatBottomRight);

			// Draw a height-color key for Topography mode
			if (SettingsPlot.IsTopographic())
			{
				// Identify the sizing and locations for drawing the height-color-key strings
				double numHeightKeys = SettingsPlotTopograph.heightKeyIndicators;
				Font topographFont = new Font(fontCollection.Families[0], 62, GraphicsUnit.Pixel);
				float singleLineHeight = imageGraphic.MeasureString(SettingsPlotTopograph.heightKeyString, topographFont, new SizeF(infoTextBounds.Width, infoTextBounds.Height)).Height;

				// Identify the lower limit to start printing the key so that it ends up centered
				double baseHeight = (mapDimension / 2) - (singleLineHeight * (numHeightKeys / 2d));

				for (int i = 0; i <= numHeightKeys - 1; i++)
				{
					Brush brush = new SolidBrush(GetTopographColor(i / (numHeightKeys - 1)));
					imageGraphic.DrawString(SettingsPlotTopograph.heightKeyString, topographFont, brush, new RectangleF(plotXMax, 0, mapDimension - plotXMax, (float)(mapDimension - baseHeight)), stringFormatBottomRight);
					baseHeight += singleLineHeight;
				}
			}

			// Draw all legend text for every MapItem
			int skippedLegends = DrawLegend(font, imageGraphic);

			// Adds additional text if some items were missed from legend
			if (skippedLegends > 0)
			{
				string extraLegendText = "+" + skippedLegends + " more item" + (skippedLegends == 1 ? string.Empty : "s") + "...";
				imageGraphic.DrawString(extraLegendText, font, brushWhite, infoTextBounds, stringFormatBottomLeft);
			}

			// Start progress bar off at 0
			progressBarMain.Value = progressBarMain.Minimum;
			float progress = 0;

			// Nothing else to plot - ensure we update for the background layer but then return
			if (FormMaster.legendItems.Count == 0)
			{
				mapFrame.Image = finalImage;
				return;
			}

			// Count how many Map Data Points are due to be mapped
			int totalMapDataPoints = 0;
			foreach (MapItem mapItem in FormMaster.legendItems)
			{
				totalMapDataPoints += mapItem.count;
			}

			// Loop through every MapDataPoint represented by all the MapItems to find the min/max z coord in the dataset
			bool first = true;
			int zMin = 0;
			int zMax = 0;
			double zRange = 0;
			if (SettingsPlot.IsTopographic())
			{
				foreach (MapItem mapItem in FormMaster.legendItems)
				{
					foreach (MapDataPoint point in mapItem.GetPlots())
					{
						if (first)
						{
							zMin = point.z - (point.boundZ / 2);
							zMax = point.z + (point.boundZ / 2);
							first = false;
							continue;
						}

						// Do not contribute outlier values to the min/max range - this ensures they have the same
						// color as the min/max *legitimate* item and they do not skew the color ranges
						if (point.z > SettingsPlotTopograph.zThreshUpper || point.z < SettingsPlotTopograph.zThreshLower)
						{
							continue;
						}

						if (point.z - (point.boundZ / 2) < zMin)
						{
							zMin = point.z - (point.boundZ / 2);
						}

						if (point.z + (point.boundZ / 2) > zMax)
						{
							zMax = point.z + (point.boundZ / 2);
						}
					}
				}

				zRange = Math.Abs(zMax - zMin);

				if (zRange == 0)
				{
					zRange = 1;
				}
			}

			if (SettingsPlot.IsIconOrTopographic())
			{
				if (SettingsPlot.IsTopographic())
				{
					// Somehow this line prevents a memory leak
					// Without it, if drawing a large topographic map on first map draw, GC will not collect the multiple PlotIcon elements used in topographic drawing.
					Application.DoEvents();
				}

				// Processing each MapItem in serial, draw plots for every matching valid MapDataPoint
				foreach (MapItem mapItem in FormMaster.legendItems)
				{
					// Generate a Plot Icon and colours/brushes to be used for all instances of the MapItem
					PlotIcon plotIcon = mapItem.GetIcon();
					Image plotIconImg = SettingsPlot.IsIcon() ? plotIcon.GetIconImage() : null; // Icon mode has icon per MapItem, Topography needs icons per MapDataPoint and will be generated later
					Color volumeColor = Color.FromArgb(volumeOpacity, plotIcon.color);
					Brush volumeBrush = new SolidBrush(volumeColor);

					// Iterate over every data point and draw it
					foreach (MapDataPoint point in mapItem.GetPlots())
					{
						// Override colors in Topographic mode
						if (SettingsPlot.IsTopographic())
						{
							// Clamp the z values to the percieved outlier threshold
							double z = point.z + (point.boundZ / 2);
							z = Math.Max(Math.Min(z, SettingsPlotTopograph.zThreshUpper), SettingsPlotTopograph.zThreshLower);

							// Normalize the height of this item between the min/max z of the whole set
							double colorValue = (z - zMin) / zRange;

							// Override the plot icon color
							plotIcon.color = GetTopographColor(colorValue);
							plotIconImg = plotIcon.GetIconImage(); // Generate a new icon with a unique color for this height color

							// Apply the color to volume plotting too
							volumeColor = Color.FromArgb(volumeOpacity, plotIcon.color);
							volumeBrush = new SolidBrush(volumeColor);
						}

						if (SettingsMap.IsCellModeActive())
						{
							// If this coordinate exceeds the user-selected cell mapping height bounds, skip it
							// (Also accounts for the z-height of volumes)
							if (point.z + (point.boundZ / 2d) < SettingsCell.GetMinHeightCoordBound() || point.z - (point.boundZ / 2d) > SettingsCell.GetMaxHeightCoordBound())
							{
								continue;
							}

							point.x += cellScaling.xOffset;
							point.y += cellScaling.yOffset;

							// Multiply the coordinates by the scaling, but multiply around 0,0
							point.x = ((point.x - (mapDimension / 2)) * cellScaling.scale) + (mapDimension / 2);
							point.y = ((point.y - (mapDimension / 2)) * cellScaling.scale) + (mapDimension / 2);
							point.boundX *= cellScaling.scale;
							point.boundY *= cellScaling.scale;
						}
						else // Skip the point if its origin is outside the surface world
						if (point.x < plotXMin || point.x >= plotXMax || point.y < plotYMin || point.y >= plotYMax)
						{
							continue;
						}

						// If this meets all the criteria to be suitable to be drawn as a volume
						if (point.primitiveShape != string.Empty && // This is a primitive shape at all
							SettingsPlot.drawVolumes && // Volume drawing is enabled
							point.boundX >= minVolumeDimension && point.boundY >= minVolumeDimension) // This is large enough to be visible if drawn as a volume
						{
							Image volumeImage = new Bitmap((int)point.boundX, (int)point.boundY);
							Graphics volumeGraphic = Graphics.FromImage(volumeImage);
							volumeGraphic.SmoothingMode = SmoothingMode.AntiAlias;

							switch (point.primitiveShape)
							{
								case "Box":
								case "Line":
								case "Plane":
									volumeGraphic.FillRectangle(volumeBrush, new Rectangle(0, 0, (int)point.boundX, (int)point.boundY));
									break;
								case "Sphere":
								case "Ellipsoid":
									volumeGraphic.FillEllipse(volumeBrush, new Rectangle(0, 0, (int)point.boundX, (int)point.boundY));
									break;
								default:
									continue; // If we reach this, we dropped the drawing of a volume. Verify we've covered all shapes via the database summary.txt
							}

							volumeImage = ImageTools.RotateImage(volumeImage, point.rotationZ);
							imageGraphic.DrawImage(volumeImage, (float)(point.x - (volumeImage.Width / 2)), (float)(point.y - (volumeImage.Height / 2)));
						}

						// This MapDataPoint is not suitable to be drawn as a volume - draw a normal plot icon, or topographic plot
						else
						{
							imageGraphic.DrawImage(plotIconImg, (float)(point.x - (plotIconImg.Width / 2d)), (float)(point.y - (plotIconImg.Height / 2d)));
						}
					}

					// Increment the progress bar per MapItem
					progress += mapItem.count;
					progressBarMain.Value = (int)((progress / totalMapDataPoints) * progressBarMain.Maximum);
					Application.DoEvents();
				}
			}
			else if (SettingsPlot.IsHeatmap())
			{
				int resolution = SettingsPlotHeatmap.resolution;
				int blendRange = SettingsPlotHeatmap.blendDistance;

				// Create a 2D Array of HeatMapGridSquare
				HeatMapGridSquare[,] squares = new HeatMapGridSquare[resolution, resolution];
				for (int x = 0; x < resolution; x++)
				{
					for (int y = 0; y < resolution; y++)
					{
						squares[x, y] = new HeatMapGridSquare();
					}
				}

				int pixelsPerSquare = mapDimension / resolution;

				foreach (MapItem mapItem in FormMaster.legendItems)
				{
					int heatmapLegendGroup = SettingsPlotHeatmap.IsDuo() ? mapItem.legendGroup % 2 : 0;

					foreach (MapDataPoint point in mapItem.GetPlots())
					{
						if (SettingsMap.IsCellModeActive())
						{
							point.x += cellScaling.xOffset;
							point.y += cellScaling.yOffset;

							point.x = ((point.x - (mapDimension / 2)) * cellScaling.scale) + (mapDimension / 2);
							point.y = ((point.y - (mapDimension / 2)) * cellScaling.scale) + (mapDimension / 2);
						}

						// Identify which grid square this MapDataPoint falls within
						int squareX = (int)Math.Floor(point.x / pixelsPerSquare);
						int squareY = (int)Math.Floor(point.y / pixelsPerSquare);

						// Loop over every grid square within range, and increment by the weight proportional to the distance
						for (int x = squareX - blendRange; x < squareX + blendRange; x++)
						{
							for (int y = squareY - blendRange; y < squareY + blendRange; y++)
							{
								// Don't try to target squares which would lay outside of the grid
								if (x < 0 || x >= resolution || y < 0 || y >= resolution)
								{
									continue;
								}

								// Pythagoras on the x and y dist gives us the 'as the crow flies' distance between the squares
								double distance = Pythagoras(squareX - x, squareY - y);

								// Weight and hence brightness is modified by 1/x^2 + 1 where x is the distance from actual item
								double additionalWeight = point.weight * (1d / ((distance * distance) + 1));
								squares[x, y].weights[heatmapLegendGroup] += additionalWeight;
							}
						}
					}

					// Increment the progress bar per MapItem
					progress += mapItem.count;
					progressBarMain.Value = (int)((progress / totalMapDataPoints) * progressBarMain.Maximum);
					Application.DoEvents();
				}

				// Find the largest weight value of all squares
				double largestWeight = 0;
				for (int x = 0; x < resolution; x++)
				{
					for (int y = 0; y < resolution; y++)
					{
						double weight = squares[x, y].GetTotalWeight();
						if (weight > largestWeight)
						{
							largestWeight = weight;
						}
					}
				}

				// Finally now weights are calculated, draw a square for every HeatGripMapSquare in the array
				for (int x = 0; x < resolution; x++)
				{
					int xCoord = x * pixelsPerSquare;

					// Don't draw grid squares which are entirely within the legend text area
					if (xCoord + pixelsPerSquare < plotXMin)
					{
						continue;
					}

					for (int y = 0; y < resolution; y++)
					{
						int yCoord = y * pixelsPerSquare;

						Color color = squares[x, y].GetColor(largestWeight);
						Brush brush = new SolidBrush(color);

						Rectangle heatMapSquare = new Rectangle(xCoord, yCoord, mapDimension / SettingsPlotHeatmap.resolution, mapDimension / SettingsPlotHeatmap.resolution);
						imageGraphic.FillRectangle(brush, heatMapSquare);
					}
				}
			}

			mapFrame.Image = finalImage;
		}

19 View Source File : Map.cs
License : GNU General Public License v3.0
Project Creator : AHeroicLlama

public static void Draw()
		{
			// Reset the current image to the background layer
			finalImage = (Image)backgroundLayer.Clone();

			Graphics imageGraphic = Graphics.FromImage(finalImage);
			imageGraphic.SmoothingMode = SmoothingMode.AntiAlias;
			Font font = new Font(fontCollection.Families[0], fontSize, GraphicsUnit.Pixel);

			CellScaling cellScaling = null;

			// Prepare the game version and watermark to be printed later
			string infoText = (SettingsPlot.IsTopographic() ? "Topographic View\n" : string.Empty) + "Game version " + IOManager.GetGameVersion() + "\nMade with Mappalachia - github.com/AHeroicLlama/Mappalachia";

			// Additional steps for cell mode (Add further text to watermark text, get cell height boundings)
			if (SettingsMap.IsCellModeActive())
			{
				Cell currentCell = SettingsCell.GetCell();

				// replacedign the CellScaling property
				cellScaling = currentCell.GetScaling();

				infoText =
					currentCell.displayName + " (" + currentCell.editorID + ")\n" +
					"Height distribution: " + SettingsCell.minHeightPerc + "% - " + SettingsCell.maxHeightPerc + "%\n" +
					"Scale: 1:" + Math.Round(cellScaling.scale, 2) + "\n\n" +
					infoText;
			}

			// Gather resources for drawing informational watermark text
			Brush brushWhite = new SolidBrush(Color.White);
			RectangleF infoTextBounds = new RectangleF(plotXMin, 0, mapDimension - plotXMin, mapDimension);
			StringFormat stringFormatBottomRight = new StringFormat() { Alignment = StringAlignment.Far, LineAlignment = StringAlignment.Far }; // Align the text bottom-right
			StringFormat stringFormatBottomLeft = new StringFormat() { Alignment = StringAlignment.Near, LineAlignment = StringAlignment.Far }; // Align the text bottom-left

			// Draws bottom-right info text
			imageGraphic.DrawString(infoText, font, brushWhite, infoTextBounds, stringFormatBottomRight);

			// Draw a height-color key for Topography mode
			if (SettingsPlot.IsTopographic())
			{
				// Identify the sizing and locations for drawing the height-color-key strings
				double numHeightKeys = SettingsPlotTopograph.heightKeyIndicators;
				Font topographFont = new Font(fontCollection.Families[0], 62, GraphicsUnit.Pixel);
				float singleLineHeight = imageGraphic.MeasureString(SettingsPlotTopograph.heightKeyString, topographFont, new SizeF(infoTextBounds.Width, infoTextBounds.Height)).Height;

				// Identify the lower limit to start printing the key so that it ends up centered
				double baseHeight = (mapDimension / 2) - (singleLineHeight * (numHeightKeys / 2d));

				for (int i = 0; i <= numHeightKeys - 1; i++)
				{
					Brush brush = new SolidBrush(GetTopographColor(i / (numHeightKeys - 1)));
					imageGraphic.DrawString(SettingsPlotTopograph.heightKeyString, topographFont, brush, new RectangleF(plotXMax, 0, mapDimension - plotXMax, (float)(mapDimension - baseHeight)), stringFormatBottomRight);
					baseHeight += singleLineHeight;
				}
			}

			// Draw all legend text for every MapItem
			int skippedLegends = DrawLegend(font, imageGraphic);

			// Adds additional text if some items were missed from legend
			if (skippedLegends > 0)
			{
				string extraLegendText = "+" + skippedLegends + " more item" + (skippedLegends == 1 ? string.Empty : "s") + "...";
				imageGraphic.DrawString(extraLegendText, font, brushWhite, infoTextBounds, stringFormatBottomLeft);
			}

			// Start progress bar off at 0
			progressBarMain.Value = progressBarMain.Minimum;
			float progress = 0;

			// Nothing else to plot - ensure we update for the background layer but then return
			if (FormMaster.legendItems.Count == 0)
			{
				mapFrame.Image = finalImage;
				return;
			}

			// Count how many Map Data Points are due to be mapped
			int totalMapDataPoints = 0;
			foreach (MapItem mapItem in FormMaster.legendItems)
			{
				totalMapDataPoints += mapItem.count;
			}

			// Loop through every MapDataPoint represented by all the MapItems to find the min/max z coord in the dataset
			bool first = true;
			int zMin = 0;
			int zMax = 0;
			double zRange = 0;
			if (SettingsPlot.IsTopographic())
			{
				foreach (MapItem mapItem in FormMaster.legendItems)
				{
					foreach (MapDataPoint point in mapItem.GetPlots())
					{
						if (first)
						{
							zMin = point.z - (point.boundZ / 2);
							zMax = point.z + (point.boundZ / 2);
							first = false;
							continue;
						}

						// Do not contribute outlier values to the min/max range - this ensures they have the same
						// color as the min/max *legitimate* item and they do not skew the color ranges
						if (point.z > SettingsPlotTopograph.zThreshUpper || point.z < SettingsPlotTopograph.zThreshLower)
						{
							continue;
						}

						if (point.z - (point.boundZ / 2) < zMin)
						{
							zMin = point.z - (point.boundZ / 2);
						}

						if (point.z + (point.boundZ / 2) > zMax)
						{
							zMax = point.z + (point.boundZ / 2);
						}
					}
				}

				zRange = Math.Abs(zMax - zMin);

				if (zRange == 0)
				{
					zRange = 1;
				}
			}

			if (SettingsPlot.IsIconOrTopographic())
			{
				if (SettingsPlot.IsTopographic())
				{
					// Somehow this line prevents a memory leak
					// Without it, if drawing a large topographic map on first map draw, GC will not collect the multiple PlotIcon elements used in topographic drawing.
					Application.DoEvents();
				}

				// Processing each MapItem in serial, draw plots for every matching valid MapDataPoint
				foreach (MapItem mapItem in FormMaster.legendItems)
				{
					// Generate a Plot Icon and colours/brushes to be used for all instances of the MapItem
					PlotIcon plotIcon = mapItem.GetIcon();
					Image plotIconImg = SettingsPlot.IsIcon() ? plotIcon.GetIconImage() : null; // Icon mode has icon per MapItem, Topography needs icons per MapDataPoint and will be generated later
					Color volumeColor = Color.FromArgb(volumeOpacity, plotIcon.color);
					Brush volumeBrush = new SolidBrush(volumeColor);

					// Iterate over every data point and draw it
					foreach (MapDataPoint point in mapItem.GetPlots())
					{
						// Override colors in Topographic mode
						if (SettingsPlot.IsTopographic())
						{
							// Clamp the z values to the percieved outlier threshold
							double z = point.z + (point.boundZ / 2);
							z = Math.Max(Math.Min(z, SettingsPlotTopograph.zThreshUpper), SettingsPlotTopograph.zThreshLower);

							// Normalize the height of this item between the min/max z of the whole set
							double colorValue = (z - zMin) / zRange;

							// Override the plot icon color
							plotIcon.color = GetTopographColor(colorValue);
							plotIconImg = plotIcon.GetIconImage(); // Generate a new icon with a unique color for this height color

							// Apply the color to volume plotting too
							volumeColor = Color.FromArgb(volumeOpacity, plotIcon.color);
							volumeBrush = new SolidBrush(volumeColor);
						}

						if (SettingsMap.IsCellModeActive())
						{
							// If this coordinate exceeds the user-selected cell mapping height bounds, skip it
							// (Also accounts for the z-height of volumes)
							if (point.z + (point.boundZ / 2d) < SettingsCell.GetMinHeightCoordBound() || point.z - (point.boundZ / 2d) > SettingsCell.GetMaxHeightCoordBound())
							{
								continue;
							}

							point.x += cellScaling.xOffset;
							point.y += cellScaling.yOffset;

							// Multiply the coordinates by the scaling, but multiply around 0,0
							point.x = ((point.x - (mapDimension / 2)) * cellScaling.scale) + (mapDimension / 2);
							point.y = ((point.y - (mapDimension / 2)) * cellScaling.scale) + (mapDimension / 2);
							point.boundX *= cellScaling.scale;
							point.boundY *= cellScaling.scale;
						}
						else // Skip the point if its origin is outside the surface world
						if (point.x < plotXMin || point.x >= plotXMax || point.y < plotYMin || point.y >= plotYMax)
						{
							continue;
						}

						// If this meets all the criteria to be suitable to be drawn as a volume
						if (point.primitiveShape != string.Empty && // This is a primitive shape at all
							SettingsPlot.drawVolumes && // Volume drawing is enabled
							point.boundX >= minVolumeDimension && point.boundY >= minVolumeDimension) // This is large enough to be visible if drawn as a volume
						{
							Image volumeImage = new Bitmap((int)point.boundX, (int)point.boundY);
							Graphics volumeGraphic = Graphics.FromImage(volumeImage);
							volumeGraphic.SmoothingMode = SmoothingMode.AntiAlias;

							switch (point.primitiveShape)
							{
								case "Box":
								case "Line":
								case "Plane":
									volumeGraphic.FillRectangle(volumeBrush, new Rectangle(0, 0, (int)point.boundX, (int)point.boundY));
									break;
								case "Sphere":
								case "Ellipsoid":
									volumeGraphic.FillEllipse(volumeBrush, new Rectangle(0, 0, (int)point.boundX, (int)point.boundY));
									break;
								default:
									continue; // If we reach this, we dropped the drawing of a volume. Verify we've covered all shapes via the database summary.txt
							}

							volumeImage = ImageTools.RotateImage(volumeImage, point.rotationZ);
							imageGraphic.DrawImage(volumeImage, (float)(point.x - (volumeImage.Width / 2)), (float)(point.y - (volumeImage.Height / 2)));
						}

						// This MapDataPoint is not suitable to be drawn as a volume - draw a normal plot icon, or topographic plot
						else
						{
							imageGraphic.DrawImage(plotIconImg, (float)(point.x - (plotIconImg.Width / 2d)), (float)(point.y - (plotIconImg.Height / 2d)));
						}
					}

					// Increment the progress bar per MapItem
					progress += mapItem.count;
					progressBarMain.Value = (int)((progress / totalMapDataPoints) * progressBarMain.Maximum);
					Application.DoEvents();
				}
			}
			else if (SettingsPlot.IsHeatmap())
			{
				int resolution = SettingsPlotHeatmap.resolution;
				int blendRange = SettingsPlotHeatmap.blendDistance;

				// Create a 2D Array of HeatMapGridSquare
				HeatMapGridSquare[,] squares = new HeatMapGridSquare[resolution, resolution];
				for (int x = 0; x < resolution; x++)
				{
					for (int y = 0; y < resolution; y++)
					{
						squares[x, y] = new HeatMapGridSquare();
					}
				}

				int pixelsPerSquare = mapDimension / resolution;

				foreach (MapItem mapItem in FormMaster.legendItems)
				{
					int heatmapLegendGroup = SettingsPlotHeatmap.IsDuo() ? mapItem.legendGroup % 2 : 0;

					foreach (MapDataPoint point in mapItem.GetPlots())
					{
						if (SettingsMap.IsCellModeActive())
						{
							point.x += cellScaling.xOffset;
							point.y += cellScaling.yOffset;

							point.x = ((point.x - (mapDimension / 2)) * cellScaling.scale) + (mapDimension / 2);
							point.y = ((point.y - (mapDimension / 2)) * cellScaling.scale) + (mapDimension / 2);
						}

						// Identify which grid square this MapDataPoint falls within
						int squareX = (int)Math.Floor(point.x / pixelsPerSquare);
						int squareY = (int)Math.Floor(point.y / pixelsPerSquare);

						// Loop over every grid square within range, and increment by the weight proportional to the distance
						for (int x = squareX - blendRange; x < squareX + blendRange; x++)
						{
							for (int y = squareY - blendRange; y < squareY + blendRange; y++)
							{
								// Don't try to target squares which would lay outside of the grid
								if (x < 0 || x >= resolution || y < 0 || y >= resolution)
								{
									continue;
								}

								// Pythagoras on the x and y dist gives us the 'as the crow flies' distance between the squares
								double distance = Pythagoras(squareX - x, squareY - y);

								// Weight and hence brightness is modified by 1/x^2 + 1 where x is the distance from actual item
								double additionalWeight = point.weight * (1d / ((distance * distance) + 1));
								squares[x, y].weights[heatmapLegendGroup] += additionalWeight;
							}
						}
					}

					// Increment the progress bar per MapItem
					progress += mapItem.count;
					progressBarMain.Value = (int)((progress / totalMapDataPoints) * progressBarMain.Maximum);
					Application.DoEvents();
				}

				// Find the largest weight value of all squares
				double largestWeight = 0;
				for (int x = 0; x < resolution; x++)
				{
					for (int y = 0; y < resolution; y++)
					{
						double weight = squares[x, y].GetTotalWeight();
						if (weight > largestWeight)
						{
							largestWeight = weight;
						}
					}
				}

				// Finally now weights are calculated, draw a square for every HeatGripMapSquare in the array
				for (int x = 0; x < resolution; x++)
				{
					int xCoord = x * pixelsPerSquare;

					// Don't draw grid squares which are entirely within the legend text area
					if (xCoord + pixelsPerSquare < plotXMin)
					{
						continue;
					}

					for (int y = 0; y < resolution; y++)
					{
						int yCoord = y * pixelsPerSquare;

						Color color = squares[x, y].GetColor(largestWeight);
						Brush brush = new SolidBrush(color);

						Rectangle heatMapSquare = new Rectangle(xCoord, yCoord, mapDimension / SettingsPlotHeatmap.resolution, mapDimension / SettingsPlotHeatmap.resolution);
						imageGraphic.FillRectangle(brush, heatMapSquare);
					}
				}
			}

			mapFrame.Image = finalImage;
		}

19 View Source File : Map.cs
License : GNU General Public License v3.0
Project Creator : AHeroicLlama

static int DrawLegend(Font font, Graphics imageGraphic)
		{
			if (FormMaster.legendItems.Count == 0)
			{
				return 0;
			}

			Dictionary<int, string> overridingLegendText = FormMaster.GatherOverriddenLegendTexts();
			List<int> drawnGroups = new List<int>();

			// Calculate the total height of all legend strings with their plot icons beside, combined
			int legendTotalHeight = 0;
			foreach (MapItem mapItem in FormMaster.legendItems)
			{
				// Skip legend groups that are merged/overridden and have already been accounted for
				if (drawnGroups.Contains(mapItem.legendGroup) && overridingLegendText.ContainsKey(mapItem.legendGroup))
				{
					continue;
				}

				legendTotalHeight += Math.Max(
					(int)Math.Ceiling(imageGraphic.MeasureString(mapItem.GetLegendText(false), font, legendBounds).Height),
					SettingsPlot.IsIconOrTopographic() ? SettingsPlotIcon.iconSize : 0);

				drawnGroups.Add(mapItem.legendGroup);
			}

			int skippedLegends = 0; // How many legend items did not fit onto the map

			// The initial Y coord where first legend item should be written, in order to Y-center the entire legend
			int legendCaretHeight = (mapDimension / 2) - (legendTotalHeight / 2);

			// Reset the drawn groups list, as we need to iterate over the items again
			drawnGroups = new List<int>();

			// Loop over every MapItem and draw the legend
			foreach (MapItem mapItem in FormMaster.legendItems)
			{
				// Skip legend groups that are merged/overridden and have already been drawn
				if (drawnGroups.Contains(mapItem.legendGroup) && overridingLegendText.ContainsKey(mapItem.legendGroup))
				{
					continue;
				}

				// Calculate positions and color for legend text (plus icon)
				int fontHeight = (int)Math.Ceiling(imageGraphic.MeasureString(mapItem.GetLegendText(false), font, legendBounds).Height);

				PlotIcon icon = mapItem.GetIcon();
				Image plotIconImg = SettingsPlot.IsIconOrTopographic() ? icon.GetIconImage() : null;

				Color legendColor = SettingsPlot.IsTopographic() ? SettingsPlotTopograph.legendColor : mapItem.GetLegendColor();
				Brush textBrush = new SolidBrush(legendColor);

				int iconHeight = SettingsPlot.IsIconOrTopographic() ?
					plotIconImg.Height :
					0;

				int legendHeight = Math.Max(fontHeight, iconHeight);

				// If the icon is taller than the text, offset the text it so it sits Y-centrally against the icon
				int textOffset = 0;
				if (iconHeight > fontHeight)
				{
					textOffset = (iconHeight - fontHeight) / 2;
				}

				// If the legend text/item fits on the map vertically
				if (legendCaretHeight > 0 && legendCaretHeight + legendHeight < mapDimension)
				{
					if (SettingsPlot.IsIconOrTopographic())
					{
						imageGraphic.DrawImage(plotIconImg, (float)(legendIconX - (plotIconImg.Width / 2d)), (float)(legendCaretHeight - (plotIconImg.Height / 2d) + (legendHeight / 2d)));
					}

					imageGraphic.DrawString(mapItem.GetLegendText(false), font, textBrush, new RectangleF(legendXMin, legendCaretHeight + textOffset, legendWidth, legendHeight));
				}
				else
				{
					skippedLegends++;
				}

				drawnGroups.Add(mapItem.legendGroup);
				legendCaretHeight += legendHeight; // Move the 'caret' down for the next item, enough to fit the icon and the text
			}

			GC.Collect();
			return skippedLegends;
		}

19 View Source File : Graphics.cs
License : Mozilla Public License 2.0
Project Creator : ahyahy

public void DrawString(string str, osf.Font font, osf.Brush brush, float x, float y)
        {
            M_Graphics.DrawString(str, font.M_Font, (System.Drawing.Brush)brush.M_Brush, x, y);
            System.Windows.Forms.Application.DoEvents();
        }

19 View Source File : ImageMakerTextOverlay.cs
License : GNU General Public License v3.0
Project Creator : akaAgar

internal void Draw(Graphics graphics)
        {
            if (string.IsNullOrEmpty(Text)) return; // No text, nothing to draw

            using (Font font = new Font(FontFamily, FontSize, FontStyle))
            {
                Size textSize = graphics.MeasureString(Text, font).ToSize();
                StringFormat stringFormat = GetStringFormat();

                // Draw text black "shadow" first to make sure it is readable on any background
                if (Shadow)
                {
                    for (int x = -1; x <= 1; x++)
                        for (int y = -1; y <= 1; y++)
                            graphics.DrawString(Text, font, Brushes.Black,
                                new RectangleF(3 * x + 10, 3 * y + 10, ImageMaker.ImageSizeX -10, ImageMaker.ImageSizeY -10), stringFormat);
                }

                using (SolidBrush brush = new SolidBrush(Color))
                    graphics.DrawString(Text, font, brush,
                        new RectangleF(10, 10, ImageMaker.ImageSizeX - 10, ImageMaker.ImageSizeY -10), stringFormat);
            }
        }

19 View Source File : DynamicTextImage.cs
License : MIT License
Project Creator : akasarto

public MemoryStream Build(string text)
		{
			text = text ?? "?";

			var stream = new MemoryStream();

			var backgroundColor = ColorTranslator.FromHtml($"#{_backgroundHexColor.Trim('#')}");
			var foreGroundColor = ColorTranslator.FromHtml($"#{_foregroundHexColor.Trim('#')}");

			using (var baseFont = _fontInstanceCreator())
			{
				using (var bitmap = new Bitmap(_width, _height, PixelFormat.Format24bppRgb))
				{
					using (var graphics = Graphics.FromImage(bitmap))
					{
						var textSize = graphics.MeasureString(text, baseFont);
						var fontScale = Math.Max(textSize.Width / bitmap.Width, textSize.Height / bitmap.Height);

						using (var scaledFont = new Font(baseFont.FontFamily, baseFont.SizeInPoints / fontScale, baseFont.Style, baseFont.Unit))
						{
							graphics.Clear(backgroundColor);
							graphics.SmoothingMode = SmoothingMode.AntiAlias;
							graphics.CompositingQuality = CompositingQuality.HighQuality;
							graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
							graphics.TextRenderingHint = TextRenderingHint.AntiAlias;

							StringFormat strinngFormat = new StringFormat(StringFormat.GenericTypographic)
							{
								Alignment = StringAlignment.Center,
								LineAlignment = StringAlignment.Center,
								FormatFlags = StringFormatFlags.MeasureTrailingSpaces
							};

							textSize = graphics.MeasureString(text, scaledFont);

							graphics.DrawString(
								text,
								scaledFont,
								new SolidBrush(foreGroundColor),
								new RectangleF(
									0,
									0,
									bitmap.Width,
									bitmap.Height
								),
								strinngFormat
							);

							bitmap.Save(stream, ImageFormat.Png);

							stream.Position = 0;
						}
					}
				}
			}

			return stream;
		}

19 View Source File : SensorGadget.cs
License : MIT License
Project Creator : AlexGyver

protected override void OnPaint(PaintEventArgs e) {
      Graphics g = e.Graphics;
      int w = Size.Width;

      g.Clear(Color.Transparent);
      
      DrawBackground(g);

      int x;
      int y = topMargin;

      if (sensors.Count == 0) {
        x = leftBorder + 1;
        g.DrawString("Right-click on a sensor in the main window and select " + 
          "\"Show in Gadget\" to show the sensor here.", 
          smallFont, Brushes.White,
          new Rectangle(x, y - 1, w - rightBorder - x, 0));
      }

      foreach (KeyValuePair<IHardware, IList<ISensor>> pair in sensors) {
        if (hardwareNames.Value) {
          if (y > topMargin)
            y += hardwareLineHeight - sensorLineHeight;
          x = leftBorder + 1;
          g.DrawImage(HardwareTypeImage.Instance.GetImage(pair.Key.HardwareType),
            new Rectangle(x, y + 1, iconSize, iconSize));
          x += iconSize + 1;
          g.DrawString(pair.Key.Name, largeFont, Brushes.White,
            new Rectangle(x, y - 1, w - rightBorder - x, 0), 
            stringFormat);
          y += hardwareLineHeight;
        }

        foreach (ISensor sensor in pair.Value) {
          int remainingWidth;


          if ((sensor.SensorType != SensorType.Load &&
               sensor.SensorType != SensorType.Control &&
               sensor.SensorType != SensorType.Level) || !sensor.Value.HasValue) 
          {
            string formatted;

            if (sensor.Value.HasValue) {
              string format = "";
              switch (sensor.SensorType) {
                case SensorType.Voltage:
                  format = "{0:F3} V";
                  break;
                case SensorType.Clock:
                  format = "{0:F0} MHz";
                  break;
                case SensorType.Temperature:
                  format = "{0:F1} °C";
                  break;
                case SensorType.Fan:
                  format = "{0:F0} RPM";
                  break;
                case SensorType.Flow:
                  format = "{0:F0} L/h";
                  break;
                case SensorType.Power:
                  format = "{0:F1} W";
                  break;
                case SensorType.Data:
                  format = "{0:F1} GB";
                  break;
                case SensorType.Factor:
                  format = "{0:F3}";
                  break;
              }

              if (sensor.SensorType == SensorType.Temperature &&
                unitManager.TemperatureUnit == TemperatureUnit.Fahrenheit) {
                formatted = string.Format("{0:F1} °F",
                  UnitManager.CelsiusToFahrenheit(sensor.Value));
              } else {
                formatted = string.Format(format, sensor.Value);
              }
            } else {
              formatted = "-";
            }

            g.DrawString(formatted, smallFont, darkWhite,
              new RectangleF(-1, y - 1, w - rightMargin + 3, 0),
              alignRightStringFormat);

            remainingWidth = w - (int)Math.Floor(g.MeasureString(formatted,
              smallFont, w, StringFormat.GenericTypographic).Width) -
              rightMargin;
          } else {
            DrawProgress(g, w - progressWidth - rightMargin,
              y + 0.35f * sensorLineHeight, progressWidth,
              0.6f * sensorLineHeight, 0.01f * sensor.Value.Value);

            remainingWidth = w - progressWidth - rightMargin;
          }
           
          remainingWidth -= leftMargin + 2;
          if (remainingWidth > 0) {
            g.DrawString(sensor.Name, smallFont, darkWhite,
              new RectangleF(leftMargin - 1, y - 1, remainingWidth, 0), 
              trimStringFormat);
          }

          y += sensorLineHeight;
        }
      }
    }

19 View Source File : TabBar.cs
License : GNU General Public License v3.0
Project Creator : alexgracianoarj

private void DrawTabs(Graphics g)
		{
			Pen borderPen = new Pen(BorderColor);
			Brush activeTabBrush = new SolidBrush(ActiveTabColor);
			Brush inactiveTabBrush = new LinearGradientBrush(
				new Rectangle(0, 5, Width, Height - 1), ActiveTabColor,
				SystemColors.ControlLight, LinearGradientMode.Vertical);
			Brush textBrush;
			int left = LeftMargin;

			if (ForeColor.IsKnownColor)
				textBrush = SystemBrushes.FromSystemColor(ForeColor);
			else
				textBrush = new SolidBrush(ForeColor);

			g.DrawLine(borderPen, 0, Height - 1, left, Height - 1);
			foreach (Tab tab in tabs)
			{
				//TODO: szépíteni
				bool isActiveTab = (tab == activeTab);
				int top = (isActiveTab ? TopMargin : TopMargin + 2);
				Brush tabBrush = (isActiveTab ? activeTabBrush : inactiveTabBrush);
				Rectangle tabRectangle = new Rectangle(left, top, tab.Width, Height - top);

				// To display bottom line for inactive tabs
				if (!isActiveTab)
					tabRectangle.Height--;

				g.FillRectangle(tabBrush, tabRectangle); // Draw background
				g.DrawRectangle(borderPen, tabRectangle); // Draw border
				Font font = (isActiveTab) ? activeTabFont : Font;
				g.DrawString(tab.Text, font, textBrush, tabRectangle, stringFormat);

				left += tab.Width;
			}
			g.DrawLine(borderPen, left, Height - 1, Width - 1, Height - 1);

			borderPen.Dispose();
			if (!ForeColor.IsKnownColor)
				textBrush.Dispose();
			activeTabBrush.Dispose();
			inactiveTabBrush.Dispose();
		}

19 View Source File : GdiGraphics.cs
License : GNU General Public License v3.0
Project Creator : alexgracianoarj

public void DrawString(string s, Font font, Brush brush, RectangleF layoutRectangle,
			StringFormat format)
		{
			graphics.DrawString(s, font, brush, layoutRectangle, format);
		}

19 View Source File : SensorGadget.cs
License : MIT License
Project Creator : AlexGyver

protected override void OnPaint(PaintEventArgs e) {
      Graphics g = e.Graphics;
      int w = Size.Width;

      g.Clear(Color.Transparent);
      
      DrawBackground(g);

      int x;
      int y = topMargin;

      if (sensors.Count == 0) {
        x = leftBorder + 1;
        g.DrawString("Right-click on a sensor in the main window and select " + 
          "\"Show in Gadget\" to show the sensor here.", 
          smallFont, Brushes.White,
          new Rectangle(x, y - 1, w - rightBorder - x, 0));
      }

      foreach (KeyValuePair<IHardware, IList<ISensor>> pair in sensors) {
        if (hardwareNames.Value) {
          if (y > topMargin)
            y += hardwareLineHeight - sensorLineHeight;
          x = leftBorder + 1;
          g.DrawImage(HardwareTypeImage.Instance.GetImage(pair.Key.HardwareType),
            new Rectangle(x, y + 1, iconSize, iconSize));
          x += iconSize + 1;
          g.DrawString(pair.Key.Name, largeFont, Brushes.White,
            new Rectangle(x, y - 1, w - rightBorder - x, 0), 
            stringFormat);
          y += hardwareLineHeight;
        }

        foreach (ISensor sensor in pair.Value) {
          int remainingWidth;


          if ((sensor.SensorType != SensorType.Load &&
               sensor.SensorType != SensorType.Control &&
               sensor.SensorType != SensorType.Level) || !sensor.Value.HasValue) 
          {
            string formatted;

            if (sensor.Value.HasValue) {
              string format = "";
              switch (sensor.SensorType) {
                case SensorType.Voltage:
                  format = "{0:F3} V";
                  break;
                case SensorType.Clock:
                  format = "{0:F0} MHz";
                  break;
                case SensorType.Temperature:
                  format = "{0:F1} °C";
                  break;
                case SensorType.Fan:
                  format = "{0:F0} RPM";
                  break;
                case SensorType.Flow:
                  format = "{0:F0} L/h";
                  break;
                case SensorType.Power:
                  format = "{0:F1} W";
                  break;
                case SensorType.Data:
                  format = "{0:F1} GB";
                  break;
                case SensorType.Factor:
                  format = "{0:F3}";
                  break;
              }

              if (sensor.SensorType == SensorType.Temperature &&
                unitManager.TemperatureUnit == TemperatureUnit.Fahrenheit) {
                formatted = string.Format("{0:F1} °F",
                  UnitManager.CelsiusToFahrenheit(sensor.Value));
              } else {
                formatted = string.Format(format, sensor.Value);
              }
            } else {
              formatted = "-";
            }

            g.DrawString(formatted, smallFont, darkWhite,
              new RectangleF(-1, y - 1, w - rightMargin + 3, 0),
              alignRightStringFormat);

            remainingWidth = w - (int)Math.Floor(g.MeasureString(formatted,
              smallFont, w, StringFormat.GenericTypographic).Width) -
              rightMargin;
          } else {
            DrawProgress(g, w - progressWidth - rightMargin,
              y + 0.35f * sensorLineHeight, progressWidth,
              0.6f * sensorLineHeight, 0.01f * sensor.Value.Value);

            remainingWidth = w - progressWidth - rightMargin;
          }
           
          remainingWidth -= leftMargin + 2;
          if (remainingWidth > 0) {
            g.DrawString(sensor.Name, smallFont, darkWhite,
              new RectangleF(leftMargin - 1, y - 1, remainingWidth, 0), 
              trimStringFormat);
          }

          y += sensorLineHeight;
        }
      }
    }

19 View Source File : BaseTextControl.cs
License : MIT License
Project Creator : AlexGyver

public override void Draw(TreeNodeAdv node, DrawContext context)
		{
			if (context.CurrentEditorOwner == this && node == Parent.CurrentNode)
				return;

			Performancereplacedyzer.Start("BaseTextControl.Draw");
			string label = GetLabel(node);
			Rectangle bounds = GetBounds(node, context);
			Rectangle focusRect = new Rectangle(bounds.X, context.Bounds.Y,	
				bounds.Width, context.Bounds.Height);

			Brush backgroundBrush;
			Color textColor;
			Font font;
			CreateBrushes(node, context, label, out backgroundBrush, out textColor, out font, ref label);

			if (backgroundBrush != null)
				context.Graphics.FillRectangle(backgroundBrush, focusRect);
			if (context.DrawFocus)
			{
				focusRect.Width--;
				focusRect.Height--;
				if (context.DrawSelection == DrawSelectionMode.None)
					_focusPen.Color = SystemColors.ControlText;
				else
					_focusPen.Color = SystemColors.InactiveCaption;
				context.Graphics.DrawRectangle(_focusPen, focusRect);
			}
			
			Performancereplacedyzer.Start("BaseTextControl.DrawText");
			if (UseCompatibleTextRendering)
				TextRenderer.DrawText(context.Graphics, label, font, bounds, textColor, _formatFlags);
			else
				context.Graphics.DrawString(label, font, GetFrush(textColor), bounds, _format);
			Performancereplacedyzer.Finish("BaseTextControl.DrawText");

			Performancereplacedyzer.Finish("BaseTextControl.Draw");
		}

19 View Source File : GraphicsRenderContext.cs
License : MIT License
Project Creator : AlexGyver

public override void DrawText(
            ScreenPoint p,
            string text,
            OxyColor fill,
            string fontFamily,
            double fontSize,
            double fontWeight,
            double rotate,
            HorizontalAlignment halign,
            VerticalAlignment valign,
            OxySize? maxSize)
        {
            var fs = FontStyle.Regular;
            if (fontWeight >= 700)
            {
                fs = FontStyle.Bold;
            }

            using (var font = new Font(fontFamily, (float)fontSize * FontsizeFactor, fs))
            {
                using (var sf = new StringFormat { Alignment = StringAlignment.Near })
                {
                    var size = this.g.MeasureString(text, font);
                    if (maxSize != null)
                    {
                        if (size.Width > maxSize.Value.Width)
                        {
                            size.Width = (float)maxSize.Value.Width;
                        }

                        if (size.Height > maxSize.Value.Height)
                        {
                            size.Height = (float)maxSize.Value.Height;
                        }
                    }

                    float dx = 0;
                    if (halign == HorizontalAlignment.Center)
                    {
                        dx = -size.Width / 2;
                    }

                    if (halign == HorizontalAlignment.Right)
                    {
                        dx = -size.Width;
                    }

                    float dy = 0;
                    sf.LineAlignment = StringAlignment.Near;
                    if (valign == VerticalAlignment.Middle)
                    {
                        dy = -size.Height / 2;
                    }

                    if (valign == VerticalAlignment.Bottom)
                    {
                        dy = -size.Height;
                    }

                    this.g.TranslateTransform((float)p.X, (float)p.Y);
                    if (Math.Abs(rotate) > double.Epsilon)
                    {
                        this.g.RotateTransform((float)rotate);
                    }

                    this.g.TranslateTransform(dx, dy);

                    var layoutRectangle = new RectangleF(0, 0, size.Width, size.Height);
                    this.g.DrawString(text, font, this.ToBrush(fill), layoutRectangle, sf);

                    this.g.ResetTransform();
                }
            }
        }

19 View Source File : Main.cs
License : MIT License
Project Creator : AlturosDestinations

private void DrawBoundingBoxes(IEnumerable<YoloTrackingItem> items)
        {
            var imageInfo = this.GetCurrentImage();
            //Load the image(probably from your stream)
            var image = Image.FromFile(imageInfo.Path);

            using (var font = new Font(FontFamily.GenericSansSerif, 16))
            using (var canvas = Graphics.FromImage(image))
            {
                foreach (var item in items)
                {
                    var x = item.X;
                    var y = item.Y;
                    var width = item.Width;
                    var height = item.Height;

                    var brush = this.GetBrush(item.Confidence);
                    var penSize = image.Width / 100.0f;

                    using (var pen = new Pen(brush, penSize))
                    {
                        canvas.DrawRectangle(pen, x, y, width, height);
                        canvas.FillRectangle(brush, x - (penSize / 2), y - 15, width + penSize, 25);
                    }
                }

                foreach (var item in items)
                {
                    canvas.DrawString(item.ObjectId.ToString(), font, Brushes.White, item.X, item.Y - 12);
                }

                canvas.Flush();
            }

            var oldImage = this.pictureBox1.Image;
            this.pictureBox1.Image = image;
            oldImage?.Dispose();
        }

19 View Source File : AnnotateMarginControl.cs
License : Apache License 2.0
Project Creator : AmpScm

protected override void OnPaint(PaintEventArgs e)
        {
            if (DesignMode)
                return;

            StringFormat sfr = new StringFormat();
            sfr.Alignment = StringAlignment.Far;

            StringFormat sfl = new StringFormat();
            sfl.Trimming = StringTrimming.EllipsisCharacter;
            sfl.FormatFlags = StringFormatFlags.NoWrap;

            using (Font f = new Font(Font.FontFamily, 7F))
            using (Pen border = new Pen(Color.Gray))
            using (Brush textColor = new SolidBrush(Color.Black))
            using (Brush selectedTextColor = new SolidBrush(SystemColors.HighlightText))
            using (Brush grayBg = new LinearGradientBrush(new Point(0, 0), new Point(Width, 0), BackColor, Color.LightGray))
            using (Brush blueBg = new LinearGradientBrush(new Point(0, 0), new Point(Width, 0), BackColor, Color.LightBlue))
            using (Brush selectedBg = new SolidBrush(SystemColors.Highlight))
            using (SolidBrush localBg = new SolidBrush(SystemColors.Info))
            {
                foreach (AnnotateRegion region in _regions)
                {
                    // We try to draw a few regions above and below to fix up drawing
                    // when the actual editor is smaller than our view. 
                    // (E.g. navigation bar for C# editor)
                    if (region.EndLine < _firstLine-4) 
                        continue;
                    if (region.StartLine > _lastLine+4)
                        break;

                    Rectangle rect = GetRectangle(region);
                    if (!e.ClipRectangle.IntersectsWith(rect))
                        continue;

                    if (IsSelected(region))
                        e.Graphics.FillRectangle(selectedBg, rect);
                    else
                    {
                        if (region.Hovered)
                            e.Graphics.FillRectangle(blueBg, rect);
                        else if (region.Source.Revision >= 0)
                            e.Graphics.FillRectangle(grayBg, rect);
                        else
                            e.Graphics.FillRectangle(localBg, rect);
                    }
                    e.Graphics.DrawRectangle(border, rect);

                    AnnotateSource src = region.Source;
                    if (src.Revision >= 0)
                    {
                        string revisionString = src.Revision.ToString();
                        string dateString = src.Time.ToShortDateString();

                        float rectTop = rect.Top + 2; // top padding of 2px
                        float revisionWidth = e.Graphics.MeasureString(revisionString, f).Width;
                        float dateWidth = e.Graphics.MeasureString(dateString, f).Width;

                        // Calculate the author field based on the fields to the left and right of it
                        // because we use ellipsis trimming when it's too small
                        float authorWidth = Width - revisionWidth - dateWidth - 8; // left+right padding of both revision and date means 2+2+2+2 = 8

                        Brush color = IsSelected(region) ? selectedTextColor : textColor;
                        e.Graphics.DrawString(revisionString, f, color, new RectangleF(3, rectTop, revisionWidth, LineHeight), sfr);

                        // TODO: decide if this is the best way
                        // If the authorWidth is negative, don't attempt to show the author. This case should only
                        // occur with very long ShortDateStrings, or very long revision strings.
                        if (authorWidth > 0)
                            e.Graphics.DrawString(src.Author, f, color, new RectangleF(revisionWidth + 5, rectTop, authorWidth, LineHeight), sfl);

                        e.Graphics.DrawString(dateString, f, color, new RectangleF(Width - dateWidth - 2, rectTop, dateWidth, LineHeight), sfr);
                    }
                }

                Rectangle clip = e.ClipRectangle;
                using (SolidBrush sb = new SolidBrush(BackColor))
                {
                    if (_regions.Count > 0)
                    {
                        Rectangle rect = GetRectangle(_regions[0]);

                        if (e.ClipRectangle.Top < rect.Top)
                            e.Graphics.FillRectangle(sb, clip.X, clip.Y, clip.Width, rect.Top - clip.Y);
                            
                        rect = GetRectangle(_regions[_regions.Count - 1]);

                        if (e.ClipRectangle.Bottom > rect.Bottom)
                            e.Graphics.FillRectangle(sb, clip.X, rect.Bottom + 1, rect.Width, clip.Y+clip.Height - rect.Bottom - 1);
                    }
                    else
                        e.Graphics.FillRectangle(sb, clip);
                }
            }
        }

19 View Source File : AnnotateMarginControl.cs
License : Apache License 2.0
Project Creator : AmpScm

protected override void OnPaint(PaintEventArgs e)
        {
            if (DesignMode)
                return;

            StringFormat sfr = new StringFormat();
            sfr.Alignment = StringAlignment.Far;

            StringFormat sfl = new StringFormat();
            sfl.Trimming = StringTrimming.EllipsisCharacter;
            sfl.FormatFlags = StringFormatFlags.NoWrap;

            using (Font f = new Font(Font.FontFamily, 7F))
            using (Pen border = new Pen(Color.Gray))
            using (Brush textColor = new SolidBrush(Color.Black))
            using (Brush selectedTextColor = new SolidBrush(SystemColors.HighlightText))
            using (Brush grayBg = new LinearGradientBrush(new Point(0, 0), new Point(Width, 0), BackColor, Color.LightGray))
            using (Brush blueBg = new LinearGradientBrush(new Point(0, 0), new Point(Width, 0), BackColor, Color.LightBlue))
            using (Brush selectedBg = new SolidBrush(SystemColors.Highlight))
            using (SolidBrush localBg = new SolidBrush(SystemColors.Info))
            {
                foreach (AnnotateRegion region in _regions)
                {
                    // We try to draw a few regions above and below to fix up drawing
                    // when the actual editor is smaller than our view. 
                    // (E.g. navigation bar for C# editor)
                    if (region.EndLine < _firstLine-4) 
                        continue;
                    if (region.StartLine > _lastLine+4)
                        break;

                    Rectangle rect = GetRectangle(region);
                    if (!e.ClipRectangle.IntersectsWith(rect))
                        continue;

                    if (IsSelected(region))
                        e.Graphics.FillRectangle(selectedBg, rect);
                    else
                    {
                        if (region.Hovered)
                            e.Graphics.FillRectangle(blueBg, rect);
                        else if (region.Source.Revision >= 0)
                            e.Graphics.FillRectangle(grayBg, rect);
                        else
                            e.Graphics.FillRectangle(localBg, rect);
                    }
                    e.Graphics.DrawRectangle(border, rect);

                    AnnotateSource src = region.Source;
                    if (src.Revision >= 0)
                    {
                        string revisionString = src.Revision.ToString();
                        string dateString = src.Time.ToShortDateString();

                        float rectTop = rect.Top + 2; // top padding of 2px
                        float revisionWidth = e.Graphics.MeasureString(revisionString, f).Width;
                        float dateWidth = e.Graphics.MeasureString(dateString, f).Width;

                        // Calculate the author field based on the fields to the left and right of it
                        // because we use ellipsis trimming when it's too small
                        float authorWidth = Width - revisionWidth - dateWidth - 8; // left+right padding of both revision and date means 2+2+2+2 = 8

                        Brush color = IsSelected(region) ? selectedTextColor : textColor;
                        e.Graphics.DrawString(revisionString, f, color, new RectangleF(3, rectTop, revisionWidth, LineHeight), sfr);

                        // TODO: decide if this is the best way
                        // If the authorWidth is negative, don't attempt to show the author. This case should only
                        // occur with very long ShortDateStrings, or very long revision strings.
                        if (authorWidth > 0)
                            e.Graphics.DrawString(src.Author, f, color, new RectangleF(revisionWidth + 5, rectTop, authorWidth, LineHeight), sfl);

                        e.Graphics.DrawString(dateString, f, color, new RectangleF(Width - dateWidth - 2, rectTop, dateWidth, LineHeight), sfr);
                    }
                }

                Rectangle clip = e.ClipRectangle;
                using (SolidBrush sb = new SolidBrush(BackColor))
                {
                    if (_regions.Count > 0)
                    {
                        Rectangle rect = GetRectangle(_regions[0]);

                        if (e.ClipRectangle.Top < rect.Top)
                            e.Graphics.FillRectangle(sb, clip.X, clip.Y, clip.Width, rect.Top - clip.Y);
                            
                        rect = GetRectangle(_regions[_regions.Count - 1]);

                        if (e.ClipRectangle.Bottom > rect.Bottom)
                            e.Graphics.FillRectangle(sb, clip.X, rect.Bottom + 1, rect.Width, clip.Y+clip.Height - rect.Bottom - 1);
                    }
                    else
                        e.Graphics.FillRectangle(sb, clip);
                }
            }
        }

19 View Source File : StatusContainer.cs
License : Apache License 2.0
Project Creator : AmpScm

protected override void OnPaint(PaintEventArgs e)
        {
            //base.OnPaint(e);
            int width = ClientSize.Width;
            Font fnt = null;
            StringFormat fmt = null;
            try
            {
                foreach (StatusPanel panel in Controls)
                {
                    if (!panel.Visible)
                        continue;

                    Point pl = panel.PanelLocation;
                    Size pz = panel.PanelSize;
                    int hh = panel.HeaderHeight;

                    e.Graphics.DrawRectangle(SystemPens.ControlDark, new Rectangle(pl, pz));
                    e.Graphics.DrawLine(SystemPens.ControlDark, pl.X + 1, pl.Y + hh + 1, pl.X + pz.Width, pl.Y + hh + 1);

                    using (Brush brush = new LinearGradientBrush(pl, pl + new Size(width, 0), panel.GradientLeft, panel.GradientRight))
                        e.Graphics.FillRectangle(brush, new Rectangle(pl.X + 1, pl.Y + 1, pz.Width - 1, panel.HeaderHeight));

                    Image img = panel.HeaderImage;

                    if (img != null)
                        e.Graphics.DrawImageUnscaled(img, pl + new Size((hh - img.Width) / 2, (hh - img.Height) / 2));

                    if (!string.IsNullOrEmpty(panel.replacedle))
                    {
                        if (fnt == null)
                        {
                            Font f = Font;
                            fnt = new Font(SystemFonts.CaptionFont.FontFamily, f.SizeInPoints * 1.5f, FontStyle.Regular);
                            fmt = new StringFormat(StringFormatFlags.NoWrap);
                            fmt.LineAlignment = StringAlignment.Center;
                        }

                        int x = pl.X + hh;
                        e.Graphics.DrawString(panel.replacedle, fnt, SystemBrushes.ControlText, new RectangleF(x, pl.Y + 1, pz.Width - x, hh), fmt);
                    }
                }
            }
            finally
            {
                if (fnt != null)
                    fnt.Dispose();
            }
        }

19 View Source File : DockersTabsControl.cs
License : GNU General Public License v3.0
Project Creator : anotak

protected unsafe void RedrawTabs()
		{
			// Determine length and width in pixels
			int tabslength = 0;
			for(int i = 0; i < this.TabPages.Count; i++)
			{
				Rectangle r = this.GetTabRect(i);
				tabslength += r.Height;
			}
			tabslength += 4;
			int tabswidth = this.ItemSize.Height + 2;
			
			// Dispose old image
			if(tabsimage != null)
			{
				tabsimage.Dispose();
				tabsimage = null;
			}
			
			if(VisualStyleInformation.IsSupportedByOS && VisualStyleInformation.IsEnabledByUser)
			{
				StringFormat drawformat = new StringFormat();
				drawformat.Alignment = StringAlignment.Center;
				drawformat.HotkeyPrefix = HotkeyPrefix.None;
				drawformat.LineAlignment = StringAlignment.Center;
				
				// Create images
				tabsimage = new Bitmap(tabswidth, tabslength, PixelFormat.Format32bppArgb);
				Bitmap drawimage = new Bitmap(tabslength, tabswidth, PixelFormat.Format32bppArgb);
				Graphics g = Graphics.FromImage(drawimage);
				
				// Render the tabs (backwards when right-aligned)
				int posoffset = 0;
				int selectedposoffset = -1;
				int start = (this.Alignment == TabAlignment.Left) ? 0 : (this.TabPages.Count - 1);
				int end = (this.Alignment == TabAlignment.Left) ? this.TabPages.Count : -1;
				int step = (this.Alignment == TabAlignment.Left) ? 1 : -1;
				for(int i = start; i != end; i += step)
				{
					VisualStyleRenderer renderer;
					Rectangle tr = this.GetTabRect(i);
					
					// Tab selected?
					if(i == this.SelectedIndex)
					{
						// We will draw this later
						selectedposoffset = posoffset;
					}
					else
					{
						if(i == highlighttab)
							renderer = new VisualStyleRenderer(VisualStyleElement.Tab.TabItem.Hot);
						else
							renderer = new VisualStyleRenderer(VisualStyleElement.Tab.TabItem.Normal);
						
						// Draw tab
						Rectangle r = new Rectangle(posoffset + 2, 2, tr.Height, tr.Width - 2);
						renderer.DrawBackground(g, r);
						g.DrawString(this.TabPages[i].Text, this.Font, SystemBrushes.ControlText, new RectangleF(r.Location, r.Size), drawformat);
					}
					
					posoffset += tr.Height;
				}
				
				// Render the selected tab, because it is slightly larger and overlapping the others
				if(selectedposoffset > -1)
				{
					VisualStyleRenderer renderer = new VisualStyleRenderer(VisualStyleElement.Tab.TabItem.Pressed);
					Rectangle tr = this.GetTabRect(this.SelectedIndex);
					Rectangle r = new Rectangle(selectedposoffset, 0, tr.Height + 4, tr.Width);
					renderer.DrawBackground(g, r);
					g.DrawString(this.TabPages[this.SelectedIndex].Text, this.Font, SystemBrushes.ControlText, new RectangleF(r.X, r.Y, r.Width, r.Height - 2), drawformat);
				}
				
				// Rotate the image and copy to tabsimage
				BitmapData drawndata = drawimage.LockBits(new Rectangle(0, 0, drawimage.Size.Width, drawimage.Size.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
				BitmapData targetdata = tabsimage.LockBits(new Rectangle(0, 0, tabsimage.Size.Width, tabsimage.Size.Height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);
				int* dd = (int*)drawndata.Scan0.ToPointer();
				int* td = (int*)targetdata.Scan0.ToPointer();
				if(this.Alignment == TabAlignment.Right)
				{
					for(int y = 0; y < drawndata.Height; y++)
					{
						for(int x = 0; x < drawndata.Width; x++)
						{
							td[(drawndata.Width - 1 - x) * targetdata.Width + y] = *dd;
							dd++;
						}
					}
				}
				else
				{
					for(int y = 0; y < drawndata.Height; y++)
					{
						for(int x = 0; x < drawndata.Width; x++)
						{
							td[x * targetdata.Width + (drawndata.Height - 1 - y)] = *dd;
							dd++;
						}
					}
				}
				drawimage.UnlockBits(drawndata);
				tabsimage.UnlockBits(targetdata);
				
				// Clean up
				g.Dispose();
				drawimage.Dispose();
			}
		}

19 View Source File : ActionSelectorControl.cs
License : GNU General Public License v3.0
Project Creator : anotak

private void list_DrawItem(object sender, DrawItemEventArgs e)
		{
			INumberedreplacedle item;
			Brush displaybrush = SystemBrushes.WindowText;
			Brush backbrush = SystemBrushes.Window;
			string displayname = "";
			int intnumber = 0;
			
			// Only when running
			if(!this.DesignMode)
			{
				// Unknow item?
				if(e.Index < 0)
				{
					// Grayed
					displaybrush = new SolidBrush(SystemColors.GrayText);
					backbrush = new SolidBrush(SystemColors.Window);

					// Try getting integral number
					int.TryParse(number.Text, out intnumber);

					// Check what to display
					if(number.Text.Length == 0)
						displayname = "";
					else if(intnumber == 0)
						displayname = "None";
					else if((generalizedcategories != null) && GameConfiguration.IsGeneralized(intnumber, generalizedcategories))
						displayname = "Generalized (" + General.Map.Config.GetGeneralizedActionCategory(intnumber) + ")";
					else
						displayname = "Unknown";
				}
				// In the display part of the combobox?
				else if((e.State & DrawItemState.ComboBoxEdit) != 0)
				{
					// Show without number
					item = (INumberedreplacedle)list.Items[e.Index];
					displayname = item.replacedle.Trim();

					// Determine colors to use
					if(item.Index == 0)
					{
						// Grayed
						displaybrush = new SolidBrush(SystemColors.GrayText);
						backbrush = new SolidBrush(SystemColors.Window);
					}
					else
					{
						// Normal color
						displaybrush = new SolidBrush(list.ForeColor);
						backbrush = new SolidBrush(SystemColors.Window);
					}
				}
				else
				{
					// Use number and description
					item = (INumberedreplacedle)list.Items[e.Index];
					displayname = item.Index + NUMBER_SEPERATOR + item.replacedle;

					// Determine colors to use
					if((e.State & DrawItemState.Focus) != 0)
					{
						displaybrush = new SolidBrush(SystemColors.HighlightText);
						backbrush = new SolidBrush(SystemColors.Highlight);
					}
					else
					{
						displaybrush = new SolidBrush(list.ForeColor);
						backbrush = new SolidBrush(SystemColors.Window);
					}
				}
				
			}

			// Draw item
			e.Graphics.FillRectangle(backbrush, e.Bounds);
			e.Graphics.DrawString(displayname, list.Font, displaybrush, e.Bounds.X, e.Bounds.Y);
		}

19 View Source File : ProgressBarEx.cs
License : GNU General Public License v3.0
Project Creator : antikmozib

protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)
        {
            e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
            Point StartPoint = new Point(0, 0);
            Point EndPoint = new Point(0, this.Height);

            if (_ProgressDirection == ProgressDir.Vertical)
            {
                EndPoint = new Point(this.Width, 0);
            }

            using (GraphicsPath gp = new GraphicsPath())
            {
                Rectangle rec = new Rectangle(0, 0, this.Width, this.Height);
                int rad = Convert.ToInt32(rec.Height / 2.5);
                if (rec.Width < rec.Height)
                    rad = Convert.ToInt32(rec.Width / 2.5);

                using (LinearGradientBrush _BackColorBrush = new LinearGradientBrush(StartPoint, EndPoint, _BackColor, _GradiantColor))
                {
                    _BackColorBrush.Blend = bBlend;
                    if (_RoundedCorners)
                    {
                        gp.AddArc(rec.X, rec.Y, rad, rad, 180, 90);
                        gp.AddArc(rec.Right - (rad), rec.Y, rad, rad, 270, 90);
                        gp.AddArc(rec.Right - (rad), rec.Bottom - (rad), rad, rad, 0, 90);
                        gp.AddArc(rec.X, rec.Bottom - (rad), rad, rad, 90, 90);
                        gp.CloseFigure();
                        e.Graphics.FillPath(_BackColorBrush, gp);
                    }
                    else
                    {
                        e.Graphics.FillRectangle(_BackColorBrush, rec);
                    }
                }

                if (_Value > _Minimum)
                {
                    int lngth = Convert.ToInt32((double)(this.Width / (double)(_Maximum - _Minimum)) * _Value);
                    if (_ProgressDirection == ProgressDir.Vertical)
                    {
                        lngth = Convert.ToInt32((double)(this.Height / (double)(_Maximum - _Minimum)) * _Value);
                        rec.Y = rec.Height - lngth;
                        rec.Height = lngth;
                    }
                    else
                    {
                        rec.Width = lngth;
                    }

                    using (LinearGradientBrush _ProgressBrush = new LinearGradientBrush(StartPoint, EndPoint, _ProgressColor, _GradiantColor))
                    {
                        _ProgressBrush.Blend = bBlend;
                        if (_RoundedCorners)
                        {
                            if (_ProgressDirection == ProgressDir.Horizontal)
                            {
                                rec.Height -= 1;
                            }
                            else
                            {
                                rec.Width -= 1;
                            }

                            using (GraphicsPath gp2 = new GraphicsPath())
                            {
                                gp2.AddArc(rec.X, rec.Y, rad, rad, 180, 90);
                                gp2.AddArc(rec.Right - (rad), rec.Y, rad, rad, 270, 90);
                                gp2.AddArc(rec.Right - (rad), rec.Bottom - (rad), rad, rad, 0, 90);
                                gp2.AddArc(rec.X, rec.Bottom - (rad), rad, rad, 90, 90);
                                gp2.CloseFigure();
                                using (GraphicsPath gp3 = new GraphicsPath())
                                {
                                    using (Region rgn = new Region(gp))
                                    {
                                        rgn.Intersect(gp2);
                                        gp3.AddRectangles(rgn.GetRegionScans(new Matrix()));
                                    }
                                    e.Graphics.FillPath(_ProgressBrush, gp3);
                                }
                            }
                        }
                        else
                        {
                            e.Graphics.FillRectangle(_ProgressBrush, rec);
                        }
                    }
                }

                if (_Image != null)
                {
                    if (_ImageLayout == ImageLayoutType.Stretch)
                    {
                        e.Graphics.DrawImage(_Image, 0, 0, this.Width, this.Height);
                    }
                    else if (_ImageLayout == ImageLayoutType.None)
                    {
                        e.Graphics.DrawImage(_Image, 0, 0);
                    }
                    else
                    {
                        int xx = Convert.ToInt32((this.Width / 2) - (_Image.Width / 2));
                        int yy = Convert.ToInt32((this.Height / 2) - (_Image.Height / 2));
                        e.Graphics.DrawImage(_Image, xx, yy);
                    }
                }

                if (_ShowPercentage | _ShowText)
                {
                    string perc = "";
                    if (_ShowText)
                        perc = this.Text;
                    if (_ShowPercentage)
                        perc += Convert.ToString(Convert.ToInt32(((double)100 / (double)(_Maximum - _Minimum)) * _Value)) + "%";
                    using (StringFormat sf = new StringFormat { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center })
                    {
                        e.Graphics.DrawString(perc, this.Font, _ForeColorBrush, new Rectangle(0, 0, this.Width, this.Height), sf);
                    }
                }

                if (_Border)
                {
                    rec = new Rectangle(0, 0, this.Width - 1, this.Height - 1);
                    if (_RoundedCorners)
                    {
                        gp.Reset();
                        gp.AddArc(rec.X, rec.Y, rad, rad, 180, 90);
                        gp.AddArc(rec.Right - (rad), rec.Y, rad, rad, 270, 90);
                        gp.AddArc(rec.Right - (rad), rec.Bottom - (rad), rad, rad, 0, 90);
                        gp.AddArc(rec.X, rec.Bottom - (rad), rad, rad, 90, 90);
                        gp.CloseFigure();
                        e.Graphics.DrawPath(_BorderPen, gp);
                    }
                    else
                    {
                        e.Graphics.DrawRectangle(_BorderPen, rec);
                    }
                }
            }
        }

19 View Source File : AmrPlotBase.cs
License : GNU General Public License v3.0
Project Creator : architecture-building-systems

private void Renderreplacedle(Graphics graphics)
        {
            var format = StringFormat.GenericTypographic;
            format.Alignment = StringAlignment.Center;
            graphics.DrawString(replacedle, replacedleFont, TextBrush, HeaderCenterBounds, format);
            format.Alignment = StringAlignment.Near;
            format.LineAlignment = StringAlignment.Near;
            format.Trimming = StringTrimming.EllipsisCharacter;
            graphics.DrawString(Description, NormalFont, TextBrush, HeaderLeftBounds.CloneInflate(-Spacer,0).CloneWithOffset(Spacer,0), format);
        }

19 View Source File : AmrPlotBase.cs
License : GNU General Public License v3.0
Project Creator : architecture-building-systems

private void RenderColumnreplacedles(Graphics graphics)
        {
            // we need to do some calculations, since we're mixing bold and standard fonts and have to do alignment ourselves...
            string Caption(double absoluteValue, string unit, double relativeValue)
            {
                return $"{absoluteValue:0} {unit} ({relativeValue:0}%)";
            }

            var format = StringFormat.GenericTypographic;
            format.Alignment = StringAlignment.Center;

            graphics.DrawString("Embodied", BoldFont, TextBrush, EmbodiedreplacedleBounds, format);
            graphics.DrawString("Operation", BoldFont, TextBrush, OperationreplacedleBounds, format);

            if (DisplaySumsAndAverages)
            {
                graphics.DrawString(Caption(TotalEmbodied, Data.Unit, Data.TotalEmbodied / Data.Total * 100), NormalFont, TextBrush, EmbodiedBuildingsLegendBounds, format);
                graphics.DrawString(Caption(TotalOperation, Data.Unit, Data.TotalOperation / Data.Total * 100), NormalFont, TextBrush, OperationBuildingsLegendBounds, format);
            }

            //graphics.DrawStringTwoFonts("Embodied\n", BoldFont,
            //    Caption(TotalEmbodied, Data.Unit, Data.TotalEmbodied / Data.Total * 100), NormalFont, TextBrush,
            //    EmbodiedreplacedleBounds);

            //graphics.DrawStringTwoFonts("Operation\n", BoldFont,
            //    Caption(TotalOperation, Data.Unit, Data.TotalOperation / Data.Total * 100), NormalFont,
            //    TextBrush, OperationreplacedleBounds);
        }

19 View Source File : LifetimeAmrPlot.cs
License : GNU General Public License v3.0
Project Creator : architecture-building-systems

protected override void RenderPlot(Graphics graphics)
        {
            var ebBounds = RenderEmbodiedBuildings(graphics);
            var esBounds = RenderEmbodiedSystems(graphics);
            var obBounds = RenderOperationBuildings(graphics);
            var osBounds = RenderOperationSystems(graphics);

            var total = Data.EmbodiedBuildings + Data.EmbodiedSystems + Data.OperationBuildings + Data.OperationSystems;
            string Caption(float value) => $"{value:0} ({value / total * 100:0}%)";

            var format = StringFormat.GenericTypographic;
            format.Alignment = StringAlignment.Center;
            format.LineAlignment = StringAlignment.Center;

            graphics.DrawString(Caption(Data.EmbodiedBuildings), NormalFont, TextBrush, ebBounds, format);
            graphics.DrawString(Caption(Data.EmbodiedSystems), NormalFont, TextBrush, esBounds, format);
            graphics.DrawString(Caption(Data.OperationBuildings), NormalFont, TextBrush, obBounds, format);
            graphics.DrawString(Caption(Data.OperationSystems), NormalFont, TextBrush, osBounds, format);
        }

19 View Source File : MenuButton.cs
License : GNU General Public License v3.0
Project Creator : architecture-building-systems

public void Render(ResultsPlotting results, Dictionary<string, string> plotParameters, Graphics graphics, RectangleF bounds)
        {
            _bounds = bounds;

            var format = StringFormat.GenericTypographic;
            format.Alignment = StringAlignment.Center;
            format.LineAlignment = StringAlignment.Center;

            graphics.FillRectangle(_backgroundBrush, bounds);
            graphics.DrawString(Text, _font, _textBrush, bounds, format);
            graphics.DrawRectangleF(_borderPen, bounds);
        }

19 View Source File : MonthlyAmrPlot.cs
License : GNU General Public License v3.0
Project Creator : architecture-building-systems

private void RenderOperationBuildings(Graphics graphics)
        {
            var plotBounds = OperationBuildingsPlotBounds.CloneInflate(-1, -1); // allow a bit of whitespace
            var columnWidth = plotBounds.Width / 12;
            var x = plotBounds.Left;
            foreach (var value in Data.OperationBuildingsMonthly)
            {
                var height = value.Scale(AxisMax, plotBounds.Height);
                var y = plotBounds.Y + (plotBounds.Height - height);
                var columnBounds = new RectangleF(x, y, columnWidth, height);
                graphics.FillRectangle(Style.BuildingsBrush, columnBounds);
                graphics.DrawRectangleF(new Pen(Color.White), columnBounds);

                // Value label
                var format = StringFormat.GenericTypographic;
                format.Alignment = StringAlignment.Center;
                format.LineAlignment = StringAlignment.Center;
                var textHeight = GH_FontServer.MeasureString(value.ToString(), SmallFont).Height;
                var valueLabelBounds = new RectangleF(x, y - 2 * textHeight, columnWidth, 2 * textHeight);
                graphics.DrawString(PlotCaption(value), SmallFont, TextBrush, valueLabelBounds, format);

                x += columnWidth;
            }

            RenderMonthLabelsBuildingsRow(graphics, plotBounds);
        }

19 View Source File : MonthlyAmrPlot.cs
License : GNU General Public License v3.0
Project Creator : architecture-building-systems

private void RenderMonthLabelsBuildingsRow(Graphics graphics, RectangleF bounds)
        {
            var format = StringFormat.GenericTypographic;
            format.Alignment = StringAlignment.Center;
            format.LineAlignment = StringAlignment.Center;

            var textHeight = GH_FontServer.MeasureString(months, BoldFont).Height;
            var x = bounds.Left;
            var columnWidth = bounds.Width / 12;
            foreach (var m in months)
            {
                var monthBounds = new RectangleF(x, bounds.Y, columnWidth, textHeight);
                graphics.DrawString(m.ToString(), BoldFont, TextBrush, monthBounds, format);
                x += columnWidth;
            }
        }

19 View Source File : MonthlyAmrPlot.cs
License : GNU General Public License v3.0
Project Creator : architecture-building-systems

private void RenderMonthLabelsSystemsRow(Graphics graphics, RectangleF bounds)
        {
            var format = StringFormat.GenericTypographic;
            format.Alignment = StringAlignment.Center;
            format.LineAlignment = StringAlignment.Center;

            var textHeight = GH_FontServer.MeasureString(months, BoldFont).Height;
            var x = bounds.Left;
            var columnWidth = bounds.Width / 12;
            foreach (var m in months)
            {
                var monthBounds = new RectangleF(x, bounds.Bottom - textHeight, columnWidth, textHeight);
                graphics.DrawString(m.ToString(), BoldFont, TextBrush, monthBounds, format);
                x += columnWidth;
            }
        }

19 View Source File : MonthlyAmrPlot.cs
License : GNU General Public License v3.0
Project Creator : architecture-building-systems

private void RenderOperationSystems(Graphics graphics)
        {
            var plotBounds = OperationSystemsPlotBounds.CloneInflate(-1, -1); // allow a bit of whitespace
            var columnWidth = plotBounds.Width / 12;
            var x = plotBounds.Left;
            foreach (var value in Data.OperationSystemsMonthly)
            {
                var height = value.Scale(AxisMax, plotBounds.Height);
                var y = plotBounds.Y;
                var columnBounds = new RectangleF(x, y, columnWidth, height);
                graphics.FillRectangle(Style.SystemsBrush, columnBounds);
                graphics.DrawRectangleF(new Pen(Color.White), columnBounds);

                // Value label
                var format = StringFormat.GenericTypographic;
                format.Alignment = StringAlignment.Center;
                format.LineAlignment = StringAlignment.Center;
                var textHeight = GH_FontServer.MeasureString(value.ToString(), SmallFont).Height;
                var valueLabelBounds = new RectangleF(x, y + height, columnWidth, textHeight * 2);
                graphics.DrawString(PlotCaption(value), SmallFont, TextBrush, valueLabelBounds, format);

                x += columnWidth;
            }
            RenderMonthLabelsSystemsRow(graphics, plotBounds);
        }

19 View Source File : MonthlyAmrPlot.cs
License : GNU General Public License v3.0
Project Creator : architecture-building-systems

private void RenderEmbodiedSystems(Graphics graphics)
        {
            var plotBounds = EmbodiedSystemsPlotBounds.CloneInflate(-1, -1); // allow a bit of whitespace
            var columnWidth = plotBounds.Width / 12;
            var x = plotBounds.Left;
            foreach (var value in Data.EmbodiedSystemsMonthly)
            {
                var height = value.Scale(AxisMax, plotBounds.Height);
                var y = plotBounds.Y;
                var columnBounds = new RectangleF(x, y, columnWidth, height);
                graphics.FillRectangle(Style.SystemsBrush, columnBounds);
                graphics.DrawRectangleF(new Pen(Color.White), columnBounds);

                // Value label
                var format = StringFormat.GenericTypographic;
                format.Alignment = StringAlignment.Center;
                format.LineAlignment = StringAlignment.Center;
                var textHeight = GH_FontServer.MeasureString(value.ToString(), SmallFont).Height;
                var valueLabelBounds = new RectangleF(x, y + height, columnWidth, textHeight * 2);
                graphics.DrawString(PlotCaption(value), SmallFont, TextBrush, valueLabelBounds, format);

                x += columnWidth;
            }
            RenderMonthLabelsSystemsRow(graphics, plotBounds);
        }

19 View Source File : MonthlyAmrPlot.cs
License : GNU General Public License v3.0
Project Creator : architecture-building-systems

private void RenderEmbodiedBuildings(Graphics graphics)
        {
            var plotBounds = EmbodiedBuildingsPlotBounds.CloneInflate(-1, -1); // allow a bit of whitespace
            var columnWidth = plotBounds.Width / 12;
            var x = plotBounds.Left;
            foreach (var value in Data.EmbodiedBuildingsMonthly)
            {
                var height = value.Scale(AxisMax, plotBounds.Height);
                var y = plotBounds.Y + (plotBounds.Height - height);
                var columnBounds = new RectangleF(x, y, columnWidth, height);
                graphics.FillRectangle(Style.BuildingsBrush, columnBounds);
                graphics.DrawRectangleF(new Pen(Color.White), columnBounds);

                // Value label
                var format = StringFormat.GenericTypographic;
                format.Alignment = StringAlignment.Center;
                format.LineAlignment = StringAlignment.Center;
                var textHeight = GH_FontServer.MeasureString(value.ToString(), SmallFont).Height;
                var valueLabelBounds = new RectangleF(x, y - 2 * textHeight, columnWidth, 2 * textHeight);
                graphics.DrawString(PlotCaption(value), SmallFont, TextBrush, valueLabelBounds, format);

                x += columnWidth;
            }
            RenderMonthLabelsBuildingsRow(graphics, plotBounds);
        }

19 View Source File : YearlyAmrPlot.cs
License : GNU General Public License v3.0
Project Creator : architecture-building-systems

protected override void RenderPlot(Graphics graphics)
        {
            // FIXME in case bounds are too small, caption sometimes does not appear
            // enforce some minimum bounds for the caption to always appear (based on string size)
            var ebBounds = RenderEmbodiedBuildings(graphics);
            var esBounds = RenderEmbodiedSystems(graphics);
            var obBounds = RenderOperationBuildings(graphics);
            var osBounds = RenderOperationSystems(graphics);

            var total = Data.EmbodiedBuildingsYearly + Data.EmbodiedSystemsYearly + Data.OperationBuildingsYearly + Data.OperationSystemsYearly;
            string Caption(float value) => $"{value:0} ({value / total * 100:0}%)";

            var format = StringFormat.GenericTypographic;
            format.Alignment = StringAlignment.Center;
            format.LineAlignment = StringAlignment.Center;

            graphics.DrawString(Caption(Data.EmbodiedBuildingsYearly), NormalFont, TextBrush, ebBounds, format);
            graphics.DrawString(Caption(Data.EmbodiedSystemsYearly), NormalFont, TextBrush, esBounds, format);
            graphics.DrawString(Caption(Data.OperationBuildingsYearly), NormalFont, TextBrush, obBounds, format);
            graphics.DrawString(Caption(Data.OperationSystemsYearly), NormalFont, TextBrush, osBounds, format);
        }

public static void DrawStringVertical(this Graphics graphics, string text, Font font, Brush brush,
            RectangleF bounds)
        {
            var format = StringFormat.GenericTypographic;
            format.Alignment = StringAlignment.Center;
            format.LineAlignment = StringAlignment.Center;

            var rotatedBounds = new RectangleF(bounds.Left, bounds.Bottom, bounds.Height, bounds.Width);
            var translatedBounds = rotatedBounds.CloneWithOffset(-rotatedBounds.X, -rotatedBounds.Y);

            graphics.TranslateTransform(bounds.X, bounds.Y + bounds.Height);
            graphics.RotateTransform(-90);
            graphics.DrawString(text, font, brush, translatedBounds, format);
            graphics.RotateTransform(+90);
            graphics.TranslateTransform(-bounds.X, -bounds.Y - bounds.Height);
        }

public static void DrawStringTwoFonts(this Graphics graphics, string textA, Font fontA, string textB,
            Font fontB, Brush brush, RectangleF bounds)
        {
            var format = StringFormat.GenericTypographic;
            format.Alignment = StringAlignment.Near;
            format.Trimming = StringTrimming.None;

            var boldTextSize = GH_FontServer.MeasureString(textA, fontA);
            var standardTextSize = GH_FontServer.MeasureString(textB, fontB);

            var leftPaddingWidth = (bounds.Width - boldTextSize.Width - standardTextSize.Width) / 2;
            var leftPaddingBounds = bounds.Clone();
            leftPaddingBounds.Width = leftPaddingWidth;
            var boldTextBounds = leftPaddingBounds.CloneRight(boldTextSize.Width);
            graphics.DrawString(textA, fontA, brush, boldTextBounds, format);

            var standardTextBounds = boldTextBounds.CloneRight(standardTextSize.Width);
            graphics.DrawString(textB, fontB, brush, standardTextBounds, format);
        }

private static void RenderLegendColumn(Graphics graphics, string replacedle, RectangleF legendBounds,
            IEnumerable<string> names,
            Color[] colors)
        {
            graphics.DrawString(replacedle, GH_FontServer.StandardBold, Brushes.Black, legendBounds);
            var replacedleHeight = GH_FontServer.MeasureString(replacedle, GH_FontServer.StandardBold).Height;
            var y = legendBounds.Y + replacedleHeight;
            using (var color = colors.Select(c => c).GetEnumerator())
            {
                color.MoveNext();
                foreach (var s in names)
                {
                    var size = GH_FontServer.MeasureString(s, GH_FontServer.Standard);
                    var iconBounds = new RectangleF(legendBounds.X, y, IconWidth, size.Height);
                    graphics.FillRectangle(new SolidBrush(color.Current), iconBounds);
                    graphics.DrawRectangleF(Pens.Black, iconBounds);
                    var textBounds = iconBounds.CloneRight(legendBounds.Width - IconWidth - IconPadding)
                        .CloneWithOffset(IconPadding, 0);
                    graphics.DrawString(s, GH_FontServer.Standard, Brushes.Black, textBounds);
                    y += size.Height + IconPadding;
                    color.MoveNext();
                }
            }
        }

19 View Source File : AmrPlotBase.cs
License : GNU General Public License v3.0
Project Creator : architecture-building-systems

private void Renderreplacedle(Graphics graphics)
        {
            var format = StringFormat.GenericTypographic;
            format.Alignment = StringAlignment.Center;
            graphics.DrawString(replacedle, replacedleFont, TextBrush, HeaderCenterBounds, format);
            format.Alignment = StringAlignment.Near;
            format.LineAlignment = StringAlignment.Near;
            format.Trimming = StringTrimming.EllipsisCharacter;
            graphics.DrawString(Description, NormalFont, TextBrush, HeaderLeftBounds.CloneInflate(-Spacer,0).CloneWithOffset(Spacer,0), format);
        }

19 View Source File : AmrPlotBase.cs
License : GNU General Public License v3.0
Project Creator : architecture-building-systems

private void RenderRightAxis(Graphics graphics)
        {
            if (DisplaySumsAndAverages) {
                var format = StringFormat.GenericTypographic;
                format.Alignment = StringAlignment.Center;
                format.LineAlignment = StringAlignment.Center;
                graphics.DrawString(PlotCaption(TotalBuildings, Data.Unit, Data.TotalBuildings / Data.Total * 100), NormalFont, TextBrush, BuildingsRightAxisBounds.CloneWithOffset(0, 2),
                    format);

                format.LineAlignment = StringAlignment.Center;
                graphics.DrawString(PlotCaption(TotalSystems, Data.Unit, Data.TotalSystems / Data.Total * 100), NormalFont, TextBrush, SystemsRightAxisBounds.CloneWithOffset(0, 2),
                    format);
            }
        }

private void RenderGainsArrows(Graphics graphics, PointF[] innerHousePolygon, RectangleF houseBounds,
            RectangleF bounds, float[] gains, float max)
        {
            if (max.IsClose(0.0f))
                // no data computed yet
                return;

            // inner axis, centered inside the house, left is end point of gains, right is starting point of losses
            var innerHouseBounds = HousePolygonToInnerRectangleF(innerHousePolygon);
            var houseCenterBounds = innerHouseBounds.CloneInflate(-innerHouseBounds.Width / 4f, -10);

            var inflectionPointRight = innerHouseBounds.X + 10f;
            var rightBounds = new RectangleF(
                inflectionPointRight, houseCenterBounds.Y,
                houseCenterBounds.Left - inflectionPointRight, houseCenterBounds.Height);

            var gainsArrowLeft = (bounds.Left + houseBounds.Left) / 2f;
            var innerHouseTop = innerHousePolygon[2].Y;
            var leftBounds = new RectangleF(gainsArrowLeft, innerHouseTop, rightBounds.Width,
                houseBounds.Bottom - innerHouseTop);

            var totalGains = gains.Sum();
            var newMax = rightBounds.Height - ArrowPadding * gains.GetUpperBound(0);
            var leftArrowPadding = (leftBounds.Height - newMax) / gains.GetUpperBound(0);
            var rightY = rightBounds.Y;
            var leftY = leftBounds.Y;
            var blackPen = new Pen(Color.Black);
            var blackBrush = new SolidBrush(Color.Black);
            var format = StringFormat.GenericTypographic;
            format.Alignment = StringAlignment.Center;
            format.LineAlignment = StringAlignment.Center;
            using (var color = GainsColors.Select(c => c).GetEnumerator())
            {
                color.MoveNext();
                foreach (var gain in gains)
                {
                    var arrowHeight = gain.Scale(max, newMax);
                    var rightArrowBounds = new RectangleF(rightBounds.Left, rightY, rightBounds.Width, arrowHeight);
                    var leftArrowBounds = new RectangleF(leftBounds.Left, leftY, leftBounds.Width, arrowHeight);

                    var arrowPolygon = CreateGainsArrowPolygon(leftArrowBounds, rightArrowBounds);
                    graphics.FillPolygon(new SolidBrush(color.Current), arrowPolygon);
                    graphics.DrawPolygon(blackPen, arrowPolygon);

                    // write the percentages
                    var gainPercent = gain / totalGains * 100;
                    graphics.DrawString($"{gainPercent:F0}%", GH_FontServer.Standard, blackBrush, rightArrowBounds,
                        format);

                    rightY += rightArrowBounds.Height + ArrowPadding;
                    leftY += rightArrowBounds.Height + leftArrowPadding;
                    color.MoveNext();
                }
            }
        }

private void RenderLossesArrows(Graphics graphics, PointF[] innerHousePolygon, RectangleF houseBounds,
            RectangleF bounds, float[] losses, float max)
        {
            if (max.IsClose(0.0f))
                // no data computed yet
                return;

            // inner axis, centered inside the house, left is end point of gains, right is starting point of losses
            var innerHouseBounds = HousePolygonToInnerRectangleF(innerHousePolygon);

            var houseCenterBounds = innerHouseBounds.CloneInflate(-innerHouseBounds.Width / 4f, -10);

            var inflectionPointLeft = innerHouseBounds.Right - 10f;
            var leftBounds = new RectangleF(
                houseCenterBounds.Right, houseCenterBounds.Y,
                inflectionPointLeft - houseCenterBounds.Right, houseCenterBounds.Height);

            var lossesArrowRight = (bounds.Right + houseBounds.Right) / 2f;
            var innerHouseTop = innerHousePolygon[2].Y;
            var rightBounds = new RectangleF(lossesArrowRight - leftBounds.Width, innerHouseTop, leftBounds.Width,
                houseBounds.Bottom - innerHouseTop);

            var totalLosses = losses.Sum();
            var newMax = leftBounds.Height - ArrowPadding * losses.GetUpperBound(0);
            var rightArrowPadding = (rightBounds.Height - newMax) / losses.GetUpperBound(0);
            var leftY = leftBounds.Y;
            var rightY = rightBounds.Y;
            var blackPen = new Pen(Color.Black);
            var blackBrush = new SolidBrush(Color.Black);
            var format = StringFormat.GenericTypographic;
            format.Alignment = StringAlignment.Center;
            format.LineAlignment = StringAlignment.Center;
            using (var color = LossesColors.Select(c => c).GetEnumerator())
            {
                color.MoveNext();
                foreach (var loss in losses)
                {
                    var arrowHeight = loss.Scale(max, newMax);
                    var leftArrowBounds = new RectangleF(leftBounds.Left, leftY, leftBounds.Width, arrowHeight);
                    var rightArrowBounds = new RectangleF(rightBounds.Left, rightY, rightBounds.Width, arrowHeight);

                    var arrowPolygon = CreateLossesArrowPolygon(leftArrowBounds, rightArrowBounds);
                    graphics.FillPolygon(new SolidBrush(color.Current), arrowPolygon);
                    graphics.DrawPolygon(blackPen, arrowPolygon);

                    // write the percentages
                    var lossPercent = loss / totalLosses * 100;
                    graphics.DrawString($"{lossPercent:F0}%", GH_FontServer.Standard, blackBrush, leftArrowBounds,
                        format);

                    leftY += leftArrowBounds.Height + ArrowPadding;
                    rightY += rightArrowBounds.Height + rightArrowPadding;
                    color.MoveNext();
                }
            }
        }

19 View Source File : ControlsDrawing.cs
License : MIT License
Project Creator : arsium

private static void DrawSubItem(object sender,  DrawListViewSubItemEventArgs e)
        {
            //TextFormatFlags flags = TextFormatFlags.Left | TextFormatFlags.VerticalCenter;
            e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            e.Graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
            e.Graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
            e.Graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
            e.Graphics.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;

            using (StringFormat sf = new StringFormat())
            {
                sf.FormatFlags = StringFormatFlags.LineLimit | StringFormatFlags.FitBlackBox;
                sf.Alignment = StringAlignment.Near;
                sf.LineAlignment = StringAlignment.Center;

                if (e.Header.Index == 0 && ((ListView)sender).Name == "clientsListView")
                {
                    //TextRenderer.DrawText(e.Graphics, e.SubItem.Text, new Font(new FontFamily("Segoe UI"), (float)8.25, FontStyle.Regular), new Point(e.Bounds.X, e.Bounds.Y), e.Item.ForeColor);
                    e.Graphics.DrawString(e.SubItem.Text, new Font(new FontFamily("Segoe UI"), (float)8.25, FontStyle.Regular), new SolidBrush(e.Item.ForeColor), new RectangleF(e.Bounds.X + 28 , e.Bounds.Y, e.Bounds.Width, e.Bounds.Height), sf);
                }
                else
                {
                    //TextRenderer.DrawText(e.Graphics, e.SubItem.Text, new Font(new FontFamily("Segoe UI"), (float)8.25, FontStyle.Regular), new Point(e.Bounds.X, e.Bounds.Y), e.Item.ForeColor);
                    e.Graphics.DrawString(e.SubItem.Text, new Font(new FontFamily("Segoe UI"), (float)8.25, FontStyle.Regular), new SolidBrush(e.Item.ForeColor), new RectangleF(e.Bounds.X , e.Bounds.Y, e.Bounds.Width, e.Bounds.Height), sf);
                }  
                //e.DrawText(flags);        
            }
        }

19 View Source File : WindowsTabControls.cs
License : MIT License
Project Creator : arsium

private void PaintTabText(System.Drawing.Graphics graph, int index)
		{
			string tabtext = this.TabPages[index].Text;

			System.Drawing.StringFormat format = new System.Drawing.StringFormat();
			format.Alignment = StringAlignment.Near;
			format.LineAlignment = StringAlignment.Center;
			format.Trimming = StringTrimming.EllipsisCharacter;

			Brush forebrush = null;

			if (this.TabPages[index].Enabled == false)
			{
				forebrush = new SolidBrush(Color.DeepSkyBlue);
			}
			else
			{
				forebrush = new SolidBrush(COLOR_FORE_BASE);
			}

			Font tabFont = this.Font;
			if (index == this.SelectedIndex)
			{
				if (this.TabPages[index].Enabled != false)
				{
					forebrush = new SolidBrush(_headSelectedBackColor);
				}
			}

			Rectangle rect = this.GetTabRect(index);

			var txtSize = GetStringWidth(tabtext, graph, tabFont);
			//INSTANT VB WARNING: Instant VB cannot determine whether both operands of this division are integer types - if they are then you should use the VB integer division operator:
			Rectangle rect2 = new Rectangle(Convert.ToInt32(rect.Left + (rect.Width - txtSize) / 2.0 - 1), rect.Top, rect.Width, rect.Height);

			graph.DrawString(tabtext, tabFont, forebrush, rect2, format);
		}

19 View Source File : DropDownUIAttributes.cs
License : MIT License
Project Creator : arup-group

protected override void Render(GH_Canvas canvas, System.Drawing.Graphics graphics, GH_CanvasChannel channel)
        {
            base.Render(canvas, graphics, channel);

            if (channel == GH_CanvasChannel.Objects)
            {
                Pen spacer = new Pen(DropDownColours.SpacerColour);
                Pen pen = new Pen(DropDownColours.BorderColour)
                {
                    Width = 0.5f
                };

                Font sml = GH_FontServer.Small;
                // adjust fontsize to high resolution displays
                sml = new Font(sml.FontFamily, sml.Size / GH_GraphicsUtil.UiScale, FontStyle.Regular);

                for (int i = 0; i < dropdownlists.Count; i++)
                {
                    //Draw divider line
                    if (spacerTxts[i] != "")
                    {
                        graphics.DrawString(spacerTxts[i], sml, DropDownColours.AnnotationTextDark, SpacerBounds[i], GH_TextRenderingConstants.CenterCenter);
                        graphics.DrawLine(spacer, SpacerBounds[i].X, SpacerBounds[i].Y + SpacerBounds[i].Height / 2, SpacerBounds[i].X + (SpacerBounds[i].Width - GH_FontServer.StringWidth(spacerTxts[i], sml)) / 2 - 4, SpacerBounds[i].Y + SpacerBounds[i].Height / 2);
                        graphics.DrawLine(spacer, SpacerBounds[i].X + (SpacerBounds[i].Width - GH_FontServer.StringWidth(spacerTxts[i], sml)) / 2 + GH_FontServer.StringWidth(spacerTxts[i], sml) + 4, SpacerBounds[i].Y + SpacerBounds[i].Height / 2, SpacerBounds[i].X + SpacerBounds[i].Width, SpacerBounds[i].Y + SpacerBounds[i].Height / 2);
                    }

                    // Draw selected item
                    // set font and colour depending on inital or selected text
                    Font font = new Font(GH_FontServer.FamilyStandard, 7);
                    // adjust fontsize to high resolution displays
                    font = new Font(font.FontFamily, font.Size / GH_GraphicsUtil.UiScale, FontStyle.Regular);
                    Brush fontColour = DropDownColours.AnnotationTextDark;
                    if (initialTxts != null)
                    {
                        if (displayTexts[i] == initialTxts[i])
                        {
                            pen = new Pen(DropDownColours.BorderColour);
                            font = sml;
                            fontColour = Brushes.Gray;
                        }
                    }

                    // background
                    Brush background = new SolidBrush(Color.LightGray);
                    // background
                    graphics.FillRectangle(background, BorderBound[i]);
                    // border
                    graphics.DrawRectangle(pen, BorderBound[i].X, BorderBound[i].Y, BorderBound[i].Width, BorderBound[i].Height);
                    // text
                    graphics.DrawString(displayTexts[i], font, fontColour, TextBound[i], GH_TextRenderingConstants.NearCenter);
                    // draw dropdown arrow
                    DrawDropDownButton(graphics, new PointF(ButtonBound[i].X + ButtonBound[i].Width / 2, ButtonBound[i].Y + ButtonBound[i].Height / 2), Color.DarkGray, 15);

                    // draw dropdown list
                    font = new Font(GH_FontServer.FamilyStandard, 7);
                    // adjust fontsize to high resolution displays
                    font = new Font(font.FontFamily, font.Size / GH_GraphicsUtil.UiScale, FontStyle.Regular);
                    fontColour = DropDownColours.AnnotationTextDark;
                    if (unfolded[i])
                    {
                        Pen penborder = new Pen(Brushes.Gray);
                        Brush dropdownbackground = new SolidBrush(Color.LightGray);
                        penborder.Width = 0.3f;
                        for (int j = 0; j < dropdownBounds[i].Count; j++)
                        {
                            RectangleF lisreplacedem = dropdownBounds[i][j];
                            if (lisreplacedem.Y < dropdownBound[i].Y)
                            {
                                if (lisreplacedem.Y + lisreplacedem.Height < dropdownBound[i].Y)
                                {
                                    dropdownBounds[i][j] = new RectangleF();
                                    continue;
                                }
                                else
                                {
                                    lisreplacedem.Height = lisreplacedem.Height - (dropdownBound[i].Y - lisreplacedem.Y);
                                    lisreplacedem.Y = dropdownBound[i].Y;
                                    dropdownBounds[i][j] = lisreplacedem;
                                }
                            }
                            else if (lisreplacedem.Y + lisreplacedem.Height > dropdownBound[i].Y + dropdownBound[i].Height)
                            {
                                if (lisreplacedem.Y > dropdownBound[i].Y + dropdownBound[i].Height)
                                {
                                    dropdownBounds[i][j] = new RectangleF();
                                    continue;
                                }
                                else
                                {
                                    lisreplacedem.Height = dropdownBound[i].Y + dropdownBound[i].Height - lisreplacedem.Y;
                                    dropdownBounds[i][j] = lisreplacedem;
                                }
                            }

                            // background
                            graphics.FillRectangle(dropdownbackground, dropdownBounds[i][j]);
                            // border
                            graphics.DrawRectangle(penborder, dropdownBounds[i][j].X, dropdownBounds[i][j].Y, dropdownBounds[i][j].Width, dropdownBounds[i][j].Height);
                            // text
                            if (dropdownBounds[i][j].Height > 2)
                                graphics.DrawString(dropdownlists[i][j], font, fontColour, dropdownBounds[i][j], GH_TextRenderingConstants.NearCenter);
                        }
                        // border
                        graphics.DrawRectangle(pen, dropdownBound[i].X, dropdownBound[i].Y, dropdownBound[i].Width, dropdownBound[i].Height);

                        // draw vertical scroll bar
                        Brush scrollbar = new SolidBrush(Color.FromArgb(drag ? 160 : 120, Color.Black));
                        Pen scrollPen = new Pen(scrollbar);
                        scrollPen.Width = scrollBar.Width - 2;
                        scrollPen.StartCap = System.Drawing.Drawing2D.LineCap.Round;
                        scrollPen.EndCap = System.Drawing.Drawing2D.LineCap.Round;
                        graphics.DrawLine(scrollPen, scrollBar.X + 4, scrollBar.Y + 4, scrollBar.X + 4, scrollBar.Y + scrollBar.Height - 4);
                    }
                }
            }
        }

19 View Source File : SliderUIAttributes.cs
License : MIT License
Project Creator : arup-group

protected override void Render(GH_Canvas canvas, System.Drawing.Graphics graphics, GH_CanvasChannel channel)
        {
            base.Render(canvas, graphics, channel);

            if (channel == GH_CanvasChannel.Objects)
            {
                //Draw divider line
                if (SpacerTxt != "")
                {
                    Pen spacer = new Pen(SliderColours.SpacerColour);
                    Font sml = GH_FontServer.Small;
                    // adjust fontsize to high resolution displays
                    sml = new Font(sml.FontFamily, sml.Size / GH_GraphicsUtil.UiScale, FontStyle.Regular);

                    graphics.DrawString(SpacerTxt, sml, SliderColours.AnnotationTextDark, SpacerBounds, GH_TextRenderingConstants.CenterCenter);
                    graphics.DrawLine(spacer, SpacerBounds.X, SpacerBounds.Y + SpacerBounds.Height / 2, SpacerBounds.X + (SpacerBounds.Width - GH_FontServer.StringWidth(SpacerTxt, sml)) / 2 - 4, SpacerBounds.Y + SpacerBounds.Height / 2);
                    graphics.DrawLine(spacer, SpacerBounds.X + (SpacerBounds.Width - GH_FontServer.StringWidth(SpacerTxt, sml)) / 2 + GH_FontServer.StringWidth(SpacerTxt, sml) + 4, SpacerBounds.Y + SpacerBounds.Height / 2, SpacerBounds.X + SpacerBounds.Width, SpacerBounds.Y + SpacerBounds.Height / 2);
                }

                // draw drag line and intervals
                Pen line = new Pen(SliderColours.RailColour);
                graphics.DrawLine(line, new PointF(SliderBound.X + GrabBound.Width / 2, SliderBound.Y + SliderBound.Height / 2), new PointF(SliderBound.X + SliderBound.Width - GrabBound.Width / 2, SliderBound.Y + SliderBound.Height / 2));
                //graphics.DrawLine(line, new PointF(BorderBound.X + GrabBound.Width / 2, BorderBound.Y + BorderBound.Height / 3), new PointF(BorderBound.X + GrabBound.Width / 2, BorderBound.Y + BorderBound.Height * 2 / 3));
                //graphics.DrawLine(line, new PointF(BorderBound.X + BorderBound.Width - GrabBound.Width / 2, BorderBound.Y + BorderBound.Height / 3), new PointF(BorderBound.X + BorderBound.Width - GrabBound.Width / 2, BorderBound.Y + BorderBound.Height * 2 / 3));

                // draw grab item
                Pen pen = new Pen(SliderColours.DragElementEdge);
                pen.Width = 2f;
                RectangleF button = new RectangleF(GrabBound.X, GrabBound.Y, GrabBound.Width, GrabBound.Height);
                button.Inflate(-2, -2);
                Brush fill = new SolidBrush(SliderColours.DragElementFill);
                graphics.FillEllipse(fill, button);
                graphics.DrawEllipse(pen, button);

                // Draw display value text
                Font font = new Font(GH_FontServer.FamilyStandard, 7);
                // adjust fontsize to high resolution displays
                font = new Font(font.FontFamily, font.Size / GH_GraphicsUtil.UiScale, FontStyle.Regular);
                string val = string.Format(new System.Globalization.NumberFormatInfo() { NumberDecimalDigits = noDigits }, "{0:F}", new decimal(CurrentValue));

                graphics.DrawString(val, font, SliderColours.AnnotationTextDark, SliderValTextBound, ((CurrentValue - MinValue) / (MaxValue - MinValue) < 0.5) ? GH_TextRenderingConstants.NearCenter : GH_TextRenderingConstants.FarCenter);
            }
        }

19 View Source File : ButtonUIAttributes.cs
License : MIT License
Project Creator : arup-group

protected override void Render(GH_Canvas canvas, System.Drawing.Graphics graphics, GH_CanvasChannel channel)
        {
            base.Render(canvas, graphics, channel);

            if (channel == GH_CanvasChannel.Objects)
            {
                Pen spacer = new Pen(ButtonColours.SpacerColour);

                Font font = GH_FontServer.Standard;
                // adjust fontsize to high resolution displays
                font = new Font(font.FontFamily, font.Size / GH_GraphicsUtil.UiScale, FontStyle.Regular);

                Font sml = GH_FontServer.Small;
                // adjust fontsize to high resolution displays
                sml = new Font(sml.FontFamily, sml.Size / GH_GraphicsUtil.UiScale, FontStyle.Regular);

                //Draw divider line
                if (SpacerTxt != "")
                {
                    graphics.DrawString(SpacerTxt, sml, ButtonColours.AnnotationTextDark, SpacerBounds, GH_TextRenderingConstants.CenterCenter);
                    graphics.DrawLine(spacer, SpacerBounds.X, SpacerBounds.Y + SpacerBounds.Height / 2, SpacerBounds.X + (SpacerBounds.Width - GH_FontServer.StringWidth(SpacerTxt, sml)) / 2 - 4, SpacerBounds.Y + SpacerBounds.Height / 2);
                    graphics.DrawLine(spacer, SpacerBounds.X + (SpacerBounds.Width - GH_FontServer.StringWidth(SpacerTxt, sml)) / 2 + GH_FontServer.StringWidth(SpacerTxt, sml) + 4, SpacerBounds.Y + SpacerBounds.Height / 2, SpacerBounds.X + SpacerBounds.Width, SpacerBounds.Y + SpacerBounds.Height / 2);
                }

                // Draw button box
                System.Drawing.Drawing2D.GraphicsPath button = RoundedRect(ButtonBounds, 2);

                Brush normal_colour = ButtonColours.ButtonColor;
                Brush hover_colour = ButtonColours.HoverButtonColour;
                Brush clicked_colour = ButtonColours.ClickedButtonColour;

                Brush butCol = (mouseOver) ? hover_colour : normal_colour;
                graphics.FillPath(mouseDown ? clicked_colour : butCol, button);

                // draw button edge
                Color edgeColor = ButtonColours.BorderColour;
                Color edgeHover = ButtonColours.HoverBorderColour;
                Color edgeClick = ButtonColours.ClickedBorderColour;
                Color edgeCol = (mouseOver) ? edgeHover : edgeColor;
                Pen pen = new Pen(mouseDown ? edgeClick : edgeCol)
                {
                    Width = (mouseDown) ? 0.8f : 0.5f
                };
                graphics.DrawPath(pen, button);

                System.Drawing.Drawing2D.GraphicsPath overlay = RoundedRect(ButtonBounds, 2, true);
                graphics.FillPath(new SolidBrush(Color.FromArgb(mouseDown ? 0 : mouseOver ? 40 : 60, 255, 255, 255)), overlay);

                // draw button text
                graphics.DrawString(buttonText, font, ButtonColours.AnnotationTextBright, ButtonBounds, GH_TextRenderingConstants.CenterCenter);
            }
        }

19 View Source File : ProfileSelector.cs
License : MIT License
Project Creator : AstroTechies

private void ListBox1_DrawItem(object sender, DrawItemEventArgs e)
        {
            if (e.Index < 0) return;

            string decidedText = ((KeyValuePair<string, ModProfile>)listBox1.Items[e.Index]).Key;
            if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
            {
                e = new DrawItemEventArgs(e.Graphics, e.Font, e.Bounds, e.Index, e.State ^ DrawItemState.Selected, AMLPalette.ForeColor, AMLPalette.HighlightColor);
            }

            Rectangle decidedNewBounds = new Rectangle(e.Bounds.Location.X + (AMLPalette.BorderPenWidth / 2), e.Bounds.Location.Y + (AMLPalette.BorderPenWidth / 2), e.Bounds.Width - AMLPalette.BorderPenWidth, e.Bounds.Height);

            e.Graphics.FillRectangle(new SolidBrush(e.BackColor), decidedNewBounds);
            e.Graphics.DrawString(decidedText, e.Font, new SolidBrush(AMLPalette.ForeColor), decidedNewBounds, StringFormat.GenericDefault);
            if ((e.State & DrawItemState.Focus) == DrawItemState.Focus && (e.State & DrawItemState.NoFocusRect) != DrawItemState.NoFocusRect)
            {
                ControlPaint.DrawFocusRectangle(e.Graphics, decidedNewBounds, e.ForeColor, e.BackColor);
            }
        }

19 View Source File : TestForm.cs
License : MIT License
Project Creator : awaescher

private Bitmap RenderPreview(ListViewItem[] items)
        {
            var itemHeight = 23;
            var image = new Bitmap(120, itemHeight * items.Length);
            var borderBounds = new Rectangle(Point.Empty, image.Size);
            borderBounds.Width--;
            borderBounds.Height--;

            using (var graphics = Graphics.FromImage(image))
            {
                graphics.Clear(Color.White);
                graphics.DrawRectangle(Pens.Black, borderBounds);

                using (var format = new StringFormat())
                {
                    format.Alignment = StringAlignment.Near;
                    format.LineAlignment = StringAlignment.Center;
                    format.FormatFlags = StringFormatFlags.NoWrap;
                    format.Trimming = StringTrimming.EllipsisCharacter;

                    for (int i = 0; i < items.Length; i++)
                    {
                        var itemY = itemHeight * i;

                        var itemImage = imlSmall.Images[items[i].ImageIndex];
                        var imagePadding = (itemHeight - itemImage.Height) / 2;
                        graphics.DrawImage(itemImage, new Point(imagePadding, itemY + imagePadding));

                        var textX = itemImage.Width + imagePadding;
                        var textBounds = new Rectangle(textX, itemY, image.Width - textX, itemHeight);
                        graphics.DrawString(items[i].Text, listLeft.Font, Brushes.Black, textBounds, format);
                    }
                }
            }

            return image;
        }

19 View Source File : UpdatablePreview.cs
License : MIT License
Project Creator : awaescher

public void Render(Graphics graphics)
		{
			var bounds = new Rectangle(0, 20, _originalImage.Width, _originalImage.Height / 8);
			graphics.DrawImageUnscaled(_originalImage, new Rectangle(Point.Empty, PreferredSize));
			graphics.DrawString($"Distance: {_distance}px", _font, Brushes.White, bounds, _format);
		}

19 View Source File : PlotPane.cs
License : MIT License
Project Creator : azist

protected override void OnPaint(PaintEventArgs e)
    {
      //const int TXT_H_MARGIN = 8;

      var gr = e.Graphics;

      var lineWidth = m_Chart.VRulerWidth;
      // + TXT_H_MARGIN;// (int)(fSize.Width + TXT_H_MARGIN);//H margin
      var halfLineHeight = m_VLineSpaceHeight / 2;

      var rulerX = m_Chart.VRulerPosition == VRulerPosition.Right ? this.Width - lineWidth : 0;
      //Ruler bar
      gr.FillRectangle(m_Chart.RulerStyle.BackBrush, new Rectangle(rulerX, 0, lineWidth, Height));

      var pen = m_Chart.GridLinePen;
      var lineCount = this.Height/m_VLineSpaceHeight;
      var linePrice = (m_VRulerMaxScale - m_VRulerMinScale)/lineCount;

      var price = m_VRulerMinScale;
      var y = this.Height;
      while (y >= 0)
      {
        if (m_Chart.VRulerPosition == VRulerPosition.Right)
          gr.DrawLine(pen, 0, y, this.Width - lineWidth, y);
        else
          gr.DrawLine(pen, lineWidth, y, this.Right, y);

        gr.DrawString(scaleValueToString(price), m_Chart.RulerStyle.Font, m_Chart.RulerStyle.ForeBrush,
                      rulerX + (TimeSeriesChart.VRULLER_HPADDING/2), y - halfLineHeight + (VLINE_SPACE_PADDING/2));
        y     -= m_VLineSpaceHeight;
        price += linePrice;
      }

      using (var warpPen = getGridPen(m_Chart.GridLineTimeGapStyle))
      {
        foreach (var tick in m_Chart.m_TimeScalePane.Ticks)
        {
          if (tick.Warp)
          {
            gr.DrawLine(warpPen, tick.X - 1, 0, tick.X - 1, Height);
            gr.DrawLine(warpPen, tick.X + 1, 0, tick.X + 1, Height);
          }

          if (tick.DayChange)
            using (var dayChgPen = getGridPen(m_Chart.GridLineDayChangeStyle))
              gr.DrawLine(dayChgPen, tick.X, 0, tick.X, Height);
          else
            gr.DrawLine(pen, tick.X, 0, tick.X, Height);
        }
      }

      //Vertical cursor line
      gr.DrawLine(m_Chart.VCursorLinePen, m_Chart.m_TimeScalePane.MouseCursorX, 0,
                  m_Chart.m_TimeScalePane.MouseCursorX, Height);

      base.OnPaint(e);
    }

See More Examples