System.Drawing.Graphics.Clear(System.Drawing.Color)

Here are the examples of the csharp api System.Drawing.Graphics.Clear(System.Drawing.Color) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

625 Examples 7

19 Source : AreaForm.cs
with MIT License
from 1CM69

private void mouse_Click(object sender, MouseEventArgs e)
        {
      this.g.Clear(Color.FromArgb((int) byte.MaxValue, (int) byte.MaxValue, 192));
      this.LeftButtonDown = true;
      this.ClickPoint = new Point(Control.MousePosition.X, Control.MousePosition.Y);
      this.activated = false;
        }

19 Source : ExtendedSpinner.cs
with GNU General Public License v3.0
from a4004

protected override void OnPaint(PaintEventArgs e)
        {
            BufferedGraphicsContext bufferedGraphicsContext = BufferedGraphicsManager.Current;
            bufferedGraphicsContext.MaximumBuffer = new Size(Width + 1, Height + 1);

            gBuf = bufferedGraphicsContext.Allocate(CreateGraphics(), new Rectangle(0, 0, 1, 1));
            gBuf = bufferedGraphicsContext.Allocate(CreateGraphics(), ClientRectangle);

            gBuf.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
            gBuf.Graphics.InterpolationMode = InterpolationMode.HighQualityBilinear;
            gBuf.Graphics.CompositingQuality = CompositingQuality.HighQuality;
            gBuf.Graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
            gBuf.Graphics.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;

            if (BackgroundImage == null)
                gBuf.Graphics.Clear(BackColor);
            else
                gBuf.Graphics.DrawImage(BackgroundImage, 0, 0);

            Rectangle rect = new Rectangle(_thickness / 2 + 1, _thickness / 2 + 1, Width - _thickness - 2, Height - _thickness - 2);

            if (_backThick > 0)
                gBuf.Graphics.DrawArc(new Pen(_bkcolor, _backThick), rect, 0f, 360f);

            if (_gradient)
                gBuf.Graphics.DrawArc(new Pen(new LinearGradientBrush(DisplayRectangle, _colorOne, _colorTwo, 180f), _thickness), rect, _angle, _value * 3.6f);
            else
            {
                if (_trail)
                {
                    float constant = 0.0140625f;

                    for (int i = 0; i < 255; i++)
                        gBuf.Graphics.DrawArc(new Pen(Color.FromArgb(i, _color), _thickness), rect, _angle + (_value * (constant * i)), _value * constant);
                }
                else
                    gBuf.Graphics.DrawArc(new Pen(_color, _thickness), rect, _angle, _value * 3.6f);
            }

            gBuf.Render(e.Graphics);

            base.OnPaint(e);
        }

19 Source : ImageHack.cs
with MIT License
from Aeroblast

public static byte[] Warmer(byte[] data)
        {
            if (!prepared) PrepareWarmer();
            using (Bitmap b = new Bitmap(new MemoryStream(data)))
            using (Bitmap r = new Bitmap(b.Width, b.Height, PixelFormat.Format32bppArgb))
            using (Graphics g = Graphics.FromImage(r))
            {
                g.Clear(Color.Transparent);
                g.DrawImage(b, new Rectangle(0, 0, b.Width, b.Height), 0, 0, b.Width, b.Height, GraphicsUnit.Pixel, imageAttributes);
                var output = new MemoryStream();
                r.Save(output, ImageFormat.Bmp);
                return output.ToArray();
            }
        }

19 Source : ColorPicker.cs
with GNU General Public License v3.0
from aglab2

private void pictureBox1_Click(object sender, EventArgs e)
        { 
            double expectedHue = (double)picX / pictureBox.Width;
            double expectedVal = (double)picY / pictureBox.Height;

            pickedColor = ColorRGB.HSL2RGB(expectedHue, 1, expectedVal);

            for (int i = 0; i < img.Width; i++)
            {
                for (int j = 0; j < img.Height; j++)
                {
                    Color c = img.GetPixel(i, j);
                    ColorRGB.RGB2HSL(new ColorRGB(c), out double h, out double s, out double v);
                    h += expectedHue - midHue;
                    if (h < 0) h += 1;
                    if (h > 1) h -= 1;

                    Color o = ColorRGB.HSL2RGB(h, s, v);
                    Color oa = Color.FromArgb(c.A, o.R, o.G, o.B);

                    newImg.SetPixel(i, j, oa);
                }
            }

            Graphics graphics = starPicture.CreateGraphics();
            graphics.Clear(Color.Black);
            graphics.DrawImage(newImg, 0, 0, 220, 220);
        }

19 Source : ColorPicker.cs
with GNU General Public License v3.0
from aglab2

private void pictureBox_MouseMove(object sender, MouseEventArgs e)
        {
            picX = e.X; picY = e.Y;
            if (e.Button != MouseButtons.Left) return;

            Bitmap img = ld.goldStar;
            
            double expectedHue = (double) e.X / pictureBox.Width;
            double expectedVal = (double) e.Y / pictureBox.Height;

            pickedColor = ColorRGB.HSL2RGB(expectedHue, 1, expectedVal);

            for (int i = 0; i < img.Width; i++)
            {
                for (int j = 0; j < img.Height; j++)
                {
                    Color c = img.GetPixel(i, j);
                    ColorRGB.RGB2HSL(new ColorRGB(c), out double h, out double s, out double v);
                    h += expectedHue - midHue;
                    if (h < 0) h += 1;
                    if (h > 1) h -= 1;

                    Color o = ColorRGB.HSL2RGB(h, s, v);
                    Color oa = Color.FromArgb(c.A, o.R, o.G, o.B);

                    newImg.SetPixel(i, j, oa);
                }
            }

            Graphics graphics = starPicture.CreateGraphics();
            graphics.Clear(Color.Black);
            graphics.DrawImage(newImg, 0, 0, 220, 220);
        }

19 Source : MainWindow.cs
with GNU General Public License v3.0
from aglab2

private void DrawIntro()
        {
            menuStrip.Enabled = false;

            //Steps to achieve success here!
            baseImage = new Bitmap(starPicture.Width, starPicture.Height);
            Graphics baseGraphics = Graphics.FromImage(baseImage);
            baseGraphics.Clear(Color.Black);
            baseGraphics.TextRenderingHint = TextRenderingHint.AntiAlias;
            gm.graphics = Graphics.FromImage(baseImage);

            gm.DrawIntro(isEmulatorStarted, isHackLoaded, isOffsetsFound);
            baseGraphics.Dispose();
            starPicture.Image = baseImage;
        }

19 Source : MainWindow.cs
with GNU General Public License v3.0
from aglab2

private void UpdateStars(object sender)
        {
            isEmulatorStarted = false;
            isHackLoaded = false;
            isOffsetsFound = false;

            try
            {
                if (um.IsCompleted())
                {
                    if (!isUpdateRequested && !um.IsUpdated())
                    {
                        isUpdateRequested = true;
                        this.SafeInvoke((MethodInvoker)delegate
                        {
                            DialogResult result = MessageBox.Show(String.Format("Update for Star Display available!\n\n{0}\nDo you want to download it now? Press cancel to skip update", um.UpdateName()), "Update",
                            MessageBoxButtons.YesNoCancel, MessageBoxIcon.Asterisk);
                            if (result == DialogResult.Yes)
                            {
                                Process.Start(um.DownloadPath());
                            }
                            if (result == DialogResult.Cancel)
                            {
                                um.WritebackUpdate();
                            }
                        });
                    }
                }
            }
            catch (Exception) { }

            try
            {
                //if (slf != null && slf.sm != null && slf.sm.isServer)
                //    goto bla;

                if (mm.ProcessActive())
                {
                    this.SafeInvoke((MethodInvoker)delegate { DrawIntro(); ResetForm(); });
                    return;
                }
                
                isEmulatorStarted = true;

                // Well, that's just a minor magic but it works
                if (mm.Getreplacedle().Contains("-"))
                    isHackLoaded = true;

                if (!mm.isMagicDone())
                {
                    if (magicThread == null || !magicThread.IsAlive)
                    {
                        magicThread = new Thread(doMagicThread);
                        magicThread.Start();
                    }

                    this.SafeInvoke((MethodInvoker)delegate { DrawIntro(); });
                    return;
                }
                
                isOffsetsFound = true;


                try
                {
                    // Just do nothing
                    if (!mm.isReadyToRead())
                        return;

                    mm.PerformRead();
                }
                catch (Exception)
                {
                    this.SafeInvoke((MethodInvoker)delegate { DrawIntro(); ResetForm(); });
                    return;
                }
 
                bool mmIsInvalidated = mm == null ? false : mm.CheckInvalidated();
                bool gmIsInvalidated = gm == null ? false : gm.CheckInvalidated();
                bool dmIsInvalidated = dm == null ? false : dm.CheckInvalidated();
                bool smIsInvalidated = false;
                if (slf != null && slf.sm != null)
                    smIsInvalidated = slf.sm.CheckInvalidated();

                bool nmIsInvalidated = false;
                if (slf != null && slf.nm != null)
                    nmIsInvalidated = slf.nm.CheckInvalidated();

                if (smIsInvalidated && slf.sm.dropFile)
                {
                    slf.sm.dropFile = false;
                    mm.Stars = new byte[MemoryManager.FileLength];
                    mm.WriteToFile(ld.starsShown);
                    mm.isStarsInvalidated = true;
                }

                if (mmIsInvalidated && mm.isStarsInvalidated)
                {
                    mm.isStarsInvalidated = false;
                    if (slf != null && slf.sm != null)
                    {
                        slf.sm.SendData(mm.Stars);
                    }

                    Console.WriteLine("MM Invalidated!");
                }

                if (gmIsInvalidated)
                    Console.WriteLine("GM Invalidated!");
                if (dmIsInvalidated)
                    Console.WriteLine("DM Invalidated!");

                if (smIsInvalidated)
                {
                    Console.WriteLine("SM Invalidated!");
                    {
                        byte[] stars = slf.sm.AcquiredData;

                        bool shouldSendHelp = false;
                        for (int i = 0; i < stars.Count(); i++)
                        {
                            byte diff = (byte)(mm.Stars[i] ^ stars[i]);
                            if ((mm.Stars[i] & diff) != 0)
                                shouldSendHelp = true;

                            otherStars[i] |= (byte)(diff & stars[i]);
                            mm.Stars[i] = (byte)(mm.Stars[i] | stars[i]);
                        }

                        if (shouldSendHelp)
                        {
                            slf.sm.SendData(mm.Stars);
                        }

                        mm.WriteToFile(ld.starsShown);
                    }
                    if (!mm.IsDecomp)
                    {
                        var location = mm.GetLocation();
                        var netData = slf.sm.getNetData();
                        foreach (var item in netData)
                        {
                            var player = item.Key;
#if DEBUG == false
                            if (player != slf.GetPlayerName())
#endif
                            {
                                var data = item.Value;

                                if (slf is object && slf.nm is object)
                                {
                                    var id = slf.nm.RegisterPlayer(player);
                                    if (data.location == location)
                                        mm.WriteNetState(id, data.state);
                                    else
                                        mm.WriteNetState(id, null);
                                }
                            }
                        }
                    }
                }

                if (nmIsInvalidated)
                {
                    if (!mm.IsDecomp)
                    {
                        mm.WriteNetPatch();
                        var state = mm.GetMarioState();
                        if (slf.sm is object)
                        {
                            slf.sm.SendNet64Data(slf.GetNet64Name(), state, mm.GetLocation());
                        }

                        if (slf.nm.mustReload)
                        {
                            for (int i = 0; i < 16; i++)
                            {
                                mm.WriteNetState(i, null);
                            }
                            slf.nm.mustReload = false;
                        }

                        this.SafeInvoke((MethodInvoker)delegate { slf.UpdatePlayers(slf.nm.GetPlayers()); });
                    }
                }

                // We do not draw anything!
                if (!mmIsInvalidated && !gmIsInvalidated && !smIsInvalidated && !dmIsInvalidated)
                {
                    return;
                }

                gm.TestFont();

                if (enableAutoDeleteToolStripMenuItem.Checked)
                {
                    try
                    {
                        mm.DeleteStars();
                    }
                    catch (IOException)
                    {
                        MessageBox.Show("Can not modify savefiles. Trying launching with elevated rights!", "Write Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        enableAutoDeleteToolStripMenuItem.Checked = false;
                    }
                }

                //Display stars routine
                baseImage = new Bitmap(starPicture.Width, starPicture.Width * 4);

                Graphics baseGraphics = Graphics.FromImage(baseImage);
                baseGraphics.Clear(Color.Black);
                baseGraphics.TextRenderingHint = TextRenderingHint.AntiAlias;
                gm.graphics = Graphics.FromImage(baseImage);

                if (!sm.GetConfig(MainWindowsSettingsAction.collectablesOnlyConfigureName, false))
                {
                    TextHighlightAction act = mm.GetCurrentLineAction(ld);
                    if (act != null)
                    {
                        gm.AddLineHighlight(act);
                    }
                }

                UInt16 currentCRC = mm.GetRomCRC();
                if (currentCRC != oldCRC || rm == null || dmIsInvalidated)
                {
                    oldCRC = currentCRC;
                    try
                    {
                        rm = new ROMManager(mm.GetROM());
                        try
                        {
                            if (dm != null)
                            {
                                dm.GetData();
                            }

                            string exePath = Path.GetDirectoryName(replacedembly.GetEntryreplacedembly().Location);
                            LoadLayoutNoInvalidate(exePath + "\\layout\\" + rm.GetROMName() + ".jsml", false);
                        }
                        catch (IOException)
                        {
                            try
                            {
                                dm = new DownloadManager(rm.GetROMName() + ".jsml");
                            }
                            catch(Exception) { }
                            LoadDefaultLayoutNoInvalidate();
                        }

                        gm.IsFirstCall = true;
                    }
                    catch (IndexOutOfRangeException) //can be generated by box reader
                    { }
                    catch (Exception)
                    { oldCRC = 0; }

                    InvalidateCache();
                }

                int lineOffset = 0;
                var actions = sm.GetConfig(MainWindowsSettingsAction.collectablesOnlyConfigureName, false) ?
                    mm.GetCollectablesOnlyDrawActions(ld, rm) : 
                    mm.GetDrawActions(ld, rm, enableLockoutToolStripMenuItem.Checked ? otherStars : null);

                if (actions == null) return;

                foreach (var entry in actions)
                {
                    lineOffset += entry.Execute(gm, lineOffset, sm);
                }
                
                baseGraphics.Dispose();
                this.SafeInvoke(delegate {
                    menuStrip.Enabled = true;
                    starPicture.Image = baseImage;
                    starPicture.Height = (int) (lineOffset * gm.SHeight) + 10;
                    this.Height = (int)(lineOffset * gm.SHeight) + 48;
                });
            }
            catch (Win32Exception)
            {
                this.SafeInvoke((MethodInvoker)delegate { ResetForm(); DrawIntro(); });
            }
            catch (NullReferenceException)
            {
                this.SafeInvoke((MethodInvoker)delegate { ResetForm(); DrawIntro(); });
            }
            catch (ObjectDisposedException)
            {
            }
            finally
            {
                int period = (isEmulatorStarted && isHackLoaded && isOffsetsFound) ? updatePeriod : scanPeriod;
                timer.Change(period, Timeout.Infinite);
            }
        }

19 Source : Graphics.cs
with Mozilla Public License 2.0
from ahyahy

public void Clear(Color p1)
        {
            M_Graphics.Clear(p1.M_Color);
            System.Windows.Forms.Application.DoEvents();
        }

19 Source : ImageMaker.cs
with GNU General Public License v3.0
from akaAgar

internal byte[] GetImageBytes(params ImageMakerLayer[] imageLayers)
        {
            Bitmap bitmap = new Bitmap(ImageSizeX, ImageSizeY);
            using (Graphics graphics = Graphics.FromImage(bitmap))
            {
                graphics.Clear(BackgroundColor);

                // Draw all layers of the image
                foreach (ImageMakerLayer layer in imageLayers)
                {
                    string filePath = $"{BRPaths.INCLUDE_JPG}{layer.FileName}";
                    if (!File.Exists(filePath)) continue; // File doesn't exist, ignore it.

                    using (Image layerImage = Image.FromFile(filePath))
                    {
                        Point position = GetImagePosition(layer, layerImage.Size);

                        RotateGraphics(graphics, layer.Rotation);
                        graphics.DrawImage(layerImage,
                                new Rectangle(position, new Size((int)(layerImage.Size.Width * layer.Scale), (int)(layerImage.Size.Height * layer.Scale))),
                                new Rectangle(Point.Empty, layerImage.Size),
                                GraphicsUnit.Pixel);
                        RotateGraphics(graphics, -layer.Rotation);
                    }
                }

                // Draw the text overlay
                TextOverlay.Draw(graphics);
            }

            // Coverts the image to a JPG and get all bytes
            byte[] bytes;
            using (var ms = new MemoryStream())
            {
                bitmap.Save(ms, ImageFormat.Jpeg);
                bytes = ms.ToArray();
            }

            return bytes;
        }

19 Source : DynamicTextImage.cs
with MIT License
from 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 Source : SensorNotifyIcon.cs
with MIT License
from AlexGyver

private Icon CreatePercentageIcon() {      
      try {
        graphics.Clear(Color.Transparent);
      } catch (ArgumentException) {
        graphics.Clear(Color.Black);
      }
      graphics.FillRectangle(darkBrush, 0.5f, -0.5f, bitmap.Width - 2, bitmap.Height);
      float value = sensor.Value.GetValueOrDefault();
      float y = 0.16f * (100 - value);
      graphics.FillRectangle(brush, 0.5f, -0.5f + y, bitmap.Width - 2, bitmap.Height - y);
      graphics.DrawRectangle(pen, 1, 0, bitmap.Width - 3, bitmap.Height - 1);

      BitmapData data = bitmap.LockBits(
        new Rectangle(0, 0, bitmap.Width, bitmap.Height),
        ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
      byte[] bytes = new byte[bitmap.Width * bitmap.Height * 4];
      Marshal.Copy(data.Scan0, bytes, 0, bytes.Length);
      bitmap.UnlockBits(data);

      return IconFactory.Create(bytes, bitmap.Width, bitmap.Height, 
        PixelFormat.Format32bppArgb);
    }

19 Source : ImageCreator.cs
with GNU General Public License v3.0
from alexgracianoarj

public static void CopyAsImage(IPrintable doreplacedent, bool selectedOnly)
		{
			if (doreplacedent == null)
				throw new ArgumentNullException("doreplacedent");

			RectangleF areaF = doreplacedent.GetPrintingArea(true);
			areaF.Offset(0.5F, 0.5F);
			Rectangle area = Rectangle.FromLTRB((int) areaF.Left, (int) areaF.Top,
				(int) Math.Ceiling(areaF.Right), (int) Math.Ceiling(areaF.Bottom));

			using (Bitmap image = new Bitmap(area.Width, area.Height, PixelFormat.Format24bppRgb))
			using (Graphics g = Graphics.FromImage(image))
			{
				// Set drawing parameters
				g.SmoothingMode = SmoothingMode.HighQuality;
				if (DiagramEditor.Settings.Default.UseClearTypeForImages)
					g.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
				else
					g.TextRenderingHint = TextRenderingHint.SingleBitPerPixelGridFit;
				g.TranslateTransform(-area.Left, -area.Top);

				// Draw image
				g.Clear(Style.CurrentStyle.BackgroundColor);
				IGraphics graphics = new GdiGraphics(g);
				doreplacedent.Print(graphics, selectedOnly, Style.CurrentStyle);

				try
				{
					System.Windows.Forms.Clipboard.SetImage(image);
				}
				catch
				{
					//UNDONE: exception handling of CopyAsImage()
				}
			}
		}

19 Source : SensorNotifyIcon.cs
with MIT License
from AlexGyver

private Icon CreateTransparentIcon() {
      string text = GetString();
      int count = 0;
      for (int i = 0; i < text.Length; i++)
        if ((text[i] >= '0' && text[i] <= '9') || text[i] == '-')
          count++;
      bool small = count > 2;

      graphics.Clear(Color.Black);
      TextRenderer.DrawText(graphics, text, small ? smallFont : font,
        new Point(-2, small ? 1 : 0), Color.White, Color.Black);        

      BitmapData data = bitmap.LockBits(
        new Rectangle(0, 0, bitmap.Width, bitmap.Height),
        ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);

      IntPtr Scan0 = data.Scan0;

      int numBytes = bitmap.Width * bitmap.Height * 4;
      byte[] bytes = new byte[numBytes];
      Marshal.Copy(Scan0, bytes, 0, numBytes);
      bitmap.UnlockBits(data);

      byte red, green, blue;
      for (int i = 0; i < bytes.Length; i += 4) {
        blue = bytes[i];
        green = bytes[i + 1];
        red = bytes[i + 2];

        bytes[i] = color.B;
        bytes[i + 1] = color.G;
        bytes[i + 2] = color.R;
        bytes[i + 3] = (byte)(0.3 * red + 0.59 * green + 0.11 * blue);
      }

      return IconFactory.Create(bytes, bitmap.Width, bitmap.Height, 
        PixelFormat.Format32bppArgb);
    }

19 Source : TreeViewAdv.Input.cs
with MIT License
from AlexGyver

private void CreateDragBitmap(IDataObject data)
		{
			if (UseColumns || !DisplayDraggingNodes)
				return;

			TreeNodeAdv[] nodes = data.GetData(typeof(TreeNodeAdv[])) as TreeNodeAdv[];
			if (nodes != null && nodes.Length > 0)
			{
				Rectangle rect = DisplayRectangle;
				Bitmap bitmap = new Bitmap(rect.Width, rect.Height);
				using (Graphics gr = Graphics.FromImage(bitmap))
				{
					gr.Clear(BackColor);
					DrawContext context = new DrawContext();
					context.Graphics = gr;
					context.Font = Font;
					context.Enabled = true;
					int y = 0;
					int maxWidth = 0;
					foreach (TreeNodeAdv node in nodes)
					{
						if (node.Tree == this)
						{
							int x = 0;
							int height = _rowLayout.GetRowBounds(node.Row).Height;
							foreach (NodeControl c in NodeControls)
							{
								Size s = c.GetActualSize(node, context);
								if (!s.IsEmpty)
								{
									int width = s.Width;
									rect = new Rectangle(x, y, width, height);
									x += (width + 1);
									context.Bounds = rect;
									c.Draw(node, context);
								}
							}
							y += height;
							maxWidth = Math.Max(maxWidth, x);
						}
					}

					if (maxWidth > 0 && y > 0)
					{
						_dragBitmap = new Bitmap(maxWidth, y, PixelFormat.Format32bppArgb);
						using (Graphics tgr = Graphics.FromImage(_dragBitmap))
							tgr.DrawImage(bitmap, Point.Empty);
						BitmapHelper.SetAlphaChanelValue(_dragBitmap, 150);
					}
					else
						_dragBitmap = null;
				}
			}
		}

19 Source : ImageCreator.cs
with GNU General Public License v3.0
from alexgracianoarj

private static void SaveAsImage(IPrintable doreplacedent, string path,
			ImageFormat format, bool selectedOnly, bool transparent)
		{
			const int Margin = 20;

			RectangleF areaF = doreplacedent.GetPrintingArea(selectedOnly);
			areaF.Offset(0.5F, 0.5F);
			Rectangle area = Rectangle.FromLTRB((int) areaF.Left, (int) areaF.Top,
				(int) Math.Ceiling(areaF.Right), (int) Math.Ceiling(areaF.Bottom));

			if (format == ImageFormat.Emf) // Save to metafile
			{
				Graphics metaG = control.CreateGraphics();
				IntPtr hc = metaG.GetHdc();
				Graphics g = null;

				try
				{
					// Set drawing parameters
					Metafile meta = new Metafile(path, hc);
					g = Graphics.FromImage(meta);
					g.SmoothingMode = SmoothingMode.HighQuality;
					if (DiagramEditor.Settings.Default.UseClearTypeForImages)
						g.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
					else
						g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
					g.TranslateTransform(-area.Left, -area.Top);

					// Draw image
					IGraphics graphics = new GdiGraphics(g);
					doreplacedent.Print(graphics, selectedOnly, Style.CurrentStyle);

					meta.Dispose();
				}
				catch (Exception ex)
				{
					MessageBox.Show(
						string.Format("{0}\n{1}: {2}", Strings.ErrorInSavingImage,
							Strings.ErrorsReason, ex.Message),
						Strings.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
				}
				finally
				{
					metaG.ReleaseHdc();
					metaG.Dispose();
					if (g != null)
						g.Dispose();
				}
			}
			else // Save to rastered image
			{
				int width = area.Width + Margin * 2;
				int height = area.Height + Margin * 2;
				PixelFormat pixelFormat;

				if (transparent)
					pixelFormat = PixelFormat.Format32bppArgb;
				else
					pixelFormat = PixelFormat.Format24bppRgb;

				using (Bitmap image = new Bitmap(width, height, pixelFormat))
				using (Graphics g = Graphics.FromImage(image))
				{
					// Set drawing parameters
					g.SmoothingMode = SmoothingMode.HighQuality;
					if (DiagramEditor.Settings.Default.UseClearTypeForImages && !transparent)
						g.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
					else
						g.TextRenderingHint = TextRenderingHint.SingleBitPerPixelGridFit;
					g.TranslateTransform(Margin - area.Left, Margin - area.Top);

					// Draw image
					if (!transparent)
						g.Clear(Style.CurrentStyle.BackgroundColor);

					IGraphics graphics = new GdiGraphics(g);
					doreplacedent.Print(graphics, selectedOnly, Style.CurrentStyle);

					try
					{
						image.Save(path, format);
					}
					catch (Exception ex)
					{
						MessageBox.Show(
							string.Format("{0}\n{1}: {2}", Strings.ErrorInSavingImage,
								Strings.ErrorsReason, ex.Message),
							Strings.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
					}
				}
			}
		}

19 Source : SensorGadget.cs
with MIT License
from 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 Source : ImageMetaData.cs
with Apache License 2.0
from alibaba

public Image GetImg()
        {
            Image tmp_img = null;
            if (null == img)
            {
                try
                {
                    img = Image.FromFile(path);
                    ratio = 1.0f;
                    height = img.Height;
                    width = img.Width;
                    //MessageBox.Show(MainForm.maxH.ToString() + "," + MainForm.maxW.ToString());

                    if (1.0 * height / (MainForm.maxH-2*extend) > 1.0 * width / (MainForm.maxW-2*extend))
                    {
                        if (height > (MainForm.maxH-2*extend))
                        {
                            ratio = 1.0f * (MainForm.maxH-2*extend) / height;
                        }
                    }
                    else
                    {
                        if (width > (MainForm.maxW-2*extend))
                        {
                            ratio = 1.0f * (MainForm.maxW-2*extend) / width;
                        }
                    }
                    //tmp_img = (Bitmap)img.Clone();

                    if (ratio < 1.0f)
                    {
                        //MessageBox.Show("ERROR");
                        Image souImg = img;
                        h = Convert.ToInt32(ratio * height);
                        w = Convert.ToInt32(ratio * width);
                        tmp_img = new Bitmap(w+2*extend, h+2*extend);
                        //MessageBox.Show((h+extend).ToString() + "," + (w+extend).ToString());
                        Graphics g = Graphics.FromImage(tmp_img);
                        g.Clear(Color.White);
                        g.InterpolationMode = InterpolationMode.High;
                        g.SmoothingMode = SmoothingMode.HighQuality;
                        g.DrawImage(souImg, new Rectangle(extend, extend, w, h), new Rectangle(0, 0, width, height), GraphicsUnit.Pixel);
                    }
                    else
                    {
                        Image souImg = img;
                        h = height;
                        w = width;
                        //MessageBox.Show(h.ToString()+","+w.ToString());
                        tmp_img = new Bitmap(w + 2 * extend, h + 2 * extend);
                        Graphics g = Graphics.FromImage(tmp_img);
                        g.Clear(Color.White);
                        g.DrawImage(souImg, new Rectangle(extend, extend, w, h), new Rectangle(0, 0, width, height), GraphicsUnit.Pixel);
                    }
                }
                catch
                {
                    img = null;
                }
            }
            img.Dispose();
            img = null;
            return tmp_img;
        }

19 Source : MainForm.cs
with Apache License 2.0
from alibaba

private void Confirm_Click(object sender, EventArgs e)
        {
            buffer[index] = new Poly(clkpoint, ang);
            ++index;
            Zoom f = new Zoom(index);       
            f.mf = this;
            Image img = new Bitmap(800,600);
            Image org = new Bitmap(rgIMD[cur].GetImg());
            Graphics g = Graphics.FromImage(img);
            int lx, rx, ly, ry;
            double ra, rax, ray;
            lx = Math.Min(newpoint[0].X, newpoint[1].X); lx = Math.Min(lx, newpoint[2].X); lx = Math.Min(lx, newpoint[3].X);
            rx = Math.Max(newpoint[0].X, newpoint[1].X); rx = Math.Max(rx, newpoint[2].X); rx = Math.Max(rx, newpoint[3].X);
            ly = Math.Min(newpoint[0].Y, newpoint[1].Y); ly = Math.Min(ly, newpoint[2].Y); ly = Math.Min(ly, newpoint[3].Y);
            ry = Math.Max(newpoint[0].Y, newpoint[1].Y); ry = Math.Max(ry, newpoint[2].Y); ry = Math.Max(ry, newpoint[3].Y);
            rax = 800.0 / (double)(rx - lx);
            ray = 600.0 / (double)(ry - ly);
            ra = Math.Min(rax, ray);
            g.Clear(Color.White);
            g.InterpolationMode = InterpolationMode.High;
            g.SmoothingMode = SmoothingMode.HighQuality;
            g.DrawImage(org, new Rectangle(0, 0, (int)(ra*(rx-lx)), (int)(ra*(ry-ly))), new Rectangle(lx,ly,rx-lx,ry-ly), GraphicsUnit.Pixel);
            f.setdata(ra,lx,ly);
            f.Zoompicbox.Image = img;
            f.Show();
            AddPoly();
            selected = -1;
            OperateClick();
        }

19 Source : MainForm.cs
with Apache License 2.0
from alibaba

private void edittext_Click(object sender, EventArgs e)
        {
            Zoom f = new Zoom(selected + 1);
            f.mf = this;
            Image img = new Bitmap(800, 600);
            Image org = new Bitmap(rgIMD[cur].GetImg());
            Graphics g = Graphics.FromImage(img);
            int lx, rx, ly, ry;
            double ra, rax, ray;
            Point[] newp = new Point[4];
            newp[0] = new Point(buffer[selected].rgP[0].X, buffer[selected].rgP[0].Y);
            newp[2] = new Point(buffer[selected].rgP[1].X, buffer[selected].rgP[1].Y);
            if (buffer[selected].angle == 0 || buffer[selected].angle == 90 || buffer[selected].angle == -90)
            {
                newp[1] = new Point(newp[0].X, newp[2].Y);
                newp[3] = new Point(newp[2].X, newp[0].Y);
            }
            else
            {
                double alp = buffer[selected].angle / 180.0 * Math.PI;
                double beta = Math.Atan2((double)(newp[2].Y - newp[0].Y), (double)(newp[2].X - newp[0].X));
                double le = Math.Sqrt((newp[2].Y - newp[0].Y) * (newp[2].Y - newp[0].Y) + (newp[2].X - newp[0].X) * (newp[2].X - newp[0].X));
                int mx = (int)(le * Math.Cos(alp - beta) * Math.Cos(alp));
                int my = (int)(le * Math.Cos(alp - beta) * Math.Sin(alp));
                newp[1] = new Point(newp[0].X + mx, newp[0].Y + my);
                newp[3] = new Point(newp[2].X - mx, newp[2].Y - my);
            }
            lx = Math.Min(newp[0].X, newp[1].X); lx = Math.Min(lx, newp[2].X); lx = Math.Min(lx, newp[3].X);
            rx = Math.Max(newp[0].X, newp[1].X); rx = Math.Max(rx, newp[2].X); rx = Math.Max(rx, newp[3].X);
            ly = Math.Min(newp[0].Y, newp[1].Y); ly = Math.Min(ly, newp[2].Y); ly = Math.Min(ly, newp[3].Y);
            ry = Math.Max(newp[0].Y, newp[1].Y); ry = Math.Max(ry, newp[2].Y); ry = Math.Max(ry, newp[3].Y);
            rax = 800.0 / (double)(rx - lx);
            ray = 600.0 / (double)(ry - ly);
            ra = Math.Min(rax, ray);
            g.Clear(Color.White);
            g.InterpolationMode = InterpolationMode.High;
            g.SmoothingMode = SmoothingMode.HighQuality;
            g.DrawImage(org, new Rectangle(0, 0, (int)(ra * (rx - lx)), (int)(ra * (ry - ly))), new Rectangle(lx, ly, rx - lx, ry - ly), GraphicsUnit.Pixel);
            f.setdata(ra, lx, ly);
            f.setstr(buffer[selected].name);
            f.Zoompicbox.Image = img;
            f.Show();
            selected = -1;
            OperateClick();
        }

19 Source : DetectNativeTest.cs
with MIT License
from AlturosDestinations

[TestMethod]
        public void DetectNative()
        {
            var configuration = new YoloConfigurationDetector().Detect();
            using (var yoloWrapper = new YoloWrapper(configuration))
            {
                using (var image = new Bitmap(600, 400))
                using (var canvas = Graphics.FromImage(image))
                {
                    canvas.Clear(Color.AliceBlue);
                    canvas.FillPie(Brushes.Black, 0, 0, 100, 100, 0, 360);
                    canvas.Flush();

                    BitmapData bmpdata = null;
                    bmpdata = image.LockBits(new Rectangle(0, 0, image.Width, image.Height),
                        ImageLockMode.ReadOnly,
                        image.PixelFormat);

                    var rawImagePtr = bmpdata.Scan0;
                    var bmpImagePtr = IntPtr.Zero;

                    try
                    {
                        bmpImagePtr = CreateBmp(rawImagePtr, image.Width, image.Height, out var length);
                        var result = yoloWrapper.Detect(bmpImagePtr, length);
                    }
                    finally
                    {
                        if (bmpImagePtr != IntPtr.Zero)
                        {
                            Marshal.FreeHGlobal(bmpImagePtr);
                        }
                    }
                }
            }
        }

19 Source : DrawHelper.cs
with MIT License
from AlturosDestinations

public static Image DrawBoxes(AnnotationImage image)
        {
            try
            {
                var originalBitmap = new Bitmap(image.ImagePath);

                var newImageSize = new Size(originalBitmap.Width, originalBitmap.Height);
                if (originalBitmap.Width > ImageSize.Width)
                {
                    newImageSize.Height = (int)(originalBitmap.Height * (ImageSize.Width / (double)originalBitmap.Width));
                    newImageSize.Width = ImageSize.Width;
                }
                if (originalBitmap.Height > ImageSize.Height)
                {
                    newImageSize.Width = (int)(originalBitmap.Width * (ImageSize.Height / (double)originalBitmap.Height));
                    newImageSize.Height = ImageSize.Height;
                }

                var resizedBitmap = new Bitmap(originalBitmap, newImageSize);
                foreach (var id in originalBitmap.PropertyIdList)
                {
                    resizedBitmap.SetPropertyItem(originalBitmap.GetPropertyItem(id));
                }
  
                originalBitmap.Dispose();

                return resizedBitmap;
            }
            catch (Exception exception)
            {
                var bitmap = new Bitmap(ImageSize.Width, ImageSize.Height);
                using (var graphics = Graphics.FromImage(bitmap))
                {
                    graphics.Clear(Color.White);
                    graphics.DrawString(exception.Message, new Font("Arial", 12), Brushes.Black, 50, 50);
                }

                return bitmap;
            }
        }

19 Source : loading.cs
with MIT License
from Amine-Smahi

private void t_Tick(object sender, EventArgs e)
        {
            g = Graphics.FromImage(bmp);
            g.Clear(Color.White);
            var myBrush = new SolidBrush(Color.FromArgb(37, 155, 36));
            g.FillRectangle(myBrush, new Rectangle(0, 0, (int) (pbComplete * pbUnit), pbHEIGHT));


            if (pbComplete == 60)
            {

                FileInfo fi = new FileInfo(@".\a\lang.txt");
                DirectoryInfo di = new DirectoryInfo(@".\a");
                if (!di.Exists)
                {
                    di.Create();
                }
                if (!fi.Exists)
                {
                    fi.Create().Dispose();
                }

                /* if (!File.Exists(path))
                 {
                     File.Create(path).Dispose();
                     using (TextWriter tw = new StreamWriter(path))
                     {
                         tw.WriteLine("english");
                         tw.Close();
                     }
                 }
                 */
            }

            if (pbComplete == 70)
                if (File.Exists(path))
                    using (TextReader tr = new StreamReader(path))
                    {
                        var langugeChoused = tr.ReadLine();

                        if (langugeChoused == "arabic")
                        {
                            fom.bunifuTileButton1.LabelText = "إفتح صورة";
                            fom.bunifuTileButton2.LabelText = "إحفظ الصورة";
                            fom.bunifuTileButton3.LabelText = "أكتب الرسالة";
                            fom.bunifuTileButton4.LabelText = "أظهر الصورة";
                            fom.about_us.LabelText = "عن البرنامج";
                            fom.bunifuTileButton6.LabelText = "إعداداتي";
                        }
                    }

            picboxPB.Image = bmp;
            pbComplete++;

            if (pbComplete > 100)
            {
                g.Dispose();
                t.Stop();
                Hide();

                fom.Show();
            }
        }

19 Source : DockersTabsControl.cs
with GNU General Public License v3.0
from anotak

protected override void OnPaint(PaintEventArgs e)
		{
			Point p;

			if(VisualStyleInformation.IsSupportedByOS && VisualStyleInformation.IsEnabledByUser)
			{
				RedrawTabs();
				
				e.Graphics.Clear(SystemColors.Control);
				
				if(this.Alignment == TabAlignment.Left)
				{
					p = new Point(0, 0);
				}
				else
				{
					int left = this.ClientSize.Width - tabsimage.Size.Width;
					if(left < 0) left = 0;
					p = new Point(left, 0);
				}
				
				e.Graphics.DrawImage(tabsimage, p);
			}
			else
			{
				base.OnPaint(e);
			}
		}

19 Source : AngleControl.cs
with GNU General Public License v3.0
from anotak

private void AngleControl_Paint(object sender, PaintEventArgs e)
		{
			float rad = Angle2D.DegToRad((float)angle);
			e.Graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
			e.Graphics.InterpolationMode = InterpolationMode.High;
			e.Graphics.SmoothingMode = SmoothingMode.HighQuality;
			e.Graphics.Clear(this.BackColor);
			Pen linepen = new Pen(SystemColors.ControlText, LINE_THICKNESS);
			PointF start = new PointF((float)this.Size.Width * 0.5f, (float)this.Size.Height * 0.5f);
			float line_length = (float)this.Size.Width * 0.26f;
			if((rad >= 0) && (rad < 360))
			{
				PointF end = new PointF(start.X + (float)Math.Sin(rad + Angle2D.PIHALF) * line_length,
										start.Y + (float)Math.Cos(rad + Angle2D.PIHALF) * line_length);
				e.Graphics.DrawLine(linepen, start, end);
			}
			else
			{
				e.Graphics.DrawLine(linepen, start, start);
			}
		}

19 Source : ImagePanel.cs
with GNU General Public License v3.0
from anotak

protected override void OnPaintBackground(PaintEventArgs e)
        {
            if (bg == null || !SystemInformation.HighContrast)
            {
                base.OnPaintBackground(e);
                return;
            }

            // filtering looks awful for old sprites
            e.Graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor;

            e.Graphics.Clear(BackColor);

            Rectangle clip = e.ClipRectangle;
            float centerx = clip.Width  / 2.0f;
            float centery = clip.Height / 2.0f;

            float outputw = bg.Width;
            float outputh = bg.Height;

            float scale = Math.Min(clip.Width / outputw, clip.Height / outputh);

            outputw *= scale;
            outputh *= scale;

            float targetx = centerx - (outputw / 2.0f);
            float targety = centery - (outputh / 2.0f);


            e.Graphics.DrawImage(bg,targetx,targety, outputw, outputh);
        }

19 Source : TransparentPanel.cs
with GNU General Public License v3.0
from anotak

protected override void OnPaintBackground(PaintEventArgs e)
		{
			if(BackColor != Color.Transparent)
				e.Graphics.Clear(BackColor);
		}

19 Source : ImageData.cs
with GNU General Public License v3.0
from anotak

protected virtual void LocalLoadImage()
		{
			BitmapData bmpdata = null;
			
			lock(this)
			{
				// Bitmap loaded successfully?
				if(bitmap != null)
				{
					// Bitmap has incorrect format?
					if(bitmap.PixelFormat != PixelFormat.Format32bppArgb)
					{
						if(dynamictexture)
							throw new Exception("Dynamic images must be in 32 bits ARGB format.");
						
						//General.ErrorLogger.Add(ErrorType.Warning, "Image '" + name + "' does not have A8R8G8B8 pixel format. Conversion was needed.");
						Bitmap oldbitmap = bitmap;
						try
						{
							// Convert to desired pixel format
							bitmap = new Bitmap(oldbitmap.Size.Width, oldbitmap.Size.Height, PixelFormat.Format32bppArgb);
							Graphics g = Graphics.FromImage(bitmap);
							g.PageUnit = GraphicsUnit.Pixel;
							g.CompositingQuality = CompositingQuality.HighQuality;
							g.InterpolationMode = InterpolationMode.NearestNeighbor;
							g.SmoothingMode = SmoothingMode.None;
							g.PixelOffsetMode = PixelOffsetMode.None;
							g.Clear(Color.Transparent);
							g.DrawImage(oldbitmap, 0, 0, oldbitmap.Size.Width, oldbitmap.Size.Height);
							g.Dispose();
							oldbitmap.Dispose();
						}
						catch(Exception e)
						{
							bitmap = oldbitmap;
							General.ErrorLogger.Add(ErrorType.Warning, "Cannot lock image '" + name + "' for pixel format conversion. The image may not be displayed correctly.\n" + e.GetType().Name + ": " + e.Message);
						}
					}
					
					// This applies brightness correction on the image
					if(usecolorcorrection)
					{
						try
						{
							// Try locking the bitmap
							bmpdata = bitmap.LockBits(new Rectangle(0, 0, bitmap.Size.Width, bitmap.Size.Height), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);
						}
						catch(Exception e)
						{
							General.ErrorLogger.Add(ErrorType.Warning, "Cannot lock image '" + name + "' for color correction. The image may not be displayed correctly.\n" + e.GetType().Name + ": " + e.Message);
						}

						// Bitmap locked?
						if(bmpdata != null)
						{
							// Apply color correction
							PixelColor* pixels = (PixelColor*)(bmpdata.Scan0.ToPointer());
							General.Colors.ApplColorCorrection(pixels, bmpdata.Width * bmpdata.Height);
							bitmap.UnlockBits(bmpdata);
						}
					}
				}
				else
				{
					// Loading failed
					// We still mark the image as ready so that it will
					// not try loading again until Reload Resources is used
					loadfailed = true;
					bitmap = new Bitmap(Properties.Resources.Failed);
				}

				if(bitmap != null)
				{
					width = bitmap.Size.Width;
					height = bitmap.Size.Height;

					if(dynamictexture)
					{
						if((width != General.NextPowerOf2(width)) || (height != General.NextPowerOf2(height)))
							throw new Exception("Dynamic images must have a size in powers of 2.");
					}

					// Do we still have to set a scale?
					if((scale.x == 0.0f) && (scale.y == 0.0f))
					{
						if((General.Map != null) && (General.Map.Config != null))
						{
							scale.x = General.Map.Config.DefaultTextureScale;
							scale.y = General.Map.Config.DefaultTextureScale;
						}
						else
						{
							scale.x = 1.0f;
							scale.y = 1.0f;
						}
					}
				}
				
				// Image is ready
				imagestate = ImageLoadState.Ready;
			}
		}

19 Source : PreviewManager.cs
with GNU General Public License v3.0
from anotak

private void MakeImagePreview(ImageData img)
		{
			int previewwidth, previewheight;
			int imagewidth, imageheight;
			Bitmap preview;
			Graphics g;
			
			lock(img)
			{
				// Load image if needed
				if(!img.IsImageLoaded) img.LoadImage();
				if(!img.LoadFailed)
				{
					imagewidth = img.Width;
					imageheight = img.Height;
				}
				else
				{
					imagewidth = img.GetBitmap().Size.Width;
					imageheight = img.GetBitmap().Size.Height;
				}
				
				// Determine preview size
				float scalex = (img.Width > maxpreviewwidth) ? ((float)maxpreviewwidth / (float)imagewidth) : 1.0f;
				float scaley = (img.Height > maxpreviewheight) ? ((float)maxpreviewheight / (float)imageheight) : 1.0f;
				float scale = Math.Min(scalex, scaley);
				previewwidth = (int)((float)imagewidth * scale);
				previewheight = (int)((float)imageheight * scale);
				if(previewwidth < 1) previewwidth = 1;
				if(previewheight < 1) previewheight = 1;

				// Make new image
				preview = new Bitmap(previewwidth, previewheight, IMAGE_FORMAT);
				g = Graphics.FromImage(preview);
				g.PageUnit = GraphicsUnit.Pixel;
				g.CompositingQuality = CompositingQuality.HighQuality;
				g.InterpolationMode = InterpolationMode.HighQualityBicubic;
				g.SmoothingMode = SmoothingMode.HighQuality;
				g.PixelOffsetMode = PixelOffsetMode.None;
				g.Clear(Color.Transparent);
				
				// Draw image onto atlas
				Rectangle atlasrect = new Rectangle(0, 0, previewwidth, previewheight);
				RectangleF imgrect = General.MakeZoomedRect(new Size(imagewidth, imageheight), atlasrect);
				if(imgrect.Width < 1.0f)
				{
					imgrect.X -= 0.5f - imgrect.Width * 0.5f;
					imgrect.Width = 1.0f;
				}
				if(imgrect.Height < 1.0f)
				{
					imgrect.Y -= 0.5f - imgrect.Height * 0.5f;
					imgrect.Height = 1.0f;
				}
				g.DrawImage(img.GetBitmap(), imgrect);
				g.Dispose();
				
				// Unload image if no longer needed
				if(!img.IsReferenced) img.UnloadImage();
				
				lock(images)
				{
					// Set numbers
					img.PreviewIndex = images.Count;
					img.PreviewState = ImageLoadState.Ready;
					
					// Add to previews list
					images.Add(preview);
				}
			}
		}

19 Source : MetroDropShadow.cs
with MIT License
from arsium

protected override void OnPaint(PaintEventArgs e)
		{
			e.Graphics.Clear(Color.FromArgb(0, 173, 239));//16, 26, 39

			using (Brush b = new SolidBrush(Color.FromArgb(0, 173, 239)))//0; 173; 239
			{
				e.Graphics.FillRectangle(b, new Rectangle(4, 4, ClientRectangle.Width - 8, ClientRectangle.Height - 8));
			}
		}

19 Source : ExperimentalPhysics.cs
with MIT License
from awaescher

public void Render(Graphics graphics)
		{
			graphics.Clear(TransparencyKey);
			
			var maxDistance = Math.Max(-90, Math.Min(90, _distance.X));
			graphics.TranslateTransform(_originalImage.Width, 0);
			//graphics.RotateTransform(45 + (float)maxDistance / 3);
			graphics.RotateTransform(_angle);
			var bounds = new Rectangle(Point.Empty, PreferredSize);
			graphics.DrawImageUnscaled(_originalImage, bounds);
			graphics.ResetTransform();
		}

19 Source : TestForm.cs
with MIT License
from 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 Source : WidgetRenderer.cs
with MIT License
from azist

private Image drawGDIPuzzleKeypadImage(PuzzleKeypad keypad, Color? bgColor = null, bool showRects = false)
    {
      var sz = keypad.Size;
      var result = new Bitmap(sz.Width + PuzzleKeypad.DEFAULT_RENDER_OFFSET_X * 2, sz.Height + PuzzleKeypad.DEFAULT_RENDER_OFFSET_Y * 2);
      using (var gr = System.Drawing.Graphics.FromImage(result))
      {
        if (bgColor.HasValue)
          gr.Clear(bgColor.Value);

        gr.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

        var boxPen = new Pen(Color.FromArgb(240, 240, 240), 1.0f);

        var boxPen2 = new Pen(Color.FromArgb(200, 200, 200), 1.3f);
        boxPen2.DashStyle = DashStyle.Dot;

        var shadowPen = new Pen(Color.FromArgb(255, 220, 220, 220), 1.0f);

        LinearGradientBrush paperBrush = null;
        Font font = null;
        LinearGradientBrush fntBrush = null;
        LinearGradientBrush fntBadBrush = null;

        try
        {
          foreach (var box in keypad.Boxes)
          {
            if (paperBrush == null)
            {
              paperBrush = new LinearGradientBrush(box.Rect, Color.FromArgb(240, 240, 240), Color.FromArgb(255, 255, 255), LinearGradientMode.Vertical);
              paperBrush.WrapMode = WrapMode.TileFlipXY;
            }

            if (fntBrush == null)
            {
              fntBrush = new LinearGradientBrush(box.Rect, Color.FromArgb(240, 240, 250), Color.FromArgb(100, 80, 150), LinearGradientMode.ForwardDiagonal);
              fntBrush.WrapMode = WrapMode.TileFlipXY;

              fntBadBrush = new LinearGradientBrush(box.Rect, Color.FromArgb(240, 240, 250), Color.FromArgb(200, 180, 255), LinearGradientMode.Vertical);
              fntBadBrush.WrapMode = WrapMode.TileFlipXY;
            }

            if (font == null)
            {
              font = new Font("Courier New", box.Rect.Height * 0.65f, FontStyle.Bold, GraphicsUnit.Pixel);
            }


            gr.ResetTransform();
            gr.TranslateTransform(PuzzleKeypad.DEFAULT_RENDER_OFFSET_X, PuzzleKeypad.DEFAULT_RENDER_OFFSET_Y);

            if (showRects)
              gr.DrawRectangle(Pens.Red, box.Rect);

            var rnd = App.Random;

            gr.RotateTransform((float)(-3d + (6d * rnd.NextRandomDouble)));

            var pTL = new Point(box.Rect.Left + rnd.NextScaledRandomInteger(-6, +6),
                                 box.Rect.Top + rnd.NextScaledRandomInteger(-6, +6));

            var pTR = new Point(box.Rect.Right + rnd.NextScaledRandomInteger(-6, +6),
                                 box.Rect.Top  + rnd.NextScaledRandomInteger(-6, +6));

            var pBL = new Point(box.Rect.Left    + rnd.NextScaledRandomInteger(-6, +6),
                                 box.Rect.Bottom + rnd.NextScaledRandomInteger(-6, +6));

            var pBR = new Point(box.Rect.Right   + rnd.NextScaledRandomInteger(-6, +6),
                                 box.Rect.Bottom + rnd.NextScaledRandomInteger(-6, +6));

            var pa = new[] { pTL, pTR, pBR, pBL };
            gr.FillPolygon(paperBrush, pa);
            gr.DrawPolygon(boxPen, pa);

            //gr.FillRectangle(paperBrush, box.Rect);
            //gr.DrawRectangle(boxPen, box.Rect);

            //var distortedBRX = box.Rect.Right + ExternalRandomGenerator.Instance.NextScaledRandomInteger(-10, +4);
            //var distortedBRY = box.Rect.Bottom + ExternalRandomGenerator.Instance.NextScaledRandomInteger(-10, +8);

            gr.DrawLine(shadowPen, pTR, pBR);

            gr.DrawLine(boxPen2, pBL.X + 1, pBL.Y, pBR.X - 1, pBR.Y);
            gr.DrawLine(boxPen2, pBL.X, pBL.Y + 1, pBR.X - 2, pBR.Y + 1);


            var tsz = gr.MeasureString(box.Char.ToString(), font);
            var pnt = new PointF((box.Rect.Left + box.Rect.Width / 2f) - tsz.Width / 2f,
                                  (box.Rect.Top + box.Rect.Height / 2f) - tsz.Height / 2f);


            if (rnd.NextScaledRandomInteger(0, 100) > 40)
            {
              var bpnt = pnt;
              bpnt.X += rnd.NextScaledRandomInteger(-2, 4);
              bpnt.Y += rnd.NextScaledRandomInteger(-2, 4);
              gr.DrawString(box.Char.ToString(), font, fntBadBrush, bpnt);

              for (var i = 0; i < rnd.NextScaledRandomInteger(8, 75); i++)
              {
                gr.FillRectangle(fntBadBrush, new Rectangle(box.Rect.Left + rnd.NextScaledRandomInteger(0, box.Rect.Width - 4),
                                                            box.Rect.Top + rnd.NextScaledRandomInteger(0, box.Rect.Height - 4),
                                                            rnd.NextScaledRandomInteger(1, 4),
                                                            rnd.NextScaledRandomInteger(1, 4)
                                                            ));

              }
            }

            gr.DrawString(box.Char.ToString(), font, fntBrush, pnt);
          }
        }
        finally
        {
          if (boxPen != null) boxPen.Dispose();
          if (boxPen2 != null) boxPen2.Dispose();
          if (shadowPen != null) shadowPen.Dispose();
          if (paperBrush != null) paperBrush.Dispose();
          if (font != null) font.Dispose();
          if (fntBrush != null)
          {
            fntBrush.Dispose();
            fntBadBrush.Dispose();
          }
        }

      }
      return result;
    }

19 Source : TimeScalePane.cs
with MIT License
from azist

protected override void OnPaint(PaintEventArgs e)
    {
      if (m_Ticks == null) return;

      var gr = e.Graphics;

      gr.Clear(Chart.TimeScaleStyle.BGColor);

      using (var sf = new StringFormat())
      {
        sf.Alignment     = StringAlignment.Center;
        sf.LineAlignment = StringAlignment.Center;

        var hh = Height/2;
        Tick prior = null;
        foreach (var tick in m_Ticks)
        {
          var txt  = OnTimeLineFormat(tick.Sample.TimeStamp, prior, false);
          var rect = new RectangleF(tick.X, 0, TickSpace, Height);

          if (tick.Warp)
          {
            gr.FillRectangle(Brushes.Gray, rect);
            gr.DrawLine(Pens.White, tick.X, 0, tick.X, Height);
          }
          else
            gr.DrawLine(m_Chart.GridLinePen, tick.X, 0, tick.X, hh);

          gr.DrawString(txt, Chart.TimeScaleStyle.Font, Chart.TimeScaleStyle.ForeBrush, rect, sf);

          prior = tick;
        }
      }

      base.OnPaint(e);
    }

19 Source : ImageUtils.cs
with MIT License
from azist

public static Image FitCenteredImage(this Image srcImage,
                                         int targetWidth = 128, int targetHeight = 128, int xDpi = 96, int yDpi = 96,
                                         Color? bColor = null)
    {
      if (srcImage==null || targetWidth<1 ||targetHeight<1 || xDpi<1 || yDpi<1)
       throw new AzosException(StringConsts.ARGUMENT_ERROR + "FitCenteredImage(...)");

      var result = new Bitmap(targetWidth, targetHeight);
      result.SetResolution(xDpi, yDpi);
      result.MakeTransparent();

      using (var gr = System.Drawing.Graphics.FromImage(result))
      {
        var xAspect = targetWidth/(float)srcImage.Width;
        var yAspect = targetHeight/(float)srcImage.Height;
        var ar = Math.Min(xAspect, yAspect);

        var newWidth  = (int)(srcImage.Width * ar);
        var newHeight = (int)(srcImage.Height * ar);
        var newX = (targetWidth - newWidth)/2;
        var newY = (targetHeight - newHeight)/2;

        gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
        gr.Clear(bColor ?? Color.White);
        gr.DrawImage(srcImage, newX, newY, newWidth, newHeight);
      }

      return result;
    }

19 Source : NetCanvas.cs
with MIT License
from azist

public void Clear(Color color) => m_Graphics.Clear(color);

19 Source : Theme.cs
with MIT License
from b9q

protected override void OnPaint(PaintEventArgs e)
    {
        Bitmap b = new Bitmap(Width, Height);
        using (Graphics g = Graphics.FromImage(b))
        {
            g.SmoothingMode = SmoothingMode.AntiAlias;
            g.Clear(Color.FromArgb(246, 251, 254));

            Drawing.DrawWithOutline(g, new SolidBrush(Color.FromArgb(254, 255, 255)), new SolidBrush(Color.FromArgb(208, 230, 246)), new Rectangle(0, 0, Width - 1, Height - 1));
            e.Graphics.DrawImage(b, 0, 0);
        }

        b.Dispose();
    }

19 Source : Theme.cs
with MIT License
from b9q

protected override void OnPaint(PaintEventArgs e)
    {
        Bitmap b = new Bitmap(Width, Height);
        using (Graphics g = Graphics.FromImage(b))
        {
            g.Clear(Color.FromArgb(254, 255, 255));

            for (int i = 0; i <= TabCount - 1; i++)
            {
                Rectangle TabRectangle = GetTabRect(i);

                //fix tab position
                TabRectangle.X += 2;
                //TabRectangle.Height = 34;
                TabRectangle.Y += 1;

                Rectangle stringRect = TabRectangle;
                stringRect.X += 3;

                if (i == SelectedIndex)
                {
                    g.FillRectangle(Drawing.tehColor, TabRectangle);
                    g.DrawString(TabPages[i].Text, _font, Brushes.White, stringRect, new StringFormat
                    {
                        LineAlignment = StringAlignment.Center,
                        Alignment = StringAlignment.Near
                    });
                }
                else
                {
                    g.DrawRectangle(new Pen(Color.FromArgb(208, 230, 246)), TabRectangle);
                    g.DrawString(TabPages[i].Text, _font, Drawing.tehColor, stringRect, new StringFormat
                    {
                        LineAlignment = StringAlignment.Center,
                        Alignment = StringAlignment.Near
                    });
                }

                g.DrawLine(new Pen(Drawing.tehColor), new Point(TabRectangle.X, TabRectangle.Y + TabRectangle.Height),
                    new Point(this.Width - 5, TabRectangle.Y + TabRectangle.Height));
            }

            e.Graphics.DrawImage(b, 0, 0);
        }

        b.Dispose();
        base.OnPaint(e);
    }

19 Source : Theme.cs
with MIT License
from b9q

protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);
        using (Graphics g = e.Graphics)
        {
            g.Clear(Color.FromArgb(246, 251, 254));

            g.FillRectangle(new SolidBrush(Color.FromArgb(254, 255, 255)), new Rectangle(0, replacedleHeight, Width, Height));
            using (Pen thickness = new Pen(Drawing.tehColor))
            {
                thickness.Width = 2.0F;
                g.DrawRectangle(thickness, new Rectangle(1, 1, Width - 2, Height - 2)); //outline
            }

            using (Pen thickness = new Pen(Drawing.underlineColor))
            {
                thickness.Width = 1.5F;
                g.DrawLine(thickness, 4, replacedleHeight, Width - 4, replacedleHeight); //replacedleline
            }

            //replacedle text
            g.DrawString(Text, Font, new SolidBrush(Color.FromArgb(220, 20, 60)), new Rectangle(7, 0, Width, replacedleHeight + 2), new StringFormat
            {
                Alignment = StringAlignment.Near,
                LineAlignment = StringAlignment.Center
            });
        }
    }

19 Source : RemoteControl_rdp.xaml.cs
with Apache License 2.0
from beckzhu

private int WinRdpClientProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam)
        {
            if (msg == 15)
            {
                User32.CallWindowProc(_oldRdpClientWinProc, hwnd, msg, wParam, lParam);
                Graphics grap = Graphics.FromHwnd(hwnd);
                grap.Clear(Color.White);
                return 0;
            }
            if (msg == 20)
            {
                Graphics grap = Graphics.FromHwnd(hwnd);
                grap.Clear(Color.White);
                return 0;
            }
            if (msg == 133)
            {
                User32.CallWindowProc(_oldRdpClientWinProc, hwnd, msg, wParam, lParam);
                return 0;
            }
            if (msg == 512)//WM_MOUSEMOVE
            {
                int num = lParam.ToInt32();
                MouseMoveProc?.Invoke(CommonServices.LOWORD(num), CommonServices.HIWORD(num));
            }
            return User32.CallWindowProc(_oldRdpClientWinProc, hwnd, msg, wParam, lParam);
        }

19 Source : ImageExtensions.cs
with MIT License
from bibaoke

public static System.Drawing.Image Zoom(this System.Drawing.Image i, int width, int height, InterpolationMode mode)
        {
            Bitmap bitmap = new Bitmap(width, height);

            using (Graphics g = Graphics.FromImage(bitmap))
            {
                g.InterpolationMode = mode;

                g.Clear(Color.Empty);

                g.DrawImage(i, new Rectangle(0, 0, width, height), new Rectangle(0, 0, i.Width, i.Height), GraphicsUnit.Pixel);
            }

            return bitmap;
        }

19 Source : ImageExtensions.cs
with MIT License
from bibaoke

private static System.Drawing.Image CropOrFill(this System.Drawing.Image image, int width, int height, Color background, InterpolationMode mode)
        {
            Bitmap bitmap = new Bitmap(width, height);

            using (Graphics g = Graphics.FromImage(bitmap))
            {
                g.InterpolationMode = mode;

                int srcX = ImageExtensions.GetSrc(image.Width, width);
                int srcY = ImageExtensions.GetSrc(image.Height, height);

                g.Clear(background);

                g.DrawImage(image, new Rectangle(0, 0, width, height), srcX, srcY, width, height, GraphicsUnit.Pixel);
            }

            return bitmap;
        }

19 Source : StringExtensions.cs
with MIT License
from bibaoke

public static System.Drawing.Image ToImage(this string s, int width, int height, Color background, Font font, Brush brush, RectangleF layoutRectangle, StringFormat format)
        {
            System.Drawing.Image image = new Bitmap(width, height);

            using (Graphics g = Graphics.FromImage(image))
            {
                g.Clear(background);

                g.DrawString(s, font, brush, layoutRectangle, format);
            }

            return image;
        }

19 Source : Utils.cs
with GNU General Public License v3.0
from BigETI

public static Image GetThumbnail(Image image)
        {
            Bitmap ret = new Bitmap(GalleryImageSize.Width, GalleryImageSize.Height, PixelFormat.Format32bppArgb);
            Size sz = (image.Width >= image.Height) ? new Size(GalleryImageSize.Width, (int)(GalleryImageSize.Width * ((double)(image.Height) / image.Width))) : new Size(GalleryImageSize.Height, (int)(GalleryImageSize.Height * ((double)(image.Width) / image.Height)));
            Graphics g = Graphics.FromImage(ret);
            g.Clear(Color.Transparent);
            g.InterpolationMode = InterpolationMode.HighQualityBilinear;
            g.DrawImage(image, new Rectangle(new Point((GalleryImageSize.Width - sz.Width) / 2, (GalleryImageSize.Height - sz.Height) / 2), sz), new Rectangle(0, 0, image.Width, image.Height), GraphicsUnit.Pixel);
            return ret;
        }

19 Source : GLForm.cs
with MIT License
from BleuBleu

protected override void OnPaint(PaintEventArgs e)
        {
            if (DesignMode)
            {
                e.Graphics.Clear(System.Drawing.Color.Black);
                e.Graphics.DrawString("OpenGL cannot be used at design time.", this.Font, System.Drawing.Brushes.White, 10, 10);
            }
            else if (graphicsContext != null)
            {
                RenderFrameAndSwapBuffers(true);
            }
        }

19 Source : MapboxRaster.cs
with MIT License
from blueherongis

protected override void SolveInstance(IGH_DataAccess DA)
        {
            List<Curve> boundary = new List<Curve>();
            DA.GetDataList<Curve>(0, boundary);

            int zoom = -1;
            DA.GetData<int>(1, ref zoom);

            string folderPath = string.Empty;
            DA.GetData<string>(2, ref folderPath);
            if (!folderPath.EndsWith(@"\")) folderPath = folderPath + @"\";

            string prefix = string.Empty;
            DA.GetData<string>(3, ref prefix);
            if (prefix == "")
            {
                prefix = mbSource;
            }

            string URL = mbURL;

            ///get a valid mapbox token to send along with query
            string mbToken = string.Empty;
            DA.GetData<string>(4, ref mbToken);
            if (mbToken == "")
            {
                string hmbToken = System.Environment.GetEnvironmentVariable("HERONMAPBOXTOKEN");
                if (hmbToken != null)
                {
                    mbToken = hmbToken;
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Using Mapbox token stored in Environment Variable HERONMAPBOXTOKEN.");
                }
                else
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "No Mapbox token is specified.  Please get a valid token from mapbox.com");
                    return;
                }
            }

            bool run = false;
            DA.GetData<bool>("Run", ref run);

            GH_Structure<GH_String> mapList = new GH_Structure<GH_String>();
            GH_Structure<GH_Rectangle> imgFrame = new GH_Structure<GH_Rectangle>();
            GH_Structure<GH_String> tCount = new GH_Structure<GH_String>();

            /*
            ///Save for later development of warping
            ///Setup for warping
            RESTful.GdalConfiguration.ConfigureGdal();
            RESTful.GdalConfiguration.ConfigureOgr();

            OSGeo.OSR.SpatialReference userSRS = new OSGeo.OSR.SpatialReference("");
            userSRS.SetFromUserInput("WGS84");

            OSGeo.OSR.SpatialReference mapboxSRS = new OSGeo.OSR.SpatialReference("");
            mapboxSRS.SetFromUserInput("EPSG:3857");

            ///Set transform from input spatial reference to Rhino spatial reference
            OSGeo.OSR.SpatialReference rhinoSRS = new OSGeo.OSR.SpatialReference("");
            rhinoSRS.SetWellKnownGeogCS("WGS84");

            ///This transform moves and scales the points required in going from userSRS to XYZ and vice versa
            //Transform userSRSToModelTransform = Heron.Convert.GetUserSRSToModelTransform(userSRS);
            Transform modelToUserSRSTransform = Heron.Convert.GetModelToUserSRSTransform(userSRS);
            Transform mapboxSRSToModelTransform = Heron.Convert.GetUserSRSToModelTransform(mapboxSRS);
            Transform modelToMapboxSRSTransform = Heron.Convert.GetModelToUserSRSTransform(mapboxSRS);
            */

            for (int i = 0; i < boundary.Count; i++)
            {
                GH_Path path = new GH_Path(i);
                int tileTotalCount = 0;
                int tileDownloadedCount = 0;


                //Get image frame for given boundary and  make sure it's valid
                if (!boundary[i].GetBoundingBox(true).IsValid)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Boundary is not valid.");
                    return;
                }
                BoundingBox boundaryBox = boundary[i].GetBoundingBox(true);

                ///TODO: look into scaling boundary to get buffer tiles

                ///file path for final image
                string imgPath = folderPath + prefix + "_" + i + ".jpg";

                if (!tilesOut)
                {
                    //location of final image file
                    mapList.Append(new GH_String(imgPath), path);
                }

                //create cache folder for images
                string cacheLoc = folderPath + @"HeronCache\";
                List<string> cacheFilePaths = new List<string>();
                if (!Directory.Exists(cacheLoc))
                {
                    Directory.CreateDirectory(cacheLoc);
                }

                //tile bounding box array
                List<Point3d> boxPtList = new List<Point3d>();

                //get the tile coordinates for all tiles within boundary
                var ranges = Convert.GetTileRange(boundaryBox, zoom);
                List<List<int>> tileList = new List<List<int>>();
                var x_range = ranges.XRange;
                var y_range = ranges.YRange;

                if (x_range.Length > 100 || y_range.Length > 100)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "This tile range is too big (more than 100 tiles in the x or y direction). Check your units.");
                    return;
                }

                List<Rectangle3d> tileRectangles = new List<Rectangle3d>();

                //cycle through tiles to get bounding box
                for (int y = (int)y_range.Min; y <= y_range.Max; y++)
                {
                    for (int x = (int)x_range.Min; x <= x_range.Max; x++)
                    {
                        //add bounding box of tile to list
                        List<Point3d> boxPts = Convert.GetTileAsPolygon(zoom, y, x).ToList();
                        boxPtList.AddRange(boxPts);
                        string cacheFilePath = cacheLoc + mbSource.Replace(" ", "") + zoom + "-" + x + "-" + y + ".jpg";
                        cacheFilePaths.Add(cacheFilePath);

                        tileTotalCount = tileTotalCount + 1;

                        if (tilesOut)
                        {
                            mapList.Append(new GH_String(cacheFilePath), path);
                            Rectangle3d tileRectangle = BBoxToRect(new BoundingBox(boxPts));
                            tileRectangles.Add(tileRectangle);
                            imgFrame.Append(new GH_Rectangle(tileRectangle), path);
                        }
                    }
                }

                tCount.Insert(new GH_String(tileTotalCount + " tiles (" + tileDownloadedCount + " downloaded / " + (tileTotalCount - tileDownloadedCount) + " cached)"), path, 0);

                //bounding box of tile boundaries
                BoundingBox bbox = new BoundingBox(boxPtList);

                var rect = BBoxToRect(bbox);
                if (!tilesOut)
                {
                    imgFrame.Append(new GH_Rectangle(rect), path);
                }

                ///tile range as string for (de)serialization of TileCacheMeta
                string tileRangeString = zoom.ToString()
                    + x_range[0].ToString()
                    + y_range[0].ToString()
                    + x_range[1].ToString()
                    + y_range[1].ToString();

                ///check if the existing final image already covers the boundary. 
                ///if so, no need to download more or rereplacedemble the cached tiles.

                if ((TileCacheMeta == tileRangeString) && Convert.CheckCacheImagesExist(cacheFilePaths))
                {
                    if (File.Exists(imgPath) && !tilesOut)
                    {
                        using (Bitmap imageT = new Bitmap(imgPath))
                        {
                            ///getting commments currently only working for JPG
                            ///TODO: get this to work for any image type or
                            ///find another way to check if the cached image covers the boundary.
                            string imgComment = string.Empty;

                            ///Save for later development of warping
                            //if (!warped)
                            imgComment = imageT.GetCommentsFromJPG();

                            imageT.Dispose();

                            ///check to see if tilerange in comments matches current tilerange
                            if (imgComment == (mbSource.Replace(" ", "") + tileRangeString))
                            {
                                AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Using existing image.");
                                AddPreviewItem(imgPath, boundary[i], rect);
                                continue;
                            }

                        }

                    }

                    if (tilesOut)
                    {
                        for (int t = 0; t < cacheFilePaths.Count; t++)
                        {
                            if (File.Exists(cacheFilePaths[t]))
                            {
                                AddPreviewItem(cacheFilePaths[t], tileRectangles[t].ToNurbsCurve(), tileRectangles[t]);
                            }
                        }
                        continue;
                    }

                }



                ///Query Mapbox URL
                ///download all tiles within boundary
                ///merge tiles into one bitmap
                ///API to query
                string mbURLauth = mbURL + mbToken;


                ///Do the work of replacedembling image
                ///setup final image container bitmap
                int fImageW = ((int)x_range.Length + 1) * 512;
                int fImageH = ((int)y_range.Length + 1) * 512;
                Bitmap finalImage = new Bitmap(fImageW, fImageH);


                int imgPosW = 0;
                int imgPosH = 0;

                /*
                ///Save for later development of warping
                List<GCP> gcpList = new List<GCP>();
                */

                using (Graphics g = Graphics.FromImage(finalImage))
                {
                    g.Clear(Color.Black);
                    for (int y = (int)y_range.Min; y <= (int)y_range.Max; y++)
                    {
                        for (int x = (int)x_range.Min; x <= (int)x_range.Max; x++)
                        {
                            ///create tileCache name 
                            string tileCache = mbSource.Replace(" ", "") + zoom + "-" + x + "-" + y + ".jpg";
                            string tileCacheLoc = cacheLoc + tileCache;

                            /*
                            ///Save for later development of warping
                            ///Get GCPs for warping 
                            Point3d tileCorner = Heron.Convert.GetTileAsPolygon(zoom, y, x)[3];
                            var tileCorner3857 = Convert.Point3dToOgrPoint(tileCorner, modelToMapboxSRSTransform);
                            GCP gcp = new GCP(tileCorner3857.GetX(0), tileCorner3857.GetY(0), tileCorner3857.GetZ(0), imgPosW * 512, imgPosH * 512, tileCorner3857.ToString(), zoom + x + y + "");
                            gcpList.Add(gcp);
                            */

                            ///check cache folder to see if tile image exists locally
                            if (File.Exists(tileCacheLoc))
                            {
                                Bitmap tmpImage = new Bitmap(Image.FromFile(tileCacheLoc));
                                ///add tmp image to final
                                g.DrawImage(tmpImage, imgPosW * 512, imgPosH * 512);
                                tmpImage.Dispose();
                            }

                            else
                            {
                                tileList.Add(new List<int> { zoom, y, x });
                                string urlAuth = Convert.GetZoomURL(x, y, zoom, mbURLauth);

                                Bitmap tmpImage = new Bitmap(512, 512);

                                System.Net.WebClient client = new System.Net.WebClient();
                                if (run == true)
                                {
                                    try
                                    {
                                        client.DownloadFile(urlAuth, tileCacheLoc);
                                        tmpImage = new Bitmap(Image.FromFile(tileCacheLoc));
                                    }
                                    catch (WebException e)
                                    {
                                        using (Graphics tmp = Graphics.FromImage(tmpImage)) { tmp.Clear(Color.White); }
                                        AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, e.Message);
                                    }
                                }
                                client.Dispose();


                                ///add tmp image to final
                                g.DrawImage(tmpImage, imgPosW * 512, imgPosH * 512);
                                tmpImage.Dispose();
                                tileDownloadedCount = tileDownloadedCount + 1;
                            }

                            ///increment x insert position, goes left to right
                            imgPosW++;
                        }
                        ///increment y insert position, goes top to bottom
                        imgPosH++;
                        imgPosW = 0;

                    }
                    ///garbage collection
                    g.Dispose();

                    ///add tile range meta data to image comments
                    finalImage.AddCommentsToJPG(mbSource.Replace(" ", "") + tileRangeString);

                    ///Save for later development of warping
                    ///if (!warped)
                    ///save the image
                    finalImage.Save(imgPath, ImageFormat.Jpeg);
                }

                /*
                ///Save for later development of warping
                byte[] imageBuffer;
                string memFilename = "/vsimem/inmemfile";
                string memTranslated = "/vsimem/inmemfileTranslated";
                string memWarped = "/vsimem/inmemfileWarped";
                using (MemoryStream stream = new MemoryStream())
                {
                    finalImage.Save(stream, ImageFormat.Jpeg);
                    imageBuffer = stream.ToArray();
                }
                */

                //garbage collection
                finalImage.Dispose();

                /*
                ///Save for later development of warping
                Gdal.FileFromMemBuffer(memFilename, imageBuffer);
                Dataset gdalImage = Gdal.Open(memFilename, Access.GA_ReadOnly);
                var upperLeft3857 = Convert.Point3dToOgrPoint(rect.Corner(3), modelToMapboxSRSTransform);
                var lowerRight3857 = Convert.Point3dToOgrPoint(rect.Corner(1), modelToMapboxSRSTransform);
                var upperLeft4326 = Convert.Point3dToOgrPoint(rect.Corner(3), modelToUserSRSTransform);
                var lowerRight4326 = Convert.Point3dToOgrPoint(rect.Corner(1), modelToUserSRSTransform);
                List<string> translateOptions = new List<string> { "-a_srs", "EPSG:3857", 
                    "-r", "bilinear",
                    "-a_ullr", upperLeft3857.GetX(0).ToString(), upperLeft3857.GetY(0).ToString(), lowerRight3857.GetX(0).ToString(), lowerRight3857.GetY(0).ToString() };
                Dataset gdalTranslated = Gdal.wrapper_GDALTranslate(memTranslated, gdalImage, new GDALTranslateOptions(translateOptions.ToArray()), null, null);

                var wkt = gdalTranslated.GetProjection();
                //gdalTranslated.SetGCPs(gcpList.ToArray(), wkt);

                List<string> warpOptions = new List<string> { "-t_srs", "EPSG:4326", 
                    "-r", "bilinear", 
                    //"-multi", 
                    //"-wo", "NUM_THREADS=6", 
                    "-overwrite", 
                    //"-order", "1",
                    //"-tps",
                    "-te_srs", "EPSG:3857",
                    "-te", upperLeft3857.GetX(0).ToString(), lowerRight3857.GetY(0).ToString(), lowerRight3857.GetX(0).ToString(), upperLeft3857.GetY(0).ToString() };

                ///https://github.com/OSGeo/gdal/issues/813
                ///https://lists.osgeo.org/pipermail/gdal-dev/2017-February/046046.html
                ///Odd way to go about setting source dataset in parameters for Warp is a known issue

                var ptr = new[] { Dataset.getCPtr(gdalTranslated).Handle };
                var gcHandle = GCHandle.Alloc(ptr, GCHandleType.Pinned);
                try
                {
                    var dss = new SWIGTYPE_p_p_GDALDatasetShadow(gcHandle.AddrOfPinnedObject(), false, null);
                    Dataset gdalWarped = Gdal.wrapper_GDALWarpDestName(memWarped, 1, dss, new GDALWarpAppOptions(warpOptions.ToArray()), null, null);
                    var driver = Gdal.GetDriverByName("JPEG");
                    List<string> copyOptions = new List<string> { "QUALITY=95", "COMMENT=" + mbSource.Replace(" ", "") + tileRangeString};
                    var copy = driver.CreateCopy(imgPath, gdalWarped, 0, copyOptions.ToArray(), null, null);
                    copy.Dispose();
                    driver.Dispose();
                    gdalWarped.Dispose();
                }
                finally
                {
                    if (gcHandle.IsAllocated)
                        gcHandle.Free();
                }

                gdalImage.Dispose();
                gdalTranslated.Dispose();
                Gdal.Unlink(memFilename);
                Gdal.Unlink(memTranslated);
                Gdal.Unlink(memWarped);
                */

                if (!tilesOut)
                {
                    AddPreviewItem(imgPath, boundary[i], rect);
                }
                else
                {
                    for (int t = 0; t < cacheFilePaths.Count; t++)
                    {
                        if (File.Exists(cacheFilePaths[t]))
                        {
                            AddPreviewItem(cacheFilePaths[t], tileRectangles[t].ToNurbsCurve(), tileRectangles[t]);
                        }
                    }
                }

                //add to tile count total
                tCount.Insert(new GH_String(tileTotalCount + " tiles (" + tileDownloadedCount + " downloaded / " + (tileTotalCount - tileDownloadedCount) + " cached)"), path, 0);

                //write out new tile range metadata for serialization
                TileCacheMeta = tileRangeString;

            }


            DA.SetDataTree(0, mapList);
            DA.SetDataTree(1, imgFrame);
            DA.SetDataTree(2, tCount);
            DA.SetDataList(3, "copyright Mapbox");

        }

19 Source : MapboxTopo.cs
with MIT License
from blueherongis

protected override void SolveInstance(IGH_DataAccess DA)
        {
            List<Curve> boundary = new List<Curve>();
            DA.GetDataList<Curve>(0, boundary);

            int zoom = -1;
            DA.GetData<int>(1, ref zoom);

            string filePath = string.Empty;
            DA.GetData<string>(2, ref filePath);
            if (!filePath.EndsWith(@"\")) filePath = filePath + @"\";

            string prefix = string.Empty;
            DA.GetData<string>(3, ref prefix);
            if (prefix == string.Empty)
            {
                prefix = mbSource;
            }

            string URL = mbURL;
            //DA.GetData<string>(4, ref URL);


            string mbToken = string.Empty;
            DA.GetData<string>(4, ref mbToken);
            if (mbToken == string.Empty)
            {
                string hmbToken = System.Environment.GetEnvironmentVariable("HERONMAPBOXTOKEN");
                if (hmbToken != null)
                {
                    mbToken = hmbToken;
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Using Mapbox token stored in Environment Variable HERONMAPBOXTOKEN.");
                }
                else
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "No Mapbox token is specified.  Please get a valid token from mapbox.com");
                    return;
                }
            }

            bool run = false;
            DA.GetData<bool>("Run", ref run);

            GH_Structure<GH_String> mapList = new GH_Structure<GH_String>();
            GH_Structure<GH_Curve> imgFrame = new GH_Structure<GH_Curve>();
            GH_Structure<GH_String> tCount = new GH_Structure<GH_String>();
            GH_Structure<GH_Mesh> tMesh = new GH_Structure<GH_Mesh>();

            for (int i = 0; i < boundary.Count; i++)
            {

                GH_Path path = new GH_Path(i);
                int tileTotalCount = 0;
                int tileDownloadedCount = 0;

                ///Get image frame for given boundary
                if (!boundary[i].GetBoundingBox(true).IsValid)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Boundary is not valid.");
                    return;
                }
                BoundingBox boundaryBox = boundary[i].GetBoundingBox(true);

                ///TODO: look into scaling boundary to get buffer tiles

                ///file path for final image
                string imgPath = filePath + prefix + "_" + i + ".png";

                //location of final image file
                mapList.Append(new GH_String(imgPath), path);

                //create cache folder for images
                string cacheLoc = filePath + @"HeronCache\";
                List<string> cachefilePaths = new List<string>();
                if (!Directory.Exists(cacheLoc))
                {
                    Directory.CreateDirectory(cacheLoc);
                }

                //tile bounding box array
                List<Point3d> boxPtList = new List<Point3d>();


                //get the tile coordinates for all tiles within boundary
                var ranges = Convert.GetTileRange(boundaryBox, zoom);
                List<List<int>> tileList = new List<List<int>>();
                var x_range = ranges.XRange;
                var y_range = ranges.YRange;

                if (x_range.Length > 100 || y_range.Length > 100)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "This tile range is too big (more than 100 tiles in the x or y direction). Check your units.");
                    return;
                }

                //cycle through tiles to get bounding box
                for (int y = (int)y_range.Min; y <= y_range.Max; y++)
                {
                    for (int x = (int)x_range.Min; x <= x_range.Max; x++)
                    {
                        //add bounding box of tile to list
                        boxPtList.AddRange(Convert.GetTileAsPolygon(zoom, y, x).ToList());
                        cachefilePaths.Add(cacheLoc + mbSource.Replace(" ", "") + zoom + x + y + ".png");
                        tileTotalCount = tileTotalCount + 1;
                    }
                }

                tCount.Insert(new GH_String(tileTotalCount + " tiles (" + tileDownloadedCount + " downloaded / " + (tileTotalCount - tileDownloadedCount) + " cached)"), path, 0);

                //bounding box of tile boundaries
                BoundingBox bboxPts = new BoundingBox(boxPtList);

                //convert bounding box to polyline
                List<Point3d> imageCorners = bboxPts.GetCorners().ToList();
                imageCorners.Add(imageCorners[0]);
                imgFrame.Append(new GH_Curve(new Rhino.Geometry.Polyline(imageCorners).ToNurbsCurve()), path);

                //tile range as string for (de)serialization of TileCacheMeta
                string tileRangeString = zoom.ToString()
                    + x_range[0].ToString()
                    + y_range[0].ToString()
                    + x_range[1].ToString()
                    + y_range[1].ToString();

                //check if the existing final image already covers the boundary. 
                //if so, no need to download more or rereplacedemble the cached tiles.
                ///temporarily disable until how to tag images with meta data is figured out
                /*
                if (TileCacheMeta == tileRangeString && Convert.CheckCacheImagesExist(cachefilePaths))
                {
                    if (File.Exists(imgPath))
                    {
                        using (Bitmap imageT = new Bitmap(imgPath))
                        {
                            //System.Drawing.Imaging.PropertyItem prop = imageT.GetPropertyItem(40092);
                            //string imgComment = Encoding.Unicode.GetString(prop.Value);
                            string imgComment = imageT.GetCommentsFromImage();
                            //AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, imgComment);
                            imageT.Dispose();
                            //check to see if tilerange in comments matches current tilerange
                            if (imgComment == (mbSource.Replace(" ", "") + tileRangeString))
                            {
                                AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Using existing topo image.");

                                Mesh eMesh = TopoMeshFromImage(imgPath, boundaryBox, zoom);
                                tMesh.Append(new GH_Mesh(eMesh), path);
                                continue;
                            }

                        }

                    }

                }
                */


                ///Query Mapbox URL
                ///download all tiles within boundary
                ///merge tiles into one bitmap

                ///API to query
                ///string mbURL = "https://api.mapbox.com/v4/mapbox.terrain-rgb/{z}/{x}/{y}@2x.pngraw?access_token=" + mbToken;
                string mbURLauth = mbURL + mbToken;


                ///Do the work of replacedembling image
                ///setup final image container bitmap
                int fImageW = ((int)x_range.Length + 1) * 512;
                int fImageH = ((int)y_range.Length + 1) * 512;
                Bitmap finalImage = new Bitmap(fImageW, fImageH, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

                int imgPosW = 0;
                int imgPosH = 0;

                if (run == true)
                {
                    using (Graphics g = Graphics.FromImage(finalImage))
                    {
                        g.Clear(Color.Black);
                        for (int y = (int)y_range.Min; y <= (int)y_range.Max; y++)
                        {
                            for (int x = (int)x_range.Min; x <= (int)x_range.Max; x++)
                            {
                                //create tileCache name 
                                string tileCache = mbSource.Replace(" ", "") + zoom + x + y + ".png";
                                string tileCahceLoc = cacheLoc + tileCache;

                                //check cache folder to see if tile image exists locally
                                if (File.Exists(tileCahceLoc))
                                {
                                    Bitmap tmpImage = new Bitmap(Image.FromFile(tileCahceLoc));
                                    //add tmp image to final
                                    g.DrawImage(tmpImage, imgPosW * 512, imgPosH * 512);
                                    tmpImage.Dispose();
                                }

                                else
                                {
                                    tileList.Add(new List<int> { zoom, y, x });
                                    string urlAuth = Convert.GetZoomURL(x, y, zoom, mbURLauth);
                                    System.Net.WebClient client = new System.Net.WebClient();
                                    client.DownloadFile(urlAuth, tileCahceLoc);
                                    Bitmap tmpImage = new Bitmap(Image.FromFile(tileCahceLoc));
                                    client.Dispose();

                                    //add tmp image to final
                                    g.DrawImage(tmpImage, imgPosW * 512, imgPosH * 512);
                                    tmpImage.Dispose();
                                    tileDownloadedCount = tileDownloadedCount + 1;
                                }

                                //increment x insert position, goes left to right
                                imgPosW++;
                            }
                            //increment y insert position, goes top to bottom
                            imgPosH++;
                            imgPosW = 0;

                        }
                        //garbage collection
                        g.Dispose();

                        //add tile range meta data to image comments
                        finalImage.AddCommentsToPNG(mbSource.Replace(" ", "") + tileRangeString);

                        //save out replacedembled image 
                        finalImage.Save(imgPath, System.Drawing.Imaging.ImageFormat.Png);
                    }
                }

                //garbage collection
                finalImage.Dispose();

                //add to tile count total
                tCount.Insert(new GH_String(tileTotalCount + " tiles (" + tileDownloadedCount + " downloaded / " + (tileTotalCount - tileDownloadedCount) + " cached)"), path, 0);


                Mesh nMesh = TopoMeshFromImage(imgPath, boundaryBox, zoom);

                //mesh.Flip(true, true, true);
                tMesh.Append(new GH_Mesh(nMesh), path);

                //write out new tile range metadata for serialization
                TileCacheMeta = tileRangeString;

                
            }

            DA.SetDataTree(0, mapList);
            DA.SetDataTree(1, imgFrame);
            DA.SetDataTree(2, tCount);
            DA.SetDataTree(3, tMesh);
            DA.SetDataList(4, "copyright Mapbox");
            
        }

19 Source : OverlayForm.cs
with BSD 3-Clause "New" or "Revised" License
from Bluegrams

protected override void OnPaint(PaintEventArgs e)
        {
            e.Graphics.Clear(this.BackColor);
            using (var brush = new SolidBrush(SelectionColor))
            {
                e.Graphics.FillRectangle(brush, RectangleToClient(WindowSelection));
            }
        }

19 Source : MapboxRaster_DEPRECATED20211114.cs
with MIT License
from blueherongis

protected override void SolveInstance(IGH_DataAccess DA)
        {
            List<Curve> boundary = new List<Curve>();
            DA.GetDataList<Curve>(0, boundary);

            int zoom = -1;
            DA.GetData<int>(1, ref zoom);

            string folderPath = string.Empty;
            DA.GetData<string>(2, ref folderPath);
            if (!folderPath.EndsWith(@"\")) folderPath = folderPath + @"\";

            string prefix = string.Empty;
            DA.GetData<string>(3, ref prefix);
            if (prefix == "")
            {
                prefix = mbSource;
            }

            string URL = mbURL;
            //DA.GetData<string>(4, ref URL);

            ///get a valid mapbox token to send along with query
            string mbToken = string.Empty;
            DA.GetData<string>(4, ref mbToken);
            if (mbToken == "")
            {
                string hmbToken = System.Environment.GetEnvironmentVariable("HERONMAPBOXTOKEN");
                if (hmbToken != null)
                {
                    mbToken = hmbToken;
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Using Mapbox token stored in Environment Variable HERONMAPBOXTOKEN.");
                }
                else
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "No Mapbox token is specified.  Please get a valid token from mapbox.com");
                    return;
                }
            }

            bool run = false;
            DA.GetData<bool>("Run", ref run);

            GH_Structure<GH_String> mapList = new GH_Structure<GH_String>();
            GH_Structure<GH_Rectangle> imgFrame = new GH_Structure<GH_Rectangle>();
            GH_Structure<GH_String> tCount = new GH_Structure<GH_String>();


            for (int i = 0; i < boundary.Count; i++)
            {
                GH_Path path = new GH_Path(i);
                int tileTotalCount = 0;
                int tileDownloadedCount = 0;


                //Get image frame for given boundary and  make sure it's valid
                if (!boundary[i].GetBoundingBox(true).IsValid)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Boundary is not valid.");
                    return;
                }
                BoundingBox boundaryBox = boundary[i].GetBoundingBox(true);

                ///TODO: look into scaling boundary to get buffer tiles

                ///file path for final image
                string imgPath = folderPath + prefix + "_" + i + ".jpg";

                //location of final image file
                mapList.Append(new GH_String(imgPath), path);

                //create cache folder for images
                string cacheLoc = folderPath + @"HeronCache\";
                List<string> cachefolderPaths = new List<string>();
                if (!Directory.Exists(cacheLoc))
                {
                    Directory.CreateDirectory(cacheLoc);
                }

                //tile bounding box array
                List<Point3d> boxPtList = new List<Point3d>();

                //get the tile coordinates for all tiles within boundary
                var ranges = Convert.GetTileRange(boundaryBox, zoom);
                List<List<int>> tileList = new List<List<int>>();
                var x_range = ranges.XRange;
                var y_range = ranges.YRange;

                if (x_range.Length > 100 || y_range.Length > 100)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "This tile range is too big (more than 100 tiles in the x or y direction). Check your units.");
                    return;
                }

                //cycle through tiles to get bounding box
                for (int y = (int)y_range.Min; y <= y_range.Max; y++)
                {
                    for (int x = (int)x_range.Min; x <= x_range.Max; x++)
                    {
                        //add bounding box of tile to list
                        boxPtList.AddRange(Convert.GetTileAsPolygon(zoom, y, x).ToList());
                        cachefolderPaths.Add(cacheLoc + mbSource.Replace(" ", "") + zoom + x + y + ".jpg");
                        tileTotalCount = tileTotalCount + 1;
                    }
                }

                tCount.Insert(new GH_String(tileTotalCount + " tiles (" + tileDownloadedCount + " downloaded / " + (tileTotalCount - tileDownloadedCount) + " cached)"), path, 0);

                //bounding box of tile boundaries
                BoundingBox bbox = new BoundingBox(boxPtList);

                var rect = BBoxToRect(bbox);
                imgFrame.Append(new GH_Rectangle(rect), path);

                AddPreviewItem(imgPath, boundary[i], rect);

                ///tile range as string for (de)serialization of TileCacheMeta
                string tileRangeString = zoom.ToString()
                    + x_range[0].ToString()
                    + y_range[0].ToString()
                    + x_range[1].ToString()
                    + y_range[1].ToString();

                ///check if the existing final image already covers the boundary. 
                ///if so, no need to download more or rereplacedemble the cached tiles.
                if ((TileCacheMeta == tileRangeString) && Convert.CheckCacheImagesExist(cachefolderPaths))
                {
                    if (File.Exists(imgPath))
                    {
                        using (Bitmap imageT = new Bitmap(imgPath))
                        {
                            ///getting commments currently only working for JPG
                            ///TODO: get this to work for any image type or
                            ///find another way to check if the cached image covers the boundary.
                            string imgComment = imageT.GetCommentsFromJPG();

                            imageT.Dispose();

                            ///check to see if tilerange in comments matches current tilerange
                            if (imgComment == (mbSource.Replace(" ", "") + tileRangeString))
                            {
                                AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Using existing image.");
                                continue;
                            }

                        }

                    }

                }



                ///Query Mapbox URL
                ///download all tiles within boundary
                ///merge tiles into one bitmap
                ///API to query
                string mbURLauth = mbURL + mbToken;


                ///Do the work of replacedembling image
                ///setup final image container bitmap
                int fImageW = ((int)x_range.Length + 1) * 512;
                int fImageH = ((int)y_range.Length + 1) * 512;
                Bitmap finalImage = new Bitmap(fImageW, fImageH);


                int imgPosW = 0;
                int imgPosH = 0;

                if (run == true)
                {
                    using (Graphics g = Graphics.FromImage(finalImage))
                    {
                        g.Clear(Color.Black);
                        for (int y = (int)y_range.Min; y <= (int)y_range.Max; y++)
                        {
                            for (int x = (int)x_range.Min; x <= (int)x_range.Max; x++)
                            {
                                ///create tileCache name 
                                string tileCache = mbSource.Replace(" ", "") + zoom + x + y + ".jpg";
                                string tileCahceLoc = cacheLoc + tileCache;

                                ///check cache folder to see if tile image exists locally
                                if (File.Exists(tileCahceLoc))
                                {
                                    Bitmap tmpImage = new Bitmap(Image.FromFile(tileCahceLoc));
                                    ///add tmp image to final
                                    g.DrawImage(tmpImage, imgPosW * 512, imgPosH * 512);
                                    tmpImage.Dispose();
                                }

                                else
                                {
                                    tileList.Add(new List<int> { zoom, y, x });
                                    string urlAuth = Convert.GetZoomURL(x, y, zoom, mbURLauth);

                                    System.Net.WebClient client = new System.Net.WebClient();
                                    client.DownloadFile(urlAuth, tileCahceLoc);
                                    Bitmap tmpImage = new Bitmap(Image.FromFile(tileCahceLoc));
                                    client.Dispose();

                                    ///add tmp image to final
                                    g.DrawImage(tmpImage, imgPosW * 512, imgPosH * 512);
                                    tmpImage.Dispose();
                                    tileDownloadedCount = tileDownloadedCount + 1;
                                }

                                ///increment x insert position, goes left to right
                                imgPosW++;
                            }
                            ///increment y insert position, goes top to bottom
                            imgPosH++;
                            imgPosW = 0;

                        }
                        ///garbage collection
                        g.Dispose();

                        ///add tile range meta data to image comments
                        finalImage.AddCommentsToJPG(mbSource.Replace(" ", "") + tileRangeString);

                        ///save the image
                        finalImage.Save(imgPath, System.Drawing.Imaging.ImageFormat.Jpeg);
                    }
                }

                //garbage collection
                finalImage.Dispose();


                //add to tile count total
                tCount.Insert(new GH_String(tileTotalCount + " tiles (" + tileDownloadedCount + " downloaded / " + (tileTotalCount - tileDownloadedCount) + " cached)"), path, 0);

                //write out new tile range metadata for serialization
                TileCacheMeta = tileRangeString;

                //AddPreviewItem(imgPath, boundary[i], rect);

            }


            DA.SetDataTree(0, mapList);
            DA.SetDataTree(1, imgFrame);
            DA.SetDataTree(2, tCount);
            DA.SetDataList(3, "copyright Mapbox");

        }

19 Source : SlippyRaster_DEPRECATED2021114.cs
with MIT License
from blueherongis

protected override void SolveInstance(IGH_DataAccess DA)
        {
            List<Curve> boundary = new List<Curve>();
            DA.GetDataList(0, boundary);

            int zoom = -1;
            DA.GetData(1, ref zoom);

            string filePath = string.Empty;
            DA.GetData(2, ref filePath);
            if (!filePath.EndsWith(@"\")) filePath = filePath + @"\";

            string prefix = string.Empty;
            DA.GetData(3, ref prefix);
            if (prefix == string.Empty)
            {
                prefix = slippySource;
            }

            string URL = slippyURL;
            //DA.GetData<string>(4, ref URL);

            string userAgent = string.Empty;
            DA.GetData(4, ref userAgent);

            bool run = false;
            DA.GetData<bool>("Run", ref run);

            GH_Structure<GH_String> mapList = new GH_Structure<GH_String>();
            GH_Structure<GH_Rectangle> imgFrame = new GH_Structure<GH_Rectangle>();
            GH_Structure<GH_String> tCount = new GH_Structure<GH_String>();


            for (int i = 0; i < boundary.Count; i++)
            {
                GH_Path path = new GH_Path(i);
                int tileTotalCount = 0;
                int tileDownloadedCount = 0;


                ///Get image frame for given boundary and  make sure it's valid
                if (!boundary[i].GetBoundingBox(true).IsValid)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Boundary is not valid.");
                    return;
                }
                BoundingBox boundaryBox = boundary[i].GetBoundingBox(true);

                ///TODO: look into scaling boundary to get buffer tiles

                ///file path for final image
                string imgPath = filePath + prefix + "_" + i + ".jpg";

                ///location of final image file
                mapList.Append(new GH_String(imgPath), path);

                ///create cache folder for images
                string cacheLoc = filePath + @"HeronCache\";
                List<string> cachefilePaths = new List<string>();
                if (!Directory.Exists(cacheLoc))
                {
                    Directory.CreateDirectory(cacheLoc);
                }

                ///tile bounding box array
                List<Point3d> boxPtList = new List<Point3d>();

                ///get the tile coordinates for all tiles within boundary
                var ranges = Convert.GetTileRange(boundaryBox, zoom);
                List<List<int>> tileList = new List<List<int>>();
                var x_range = ranges.XRange;
                var y_range = ranges.YRange;

                if (x_range.Length > 100 || y_range.Length > 100)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "This tile range is too big (more than 100 tiles in the x or y direction). Check your units.");
                    return;
                }

                ///cycle through tiles to get bounding box
                for (int y = (int)y_range.Min; y <= y_range.Max; y++)
                {
                    for (int x = (int)x_range.Min; x <= x_range.Max; x++)
                    {
                        ///add bounding box of tile to list
                        boxPtList.AddRange(Convert.GetTileAsPolygon(zoom, y, x).ToList());
                        cachefilePaths.Add(cacheLoc + slippySource.Replace(" ", "") + zoom + x + y + ".jpg");
                        tileTotalCount = tileTotalCount + 1;
                    }
                }

                tCount.Insert(new GH_String(tileTotalCount + " tiles (" + tileDownloadedCount + " downloaded / " + (tileTotalCount - tileDownloadedCount) + " cached)"), path, 0);

                ///bounding box of tile boundaries
                BoundingBox bbox = new BoundingBox(boxPtList);

                var rect = BBoxToRect(bbox);
                imgFrame.Append(new GH_Rectangle(rect), path);

                AddPreviewItem(imgPath, boundary[i], rect);

                ///tile range as string for (de)serialization of TileCacheMeta
                string tileRangeString = zoom.ToString()
                    + x_range[0].ToString()
                    + y_range[0].ToString()
                    + x_range[1].ToString()
                    + y_range[1].ToString();

                ///check if the existing final image already covers the boundary. 
                ///if so, no need to download more or rereplacedemble the cached tiles.
                if ((TileCacheMeta == tileRangeString) && Convert.CheckCacheImagesExist(cachefilePaths))
                {
                    if (File.Exists(imgPath))
                    {
                        using (Bitmap imageT = new Bitmap(imgPath))
                        {
                            ///getting commments currently only working for JPG
                            ///TODO: get this to work for any image type or
                            ///find another way to check if the cached image covers the boundary.
                            string imgComment = imageT.GetCommentsFromJPG();

                            imageT.Dispose();

                            ///check to see if tilerange in comments matches current tilerange
                            if (imgComment == (slippySource.Replace(" ", "") + tileRangeString))
                            {
                                AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Using existing image.");
                                continue;
                            }

                        }

                    }

                }



                ///Query Slippy URL
                ///download all tiles within boundary
                ///merge tiles into one bitmap
                ///API to query


                ///Do the work of replacedembling image
                ///setup final image container bitmap
                int fImageW = ((int)x_range.Length + 1) * 256;
                int fImageH = ((int)y_range.Length + 1) * 256;
                Bitmap finalImage = new Bitmap(fImageW, fImageH);


                int imgPosW = 0;
                int imgPosH = 0;

                if (run == true)
                {
                    using (Graphics g = Graphics.FromImage(finalImage))
                    {
                        g.Clear(Color.Black);
                        for (int y = (int)y_range.Min; y <= (int)y_range.Max; y++)
                        {
                            for (int x = (int)x_range.Min; x <= (int)x_range.Max; x++)
                            {
                                //create tileCache name 
                                string tileCache = slippySource.Replace(" ", "") + zoom + x + y + ".jpg";
                                string tileCacheLoc = cacheLoc + tileCache;

                                //check cache folder to see if tile image exists locally
                                if (File.Exists(tileCacheLoc))
                                {
                                    Bitmap tmpImage = new Bitmap(Image.FromFile(tileCacheLoc));
                                    ///add tmp image to final
                                    g.DrawImage(tmpImage, imgPosW * 256, imgPosH * 256);
                                    tmpImage.Dispose();
                                }

                                else
                                {
                                    tileList.Add(new List<int> { zoom, y, x });
                                    string urlAuth = Convert.GetZoomURL(x, y, zoom, slippyURL);

                                    System.Net.WebClient client = new System.Net.WebClient();

                                    ///insert header if required
                                    client.Headers.Add("user-agent", userAgent);

                                    client.DownloadFile(urlAuth, tileCacheLoc);
                                    Bitmap tmpImage = new Bitmap(Image.FromFile(tileCacheLoc));
                                    client.Dispose();

                                    //add tmp image to final
                                    g.DrawImage(tmpImage, imgPosW * 256, imgPosH * 256);
                                    tmpImage.Dispose();
                                    tileDownloadedCount = tileDownloadedCount + 1;
                                }

                                //increment x insert position, goes left to right
                                imgPosW++;
                            }
                            //increment y insert position, goes top to bottom
                            imgPosH++;
                            imgPosW = 0;

                        }
                        //garbage collection
                        g.Dispose();

                        //add tile range meta data to image comments
                        finalImage.AddCommentsToJPG(slippySource.Replace(" ", "") + tileRangeString);

                        //save the image
                        finalImage.Save(imgPath, System.Drawing.Imaging.ImageFormat.Jpeg);
                    }
                }

                //garbage collection
                finalImage.Dispose();


                //add to tile count total
                tCount.Insert(new GH_String(tileTotalCount + " tiles (" + tileDownloadedCount + " downloaded / " + (tileTotalCount - tileDownloadedCount) + " cached)"), path, 0);

                //write out new tile range metadata for serialization
                TileCacheMeta = tileRangeString;

            }


            DA.SetDataTree(0, mapList);
            DA.SetDataTree(1, imgFrame);
            DA.SetDataTree(2, tCount);
            ///Add copyright info here
            DA.SetDataList(3, "");

        }

19 Source : SlippyRaster.cs
with MIT License
from blueherongis

protected override void SolveInstance(IGH_DataAccess DA)
        {
            List<Curve> boundary = new List<Curve>();
            DA.GetDataList(0, boundary);

            int zoom = -1;
            DA.GetData(1, ref zoom);

            string filePath = string.Empty;
            DA.GetData(2, ref filePath);
            if (!filePath.EndsWith(@"\")) filePath = filePath + @"\";

            string prefix = string.Empty;
            DA.GetData(3, ref prefix);
            if (prefix == string.Empty)
            {
                prefix = slippySource;
            }

            string URL = slippyURL;

            string userAgent = string.Empty;
            DA.GetData(4, ref userAgent);

            bool run = false;
            DA.GetData<bool>("Run", ref run);

            GH_Structure<GH_String> mapList = new GH_Structure<GH_String>();
            GH_Structure<GH_Rectangle> imgFrame = new GH_Structure<GH_Rectangle>();
            GH_Structure<GH_String> tCount = new GH_Structure<GH_String>();

            


            for (int i = 0; i < boundary.Count; i++)
            {
                GH_Path path = new GH_Path(i);
                int tileTotalCount = 0;
                int tileDownloadedCount = 0;


                ///Get image frame for given boundary and  make sure it's valid
                if (!boundary[i].GetBoundingBox(true).IsValid)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Boundary is not valid.");
                    return;
                }
                BoundingBox boundaryBox = boundary[i].GetBoundingBox(true);

                ///TODO: look into scaling boundary to get buffer tiles

                ///file path for final image
                string imgPath = filePath + prefix + "_" + i + ".jpg";

                if (!tilesOut)
                {
                    //location of final image file
                    mapList.Append(new GH_String(imgPath), path);
                }

                ///create cache folder for images
                string cacheLoc = filePath + @"HeronCache\";
                List<string> cacheFilePaths = new List<string>();
                if (!Directory.Exists(cacheLoc))
                {
                    Directory.CreateDirectory(cacheLoc);
                }

                ///tile bounding box array
                List<Point3d> boxPtList = new List<Point3d>();

                ///get the tile coordinates for all tiles within boundary
                var ranges = Convert.GetTileRange(boundaryBox, zoom);
                List<List<int>> tileList = new List<List<int>>();
                var x_range = ranges.XRange;
                var y_range = ranges.YRange;

                if (x_range.Length > 100 || y_range.Length > 100)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "This tile range is too big (more than 100 tiles in the x or y direction). Check your units.");
                    return;
                }

                List<Rectangle3d> tileRectangles = new List<Rectangle3d>();

                ///cycle through tiles to get bounding box
                for (int y = (int)y_range.Min; y <= y_range.Max; y++)
                {
                    for (int x = (int)x_range.Min; x <= x_range.Max; x++)
                    {
                        ///add bounding box of tile to list
                        List<Point3d> boxPts = Convert.GetTileAsPolygon(zoom, y, x).ToList();
                        boxPtList.AddRange(Convert.GetTileAsPolygon(zoom, y, x).ToList());
                        string cacheFilePath = cacheLoc + slippySource.Replace(" ", "") + zoom + "-" + x + "-" + y + ".jpg";
                        cacheFilePaths.Add(cacheFilePath);

                        tileTotalCount = tileTotalCount + 1;

                        if (tilesOut)
                        {
                            mapList.Append(new GH_String(cacheFilePath), path);
                            Rectangle3d tileRectangle = BBoxToRect(new BoundingBox(boxPts));
                            tileRectangles.Add(tileRectangle);
                            imgFrame.Append(new GH_Rectangle(tileRectangle), path);
                        }
                    }
                }

                tCount.Insert(new GH_String(tileTotalCount + " tiles (" + tileDownloadedCount + " downloaded / " + (tileTotalCount - tileDownloadedCount) + " cached)"), path, 0);

                ///bounding box of tile boundaries
                BoundingBox bbox = new BoundingBox(boxPtList);

                var rect = BBoxToRect(bbox);
                if (!tilesOut)
                {
                    imgFrame.Append(new GH_Rectangle(rect), path);
                }

                //AddPreviewItem(imgPath, boundary[i], rect);

                ///tile range as string for (de)serialization of TileCacheMeta
                string tileRangeString = zoom.ToString()
                    + x_range[0].ToString()
                    + y_range[0].ToString()
                    + x_range[1].ToString()
                    + y_range[1].ToString();

                ///check if the existing final image already covers the boundary. 
                ///if so, no need to download more or rereplacedemble the cached tiles.
                if ((TileCacheMeta == tileRangeString) && Convert.CheckCacheImagesExist(cacheFilePaths))
                {
                    if (File.Exists(imgPath) && !tilesOut)
                    {
                        using (Bitmap imageT = new Bitmap(imgPath))
                        {
                            ///getting commments currently only working for JPG
                            ///TODO: get this to work for any image type or
                            ///find another way to check if the cached image covers the boundary.
                            string imgComment = imageT.GetCommentsFromJPG();

                            imageT.Dispose();

                            ///check to see if tilerange in comments matches current tilerange
                            if (imgComment == (slippySource.Replace(" ", "") + tileRangeString))
                            {
                                AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Using existing image.");
                                AddPreviewItem(imgPath, boundary[i], rect);
                                continue;
                            }

                        }

                    }

                    if (tilesOut)
                    {
                        for (int t = 0; t < cacheFilePaths.Count; t++)
                        {
                            if (File.Exists(cacheFilePaths[t]))
                            {
                                AddPreviewItem(cacheFilePaths[t], tileRectangles[t].ToNurbsCurve(), tileRectangles[t]);
                            }
                        }
                        continue;
                    }

                }



                ///Query Slippy URL
                ///download all tiles within boundary
                ///merge tiles into one bitmap
                ///API to query


                ///Do the work of replacedembling image
                ///setup final image container bitmap
                int fImageW = ((int)x_range.Length + 1) * 256;
                int fImageH = ((int)y_range.Length + 1) * 256;
                Bitmap finalImage = new Bitmap(fImageW, fImageH);


                int imgPosW = 0;
                int imgPosH = 0;

                using (Graphics g = Graphics.FromImage(finalImage))
                {
                    g.Clear(Color.Black);
                    for (int y = (int)y_range.Min; y <= (int)y_range.Max; y++)
                    {
                        for (int x = (int)x_range.Min; x <= (int)x_range.Max; x++)
                        {
                            //create tileCache name 
                            string tileCache = slippySource.Replace(" ", "") + zoom + "-" + x + "-" + y + ".jpg";
                            string tileCacheLoc = cacheLoc + tileCache;

                            //check cache folder to see if tile image exists locally
                            if (File.Exists(tileCacheLoc))
                            {
                                Bitmap tmpImage = new Bitmap(Image.FromFile(tileCacheLoc));
                                ///add tmp image to final
                                g.DrawImage(tmpImage, imgPosW * 256, imgPosH * 256);
                                tmpImage.Dispose();
                            }

                            else
                            {
                                tileList.Add(new List<int> { zoom, y, x });
                                string urlAuth = Convert.GetZoomURL(x, y, zoom, slippyURL);

                                Bitmap tmpImage = new Bitmap(256, 256);
                                System.Net.WebClient client = new System.Net.WebClient();

                                ///insert header if required
                                client.Headers.Add("user-agent", userAgent);
                                if (run == true)
                                {
                                    try
                                    {
                                        client.DownloadFile(urlAuth, tileCacheLoc);
                                        tmpImage = new Bitmap(Image.FromFile(tileCacheLoc));
                                    }
                                    catch (WebException e)
                                    {
                                        using (Graphics tmp = Graphics.FromImage(tmpImage)) { tmp.Clear(Color.White); }
                                        AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, e.Message);
                                    }
                                }
                                client.Dispose();

                                //add tmp image to final
                                g.DrawImage(tmpImage, imgPosW * 256, imgPosH * 256);
                                tmpImage.Dispose();
                                tileDownloadedCount = tileDownloadedCount + 1;
                            }

                            //increment x insert position, goes left to right
                            imgPosW++;
                        }
                        //increment y insert position, goes top to bottom
                        imgPosH++;
                        imgPosW = 0;

                    }
                    //garbage collection
                    g.Dispose();

                    //add tile range meta data to image comments
                    finalImage.AddCommentsToJPG(slippySource.Replace(" ", "") + tileRangeString);

                    

                    //save the image
                    finalImage.Save(imgPath, System.Drawing.Imaging.ImageFormat.Jpeg);
                }

                //garbage collection
                finalImage.Dispose();

                if (!tilesOut)
                {
                    AddPreviewItem(imgPath, boundary[i], rect);
                }
                else
                {
                    for (int t = 0; t < cacheFilePaths.Count; t++)
                    {
                        if (File.Exists(cacheFilePaths[t]))
                        {
                            AddPreviewItem(cacheFilePaths[t], tileRectangles[t].ToNurbsCurve(), tileRectangles[t]);
                        }
                    }
                }

                //add to tile count total
                tCount.Insert(new GH_String(tileTotalCount + " tiles (" + tileDownloadedCount + " downloaded / " + (tileTotalCount - tileDownloadedCount) + " cached)"), path, 0);

                //write out new tile range metadata for serialization
                TileCacheMeta = tileRangeString;

            }


            DA.SetDataTree(0, mapList);
            DA.SetDataTree(1, imgFrame);
            DA.SetDataTree(2, tCount);
            ///Add copyright info here
            DA.SetDataList(3, "");

        }

See More Examples