示例#1
0
        private static void LoadImageFromResxAndMakeInverseCopy(string resxImgName,
                                                                out Bitmap imgNormal, out Bitmap imgInverse)
        {
            using (var imageStream = Assembly.GetCallingAssembly().GetManifestResourceStream(resxImgName))
            {
                imgNormal = new Bitmap(imageStream);
            }

            // копия
            // получить байты картинки
            var rect    = new Rectangle(0, 0, imgNormal.Width, imgNormal.Height);
            var bmpData =
                imgNormal.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite,
                                   imgNormal.PixelFormat);
            var ptr       = bmpData.Scan0;
            var bytes     = Math.Abs(bmpData.Stride) * imgNormal.Height;
            var rgbValues = new byte[bytes];

            System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes);
            imgNormal.UnlockBits(bmpData);

            // обработать байты картинки
            for (var counter = 0; counter < rgbValues.Length; counter += 4)
            {
                var r = rgbValues[counter];
                var g = rgbValues[counter + 1];
                var b = rgbValues[counter + 2];
                GraphicsExtensions.InvertColorLightness(ref r, ref g, ref b);
                rgbValues[counter]     = r;
                rgbValues[counter + 1] = g;
                rgbValues[counter + 2] = b;
            }

            // открыть новую картинку на запись
            imgInverse = new Bitmap(imgNormal);
            bmpData    =
                imgInverse.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite,
                                    imgInverse.PixelFormat);
            ptr = bmpData.Scan0;
            System.Runtime.InteropServices.Marshal.Copy(rgbValues, 0, ptr, bytes);

            // закрыть картинку
            imgInverse.UnlockBits(bmpData);
        }
示例#2
0
        public void ClipToBorder(Graphics graphics, Rectangle rectangle, IRuleset ruleset)
        {
            Region region = new Region(rectangle);

            if (ruleset.Any(p => p.IsBorderRadiusProperty()))
            {
                region.Intersect(GraphicsExtensions.CreateRoundedRectangle(rectangle,
                                                                           (int)(ruleset.BorderTopLeftRadius?.Value ?? 0),
                                                                           (int)(ruleset.BorderTopRightRadius?.Value ?? 0),
                                                                           (int)(ruleset.BorderBottomLeftRadius?.Value ?? 0),
                                                                           (int)(ruleset.BorderBottomRightRadius?.Value ?? 0)));
            }
            else
            {
                region.Intersect(rectangle);
            }

            graphics.SetClip(region, CombineMode.Intersect);
        }
示例#3
0
        private bool SwitchLineStyle(FontStyle style, Color?colorNew, bool changeColor)
        {
            tbText.SelectionChanged -= TbTextSelectionChanged;

            var cursorPosition = tbText.SelectionStart;
            var lineIndex      = tbText.GetLineFromCharIndex(cursorPosition);

            if (lineIndex < 0 || lineIndex >= tbText.Lines.Length)
            {
                return(false);
            }
            var lineText = tbText.Lines[lineIndex];

            FontStyle oldStyle;
            Color?    color;
            var       linePure     = GraphicsExtensions.GetLineModifiers(lineText, out oldStyle, out color);
            var       hadThisStyle = (oldStyle & style) == style;

            // вернуть линии все модификаторы, но добавить/убрать указанный
            if (hadThisStyle)
            {
                oldStyle = oldStyle & ~style;
            }
            else
            {
                oldStyle = oldStyle | style;
            }

            // форматировать линию обратно
            var line = GraphicsExtensions.FormatLine(linePure, oldStyle,
                                                     changeColor ? colorNew : color);

            // запихнуть линию в текст
            var oldLines = tbText.Lines.ToArray();

            oldLines[lineIndex] = line;
            tbText.Lines        = oldLines;

            tbText.SelectionChanged += TbTextSelectionChanged;

            return(hadThisStyle);
        }
        public void CloneTest5()
        {
            BitmapCloner target   = new BitmapCloner();
            var          fileName = Path.Combine(testContextInstance.TestDeploymentDir, "smile.png");

            using (var bitmap = new Bitmap(fileName))
            {
                long expectedDistance = 1024 * 32;
                var  stopwatch        = Stopwatch.StartNew();
                var  actual           = target.Clone(bitmap, expectedDistance, 2);
                stopwatch.Stop();
                var actualDistance = VectorDrawingGenetics.Instance.CalculateFitness(actual, bitmap);
                Assert.IsTrue(actualDistance <= expectedDistance);
                using (var cloneBitmap = new Bitmap(bitmap.Width, bitmap.Height))
                {
                    using (var graphics = Graphics.FromImage(cloneBitmap))
                    {
                        GraphicsExtensions.RasterizeVectorDrawing(graphics, actual);
                    }
                    cloneBitmap.Save("smile.bmp", ImageFormat.Bmp);
                }
            }
        }
示例#5
0
        /// <summary>
        /// Capture transparent Screenshot of a Window.
        /// </summary>
        public static IBitmapImage CaptureTransparent(IWindow Window, bool IncludeCursor, IPlatformServices PlatformServices)
        {
            if (Window == null)
            {
                throw new ArgumentNullException(nameof(Window));
            }

            var backdrop = new WindowScreenShotBackdrop(Window, PlatformServices);

            backdrop.ShowWhite();

            var r = backdrop.Rectangle;

            // Capture screenshot with white background
            using var whiteShot = CaptureInternal(r);
            backdrop.ShowBlack();

            // Capture screenshot with black background
            using var blackShot = CaptureInternal(r);
            backdrop.Dispose();

            var transparentImage = GraphicsExtensions.DifferentiateAlpha(whiteShot, blackShot);

            if (transparentImage == null)
            {
                return(null);
            }

            // Include Cursor only if within window
            if (IncludeCursor && r.Contains(PlatformServices.CursorPosition))
            {
                using var g = Graphics.FromImage(transparentImage);
                MouseCursor.Draw(g, P => new Point(P.X - r.X, P.Y - r.Y));
            }

            return(new DrawingImage(transparentImage.CropEmptyEdges()));
        }
示例#6
0
        /// <summary>
        /// Runs the given action on the UI thread and blocks the current thread while the action is running.
        /// If the current thread is the UI thread, the action will run immediately.
        /// </summary>
        /// <param name="action">The action to be run on the UI thread</param>
        internal static void BlockOnUIThread(Action action)
        {
            if (action == null)
            {
                throw new ArgumentNullException("action");
            }

#if (DIRECTX && !WINDOWS_PHONE) || PSM
            action();
#else
            // If we are already on the UI thread, just call the action and be done with it
            if (IsOnUIThread())
            {
                try
                {
                    action();
                }
                catch (UnauthorizedAccessException ex)
                {
                    // Need to be on a different thread
#if WINDOWS_PHONE
                    BlockOnContainerThread(Deployment.Current.Dispatcher, action);
#else
                    throw (ex);
#endif
                }
                return;
            }

#if IOS
            lock (BackgroundContext)
            {
                // Make the context current on this thread if it is not already
                if (!Object.ReferenceEquals(EAGLContext.CurrentContext, BackgroundContext))
                {
                    EAGLContext.SetCurrentContext(BackgroundContext);
                }
                // Execute the action
                action();
                // Must flush the GL calls so the GPU asset is ready for the main context to use it
                GL.Flush();
                GraphicsExtensions.CheckGLError();
            }
#elif WINDOWS || LINUX || ANGLE
            lock (BackgroundContext)
            {
                // Make the context current on this thread
                BackgroundContext.MakeCurrent(WindowInfo);
                // Execute the action
                action();
                // Must flush the GL calls so the texture is ready for the main context to use
                GL.Flush();
                GraphicsExtensions.CheckGLError();
                // Must make the context not current on this thread or the next thread will get error 170 from the MakeCurrent call
                BackgroundContext.MakeCurrent(null);
            }
#elif WINDOWS_PHONE
            BlockOnContainerThread(Deployment.Current.Dispatcher, action);
#else
            ManualResetEventSlim resetEvent = new ManualResetEventSlim(false);
#if MONOMAC
            MonoMac.AppKit.NSApplication.SharedApplication.BeginInvokeOnMainThread(() =>
#else
            Add(() =>
#endif
            {
#if ANDROID
                //if (!Game.Instance.Window.GraphicsContext.IsCurrent)
                ((AndroidGameWindow)Game.Instance.Window).GameView.MakeCurrent();
#endif
                action();
                resetEvent.Set();
            });
            resetEvent.Wait();
#endif
#endif
        }
示例#7
0
        protected internal override Texture2D Read(ContentReader reader, Texture2D existingInstance)
        {
            SurfaceFormat surfaceFormat;

            if (reader.version < 5)
            {
                switch ((SurfaceFormat_Legacy)reader.ReadInt32())
                {
                case SurfaceFormat_Legacy.Color:
                    surfaceFormat = SurfaceFormat.Color;
                    break;

                case SurfaceFormat_Legacy.Dxt1:
                    surfaceFormat = SurfaceFormat.Dxt1;
                    break;

                case SurfaceFormat_Legacy.Dxt3:
                    surfaceFormat = SurfaceFormat.Dxt3;
                    break;

                case SurfaceFormat_Legacy.Dxt5:
                    surfaceFormat = SurfaceFormat.Dxt5;
                    break;

                default:
                    throw new NotImplementedException();
                }
            }
            else
            {
                surfaceFormat = (SurfaceFormat)reader.ReadInt32();
            }
            int width1  = reader.ReadInt32();
            int height1 = reader.ReadInt32();
            int num1    = reader.ReadInt32();
            int num2    = num1;

            if (num1 > 1 && !GraphicsCapabilities.NonPowerOfTwo && (!MathHelper.IsPowerOfTwo(width1) || !MathHelper.IsPowerOfTwo(height1)))
            {
                num2 = 1;
            }
            SurfaceFormat format = surfaceFormat;

            if (surfaceFormat == SurfaceFormat.NormalizedByte4)
            {
                format = SurfaceFormat.Color;
            }
            if (!GraphicsExtensions.UseDxtCompression)
            {
                switch (surfaceFormat)
                {
                case SurfaceFormat.Dxt1:
                case SurfaceFormat.Dxt3:
                case SurfaceFormat.Dxt5:
                    format = SurfaceFormat.Color;
                    break;
                }
            }
            Texture2D texture2D = existingInstance != null ? existingInstance : new Texture2D(reader.GraphicsDevice, width1, height1, num2 > 1, format);

            for (int level = 0; level < num1; ++level)
            {
                int    count    = reader.ReadInt32();
                byte[] numArray = reader.ReadBytes(count);
                int    width2   = width1 >> level;
                int    height2  = height1 >> level;
                if (level < num2)
                {
                    if (!GraphicsExtensions.UseDxtCompression)
                    {
                        switch (surfaceFormat)
                        {
                        case SurfaceFormat.Dxt1:
                            numArray = DxtUtil.DecompressDxt1(numArray, width2, height2);
                            break;

                        case SurfaceFormat.Dxt3:
                            numArray = DxtUtil.DecompressDxt3(numArray, width2, height2);
                            break;

                        case SurfaceFormat.Dxt5:
                            numArray = DxtUtil.DecompressDxt5(numArray, width2, height2);
                            break;
                        }
                    }
                    switch (surfaceFormat)
                    {
                    case SurfaceFormat.Bgra5551:
                        int startIndex1 = 0;
                        for (int index1 = 0; index1 < height2; ++index1)
                        {
                            for (int index2 = 0; index2 < width2; ++index2)
                            {
                                ushort num3 = BitConverter.ToUInt16(numArray, startIndex1);
                                ushort num4 = (ushort)(((int)num3 & (int)short.MaxValue) << 1 | ((int)num3 & 32768) >> 15);
                                numArray[startIndex1]     = (byte)num4;
                                numArray[startIndex1 + 1] = (byte)((uint)num4 >> 8);
                                startIndex1 += 2;
                            }
                        }
                        break;

                    case SurfaceFormat.Bgra4444:
                        int startIndex2 = 0;
                        for (int index1 = 0; index1 < height2; ++index1)
                        {
                            for (int index2 = 0; index2 < width2; ++index2)
                            {
                                ushort num3 = BitConverter.ToUInt16(numArray, startIndex2);
                                ushort num4 = (ushort)(((int)num3 & 4095) << 4 | ((int)num3 & 61440) >> 12);
                                numArray[startIndex2]     = (byte)num4;
                                numArray[startIndex2 + 1] = (byte)((uint)num4 >> 8);
                                startIndex2 += 2;
                            }
                        }
                        break;

                    case SurfaceFormat.NormalizedByte4:
                        int num5 = GraphicsExtensions.Size(surfaceFormat);
                        int num6 = width2 * num5;
                        for (int index1 = 0; index1 < height2; ++index1)
                        {
                            for (int index2 = 0; index2 < width2; ++index2)
                            {
                                int num3 = BitConverter.ToInt32(numArray, index1 * num6 + index2 * num5);
                                numArray[index1 * num6 + index2 * 4]     = (byte)(num3 >> 16 & (int)byte.MaxValue);
                                numArray[index1 * num6 + index2 * 4 + 1] = (byte)(num3 >> 8 & (int)byte.MaxValue);
                                numArray[index1 * num6 + index2 * 4 + 2] = (byte)(num3 & (int)byte.MaxValue);
                                numArray[index1 * num6 + index2 * 4 + 3] = (byte)(num3 >> 24 & (int)byte.MaxValue);
                            }
                        }
                        break;
                    }
                    texture2D.SetData <byte>(level, new Rectangle?(), numArray, 0, numArray.Length);
                }
            }
            return(texture2D);
        }
示例#8
0
        protected internal override Texture2D Read(ContentReader reader, Texture2D existingInstance)
        {
            SurfaceFormat surfaceFormat;

            if (reader.version < 5)
            {
                switch ((SurfaceFormat_Legacy)reader.ReadInt32())
                {
                case SurfaceFormat_Legacy.Color:
                    surfaceFormat = SurfaceFormat.Color;
                    break;

                case SurfaceFormat_Legacy.Dxt1:
                    surfaceFormat = SurfaceFormat.Dxt1;
                    break;

                case SurfaceFormat_Legacy.Dxt3:
                    surfaceFormat = SurfaceFormat.Dxt3;
                    break;

                case SurfaceFormat_Legacy.Dxt5:
                    surfaceFormat = SurfaceFormat.Dxt5;
                    break;

                default:
                    throw new NotImplementedException();
                }
            }
            else
            {
                surfaceFormat = (SurfaceFormat)reader.ReadInt32();
            }
            int           width  = reader.ReadInt32();
            int           height = reader.ReadInt32();
            int           num1   = reader.ReadInt32();
            SurfaceFormat format = surfaceFormat;

            if (surfaceFormat == SurfaceFormat.NormalizedByte4)
            {
                format = SurfaceFormat.Color;
            }
            Texture2D texture2D = existingInstance != null ? existingInstance : new Texture2D(reader.GraphicsDevice, width, height, num1 > 1, format);

            for (int level = 0; level < num1; ++level)
            {
                int    count = reader.ReadInt32();
                byte[] data  = reader.ReadBytes(count);
                int    num2  = width >> level;
                int    num3  = height >> level;
                switch (surfaceFormat)
                {
                case SurfaceFormat.Bgra4444:
                    int startIndex = 0;
                    for (int index1 = 0; index1 < num3; ++index1)
                    {
                        for (int index2 = 0; index2 < num2; ++index2)
                        {
                            ushort num4 = BitConverter.ToUInt16(data, startIndex);
                            ushort num5 = (ushort)(((int)num4 & 4095) << 4 | ((int)num4 & 61440) >> 12);
                            data[startIndex]     = (byte)num5;
                            data[startIndex + 1] = (byte)((uint)num5 >> 8);
                            startIndex          += 2;
                        }
                    }
                    break;

                case SurfaceFormat.NormalizedByte4:
                    int num6 = GraphicsExtensions.Size(surfaceFormat);
                    int num7 = num2 * num6;
                    for (int index1 = 0; index1 < num3; ++index1)
                    {
                        for (int index2 = 0; index2 < num2; ++index2)
                        {
                            int num4 = BitConverter.ToInt32(data, index1 * num7 + index2 * num6);
                            data[index1 * num7 + index2 * 4]     = (byte)(num4 >> 16 & (int)byte.MaxValue);
                            data[index1 * num7 + index2 * 4 + 1] = (byte)(num4 >> 8 & (int)byte.MaxValue);
                            data[index1 * num7 + index2 * 4 + 2] = (byte)(num4 & (int)byte.MaxValue);
                            data[index1 * num7 + index2 * 4 + 3] = (byte)(num4 >> 24 & (int)byte.MaxValue);
                        }
                    }
                    break;
                }
                texture2D.SetData <byte>(level, new Rectangle?(), data, 0, data.Length);
            }
            return(texture2D);
        }
 public override void Draw()
 {
     GraphicsExtensions circle = new GraphicsExtensions();
     circle.DrawCircle(30,30,20);
 }
示例#10
0
        /// <summary>
        /// Runs the given action on the UI thread and blocks the current thread while the action is running.
        /// If the current thread is the UI thread, the action will run immediately.
        /// </summary>
        /// <param name="action">The action to be run on the UI thread</param>
        internal static void BlockOnUIThread(Action action)
        {
            if (action == null)
            {
                throw new ArgumentNullException("action");
            }

#if DIRECTX || PSM
            action();
#else
            // If we are already on the UI thread, just call the action and be done with it
            if (mainThreadId == Thread.CurrentThread.ManagedThreadId)
            {
                action();
                return;
            }

#if IOS
            lock (BackgroundContext)
            {
                // Make the context current on this thread if it is not already
                if (!Object.ReferenceEquals(EAGLContext.CurrentContext, BackgroundContext))
                {
                    EAGLContext.SetCurrentContext(BackgroundContext);
                }
                // Execute the action
                action();
                // Must flush the GL calls so the GPU asset is ready for the main context to use it
                GL.Flush();
                GraphicsExtensions.CheckGLError();
            }
#elif WINDOWS || LINUX
            lock (BackgroundContext)
            {
                // Make the context current on this thread
                BackgroundContext.MakeCurrent(WindowInfo);
                // Execute the action
                action();
                // Must flush the GL calls so the texture is ready for the main context to use
                GL.Flush();
                GraphicsExtensions.CheckGLError();
                // Must make the context not current on this thread or the next thread will get error 170 from the MakeCurrent call
                BackgroundContext.MakeCurrent(null);
            }
#elif !PORTABLE
            ManualResetEventSlim resetEvent = new ManualResetEventSlim(false);
#if MONOMAC
            MonoMac.AppKit.NSApplication.SharedApplication.BeginInvokeOnMainThread(() =>
#else
            Add(() =>
#endif
            {
#if ANDROID
                //if (!Game.Instance.Window.GraphicsContext.IsCurrent)
                Game.Instance.Window.MakeCurrent();
#endif
                action();
                resetEvent.Set();
            });
            resetEvent.Wait();
#endif
#endif
        }
示例#11
0
        /// <summary>
        /// Draws the control in normal or pushed states
        /// </summary>
        /// <param name="e">Paitn event</param>
        protected override void OnPaint(PaintEventArgs e)
        {
            var attributes = new ImageAttributes();

            using (var g = Graphics.FromImage(MemoryBitmap))
            {
                if (Pushed)
                {
                    using (var pen = new Pen(Theme.ThemeBase))
                        GraphicsExtensions.DrawThemedGradientRectangle(g, pen, ClientRectangle, Dpi.ScaleSize(new Size(8, 8)));
                }
                else
                {
                    g.Clear(Parent.BackColor);
                }

                var textSize = g.MeasureString(Text, Font);
                var textArea = new RectangleF((ClientSize.Width - textSize.Width) / 2,
                                              (ClientSize.Height - textSize.Height),
                                              textSize.Width,
                                              textSize.Height);

                if (Image != null)
                {
                    var imageWidth  = Dpi.Scale(Image.Width);
                    var imageHeight = Dpi.Scale(Image.Height);
                    var imageArea   = new Rectangle((ClientSize.Width - imageWidth) / 2,
                                                    (ClientSize.Height - imageHeight) / 2,
                                                    imageWidth,
                                                    imageHeight);

                    var key = Image.GetPixel(0, 0);
                    attributes.SetColorKey(key, key);

                    g.DrawImage(Image,
                                StretchImage ? ClientRectangle : imageArea,
                                0, 0, Image.Width, Image.Height,
                                GraphicsUnit.Pixel,
                                attributes);
                }

                using (var brush = new SolidBrush(ForeColor))
                    g.DrawString(Text, Font, brush, textArea);

                if (Pushed)
                {
                    var key = MemoryBitmap.GetPixel(0, 0);
                    attributes.SetColorKey(key, key);
                }
                else
                {
                    attributes.ClearColorKey();
                }

                e.Graphics.DrawImage(MemoryBitmap,
                                     ClientRectangle,
                                     0, 0, MemoryBitmap.Width, MemoryBitmap.Height,
                                     GraphicsUnit.Pixel,
                                     attributes);
            }
        }