Exemplo n.º 1
0
        public void Dispose()
        {
            try
            {
                //Dispose bitmaps
                LeftWindowTop?.Dispose();
                LeftWindow?.Dispose();
                LeftWindowBottom?.Dispose();
                TopWindowRight?.Dispose();
                TopWindow?.Dispose();
                TopWindowLeft?.Dispose();
                RightWindowTop?.Dispose();
                RightWindow?.Dispose();
                RightWindowBottom?.Dispose();
                BottomWindowLeft?.Dispose();
                BottomWindow?.Dispose();
                BottomWindowRight?.Dispose();

                //Dispose brushes
                LeftBrush?.Dispose();
                TopBrush?.Dispose();
                RightBrush?.Dispose();
                BottomBrush?.Dispose();
            }
            catch (ObjectDisposedException) { }
        }
Exemplo n.º 2
0
        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }

            borderDotPen?.Dispose();
            borderPen?.Dispose();
            infoFont?.Dispose();
            magnifierBorderPen?.Dispose();
            magnifierBorderPen?.Dispose();
            magnifierCrosshairBrush?.Dispose();
            textBackgroundBrush?.Dispose();
            textFontBrush?.Dispose();

            image?.Dispose();
            backgroundBrush?.Dispose();
            backgroundHighlightBrush?.Dispose();

            base.Dispose(disposing);
        }
Exemplo n.º 3
0
        /// <summary>
        /// Returns a <see cref="Brush"/> to draw from a reference image specifying the orientation, quality, style and effect.
        /// </summary>
        /// <param name="image">An <see cref="Image"/> base object to create the drawing brush.</param>
        /// <param name="rect">A <see cref="RectangleF"/> structure that represents the rectangle in which to paint.</param>
        /// <param name="style">One of the values in the enumeration <see cref="ImageStyle"/> that represents image style.</param>
        /// <param name="effect">One of the values in the enumeration <see cref="EffectType"/> that represents the type of effect to be applied.</param>
        /// <param name="orientation">One of the values in the enumeration <see cref="Orientation"/> that represents the orientation of the brush.</param>
        /// <param name="quality">One of the values in the enumeration <see cref="SmoothingModeEx"/> that represents the quality of presentation</param>
        /// <returns>
        /// Returns a <see cref="Brush"/> object reference that represents the drawing brush.
        /// </returns>
        public static Brush ToBrush(this Image image, RectangleF rect, ImageStyle style, EffectType effect, Orientation orientation, SmoothingModeEx quality)
        {
            if (image == null)
            {
                return(new SolidBrush(Color.Empty));
            }

            Brush        brush;
            TextureBrush tempTextureBrush = null;

            Image texture = image.Rotate(orientation).ApplyEffect(effect);

            using (var bitmap = new Bitmap(texture.Width, texture.Height))
                using (var graphics = Graphics.FromImage(bitmap))
                    using (new Smoothing(graphics, quality))
                    {
                        Rectangle dstRect = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
                        Rectangle srcRect = new Rectangle(Point.Empty, texture.Size);
                        graphics.DrawImage(texture, dstRect, srcRect, GraphicsUnit.Pixel);

                        try
                        {
                            tempTextureBrush = new TextureBrush(bitmap)
                            {
                                WrapMode = style.ToWrapMode()
                            };

                            switch (style)
                            {
                            case ImageStyle.TopLeft:
                                tempTextureBrush.TranslateTransform(rect.Left, rect.Top);
                                break;

                            case ImageStyle.TopMiddle:
                                tempTextureBrush.TranslateTransform(rect.Left + (rect.Width - texture.Width) / 2, rect.Top);
                                break;

                            case ImageStyle.TopRight:
                                tempTextureBrush.TranslateTransform(rect.Right - texture.Width, rect.Top);
                                break;

                            case ImageStyle.CenterLeft:
                                tempTextureBrush.TranslateTransform(rect.Left, rect.Top + (rect.Height - texture.Height) / 2);
                                break;

                            case ImageStyle.CenterMiddle:
                                tempTextureBrush.TranslateTransform(rect.Left + (rect.Width - texture.Width) / 2, rect.Top + (rect.Height - texture.Height) / 2);
                                break;

                            case ImageStyle.CenterRight:
                                tempTextureBrush.TranslateTransform(rect.Right - texture.Width, rect.Top + (rect.Height - texture.Height) / 2);
                                break;

                            case ImageStyle.BottomLeft:
                                tempTextureBrush.TranslateTransform(rect.Left, rect.Bottom - texture.Height);
                                break;

                            case ImageStyle.BottomMiddle:
                                tempTextureBrush.TranslateTransform(rect.Left + (rect.Width - texture.Width) / 2, rect.Bottom - texture.Height);
                                break;

                            case ImageStyle.BottomRight:
                                tempTextureBrush.TranslateTransform(rect.Right - texture.Width, rect.Bottom - texture.Height);
                                break;

                            case ImageStyle.Stretch:
                                tempTextureBrush.TranslateTransform(rect.Left, rect.Top);
                                tempTextureBrush.ScaleTransform(rect.Width / texture.Width, rect.Height / texture.Height);
                                break;

                            case ImageStyle.Tile:
                            case ImageStyle.TileFlipX:
                            case ImageStyle.TileFlipY:
                            case ImageStyle.TileFlipXY:
                                tempTextureBrush.TranslateTransform(rect.Left, rect.Top);
                                break;
                            }

                            brush = (Brush)tempTextureBrush.Clone();
                        }
                        finally
                        {
                            tempTextureBrush?.Dispose();
                        }
                    }

            return(brush);
        }
Exemplo n.º 4
0
    public LayeredImage(Int32 width, Int32 height)
    {
        _width = width;
        _height = height;
        _layers = new Layers(this);

        // checker board brush

        _checkerboard = new Bitmap(32, 32, PixelFormat.Format24bppRgb);
        Color darkgray = Color.FromArgb(102,102,102);
        Color lightgray = Color.FromArgb(153,153,153);
        for (Int32 i = 0; i < 32; i++) {
            for (Int32 j = 0; j < 32; j++) {
                if ((i < 16 && j < 16) || (i >= 16 && j >= 16))
                    _checkerboard.SetPixel(j, i, lightgray);
                else
                    _checkerboard.SetPixel(j, i, darkgray);
            }
        }

        // background layer

        Layer bglayer = _layers.Add();
        Graphics g = Graphics.FromImage(bglayer._bitmap._bitmap);
        TextureBrush brush = new TextureBrush(_checkerboard);
        g.FillRectangle(brush, 0, 0, _width, _height);
        brush.Dispose();
        g.Dispose();
    }
Exemplo n.º 5
0
        // Create dirty text effect
        private void Form1_Paint(object sender, PaintEventArgs e)
        {
            e.Graphics.SmoothingMode     = SmoothingMode.AntiAlias;
            e.Graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;

            Bitmap canvas = Canvas.GenImage(ClientSize.Width, ClientSize.Height);
            // Load the dirty image from file
            Bitmap canvasDirty = new Bitmap("..\\..\\..\\CommonImages\\dirty-texture.png");

            // Text context to store string and font info to be sent as parameter to Canvas methods
            TextContext context = new TextContext();

            FontFamily fontFamily = new FontFamily("Arial Black");

            context.fontFamily = fontFamily;
            context.fontStyle  = FontStyle.Regular;
            context.nfontSize  = 48;

            context.pszText = "DIRTY";
            context.ptDraw  = new Point(5, 70);

            // Load the texture image from file
            Bitmap texture = new Bitmap("..\\..\\..\\CommonImages\\texture_blue.jpg");

            Bitmap texture2 = Canvas.GenImage(ClientSize.Width, ClientSize.Height);

            // Draw the texture against the red dirty mask onto the 2nd texture
            Canvas.ApplyImageToMask(texture, canvasDirty, texture2, MaskColor.Red, false);
            TextureBrush textureBrush = new TextureBrush(texture2);

            Bitmap textureShadow = Canvas.GenImage(ClientSize.Width, ClientSize.Height);

            // Draw the gray color against the red dirty mask onto the shadow texture
            Canvas.ApplyColorToMask(Color.FromArgb(0xaa, 0xcc, 0xcc, 0xcc), canvasDirty, textureShadow, MaskColor.Red);
            // Create texture brush for the shadow
            TextureBrush shadowBrush = new TextureBrush(textureShadow);

            // Create strategy for the shadow with the shadow brush
            var strategyShadow = Canvas.TextNoOutline(shadowBrush);

            Bitmap canvasTemp = Canvas.GenImage(ClientSize.Width, ClientSize.Height);

            // Draw the shadow image first onto the temp canvas
            Canvas.DrawTextImage(strategyShadow, canvasTemp, new Point(0, 0), context);

            // Create strategy for the text body
            var strategy = Canvas.TextNoOutline(textureBrush);

            // Draw text body
            Canvas.DrawTextImage(strategy, canvas, new Point(0, 0), context);

            // Draw the shadow image (canvasTemp) shifted -3, -3
            e.Graphics.DrawImage(canvasTemp, 3, 3, ClientSize.Width - 3, ClientSize.Height - 3);
            // Then draw the rendered image onto window
            e.Graphics.DrawImage(canvas, 0, 0, ClientSize.Width, ClientSize.Height);

            e.Graphics.Dispose();
            texture.Dispose();
            texture2.Dispose();
            textureShadow.Dispose();

            canvasDirty.Dispose();

            canvas.Dispose();
            canvasTemp.Dispose();

            strategyShadow.Dispose();
            strategy.Dispose();

            textureBrush.Dispose();
            shadowBrush.Dispose();
        }
Exemplo n.º 6
0
        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);

            Graphics g = e.Graphics;

            // Create tiled brushes for the shadow on the right and at the bottom.
            TextureBrush shadowRightBrush = new TextureBrush(shadowRight, WrapMode.Tile);
            TextureBrush shadowDownBrush  = new TextureBrush(shadowDown, WrapMode.Tile);

            // Translate (move) the brushes so the top or left of the image matches the top or left of the
            // area where it's drawed. If you don't understand why this is necessary, comment it out.
            // Hint: The tiling would start at 0,0 of the control, so the shadows will be offset a little.
            shadowDownBrush.TranslateTransform(0, Height - shadowSize);
            shadowRightBrush.TranslateTransform(Width - shadowSize, 0);

            // Define the rectangles that will be filled with the brush.
            // (where the shadow is drawn)
            Rectangle shadowDownRectangle = new Rectangle(
                shadowSize + shadowMargin,                      // X
                Height - shadowSize,                            // Y
                Width - (shadowSize * 2 + shadowMargin),        // width (stretches)
                shadowSize                                      // height
                );

            Rectangle shadowRightRectangle = new Rectangle(
                Width - shadowSize,                             // X
                shadowSize + shadowMargin,                      // Y
                shadowSize,                                     // width
                Height - (shadowSize * 2 + shadowMargin)        // height (stretches)
                );

            // And draw the shadow on the right and at the bottom.
            g.FillRectangle(shadowDownBrush, shadowDownRectangle);
            g.FillRectangle(shadowRightBrush, shadowRightRectangle);

            // Now for the corners, draw the 3 5x5 pixel images.
            g.DrawImage(shadowTopRight, new Rectangle(Width - shadowSize, shadowMargin, shadowSize, shadowSize));
            g.DrawImage(shadowDownRight, new Rectangle(Width - shadowSize, Height - shadowSize, shadowSize, shadowSize));
            g.DrawImage(shadowDownLeft, new Rectangle(shadowMargin, Height - shadowSize, shadowSize, shadowSize));

            // Fill the area inside with the color in the PanelColor property.
            // 1 pixel is added to everything to make the rectangle smaller.
            // This is because the 1 pixel border is actually drawn outside the rectangle.
            Rectangle fullRectangle = new Rectangle(
                1,                                             // X
                1,                                             // Y
                Width - (shadowSize + 2),                      // Width
                Height - (shadowSize + 2)                      // Height
                );

            if (PanelColor != null)
            {
                SolidBrush bgBrush = new SolidBrush(_panelColor);
                g.FillRectangle(bgBrush, fullRectangle);
            }

            // Draw a nice 1 pixel border it a BorderColor is specified
            if (_borderColor != null)
            {
                Pen borderPen = new Pen(BorderColor);
                g.DrawRectangle(borderPen, fullRectangle);
            }

            // Memory efficiency
            shadowDownBrush.Dispose();
            shadowRightBrush.Dispose();

            shadowDownBrush  = null;
            shadowRightBrush = null;
        }
        /// <summary>
        /// Create the image ready to be exported
        /// </summary>
        /// <param name="texturebitmap">The image the graphics will be drawn to</param>
        /// <param name="offset">The offset of the selection in map space</param>
        /// <param name="asbrightmap">True if the image should be a brightmap, false if normally textured</param>
        /// <returns>The image to be exported</returns>
        private void CreateImage(Bitmap texturebitmap, Vector2D offset, float scale, bool asbrightmap)
        {
            // The texture
            using (Graphics gtexture = Graphics.FromImage(texturebitmap))
            {
                gtexture.Clear(Color.Black);                 // If we don't clear to black we'll see seams where the sectors touch, due to the AA
                gtexture.InterpolationMode  = InterpolationMode.HighQualityBilinear;
                gtexture.CompositingQuality = CompositingQuality.HighQuality;
                gtexture.PixelOffsetMode    = PixelOffsetMode.HighQuality;
                gtexture.SmoothingMode      = SmoothingMode.AntiAlias;            // Without AA the sector edges will be quite rough

                using (GraphicsPath gpath = new GraphicsPath())
                {
                    foreach (Sector s in sectors)
                    {
                        float rotation = (float)s.Fields.GetValue("rotationfloor", 0.0);

                        // If a sector is rotated any offset is on the rotated axes. But we need to offset by
                        // map coordinates. We'll use this vector to compute that offset
                        Vector2D rotationvector = Vector2D.FromAngle(Angle2D.DegToRad(rotation) + Angle2D.PIHALF);

                        // Sectors are triangulated, so draw every triangle
                        for (int i = 0; i < s.Triangles.Vertices.Count / 3; i++)
                        {
                            // The GDI image has the 0/0 coordinate in the top left, so invert the y component
                            Vector2D v1 = (s.Triangles.Vertices[i * 3] - offset) * scale; v1.y *= -1.0;
                            Vector2D v2 = (s.Triangles.Vertices[i * 3 + 1] - offset) * scale; v2.y *= -1.0;
                            Vector2D v3 = (s.Triangles.Vertices[i * 3 + 2] - offset) * scale; v3.y *= -1.0;

                            gpath.AddLine((float)v1.x, (float)v1.y, (float)v2.x, (float)v2.y);
                            gpath.AddLine((float)v2.x, (float)v2.y, (float)v3.x, (float)v3.y);
                            gpath.CloseFigure();

                            doneitems++;

                            int newpercent = (int)(((double)doneitems / numitems) * 100);
                            if (newpercent > donepercent)
                            {
                                donepercent = newpercent;
                                addprogress();

                                if (checkcanelexport())
                                {
                                    throw new ImageExportCanceledException();
                                }
                            }
                        }

                        if (asbrightmap)
                        {
                            // Create the brightmap based on the sector brightness
                            int brightness = General.Clamp(s.Brightness, 0, 255);
                            using (SolidBrush sbrush = new SolidBrush(Color.FromArgb(255, brightness, brightness, brightness)))
                                gtexture.FillPath(sbrush, gpath);
                        }
                        else
                        {
                            Bitmap   brushtexture;
                            Vector2D textureoffset = new Vector2D();
                            Vector2D texturescale  = new Vector2D();

                            if (settings.Floor)
                            {
                                // The image might have a color correction applied, but we need it without. So we use LocalGetBitmap, because it reloads the image,
                                // but doesn't applie the color correction if we set UseColorCorrection to false first
                                ImageData imagedata = General.Map.Data.GetFlatImage(s.FloorTexture);
                                imagedata.UseColorCorrection = false;
                                brushtexture = new Bitmap(imagedata.LocalGetBitmap());
                                imagedata.UseColorCorrection = true;

                                textureoffset.x = s.Fields.GetValue("xpanningfloor", 0.0) * scale;
                                textureoffset.y = s.Fields.GetValue("ypanningfloor", 0.0) * scale;

                                // GZDoom uses bigger numbers for smaller scales (i.e. a scale of 2 will halve the size), so we need to change the scale
                                texturescale.x = 1.0 / s.Fields.GetValue("xscalefloor", 1.0);
                                texturescale.y = 1.0 / s.Fields.GetValue("yscalefloor", 1.0);
                            }
                            else
                            {
                                // The image might have a color correction applied, but we need it without. So we use LocalGetBitmap, because it reloads the image,
                                // but doesn't applie the color correction if we set UseColorCorrection to false first
                                ImageData imagedata = General.Map.Data.GetFlatImage(s.CeilTexture);
                                imagedata.UseColorCorrection = false;
                                brushtexture = new Bitmap(imagedata.LocalGetBitmap());
                                imagedata.UseColorCorrection = true;

                                textureoffset.x = s.Fields.GetValue("xpanningceiling", 0.0) * scale;
                                textureoffset.y = s.Fields.GetValue("ypanningceiling", 0.0) * scale;

                                // GZDoom uses bigger numbers for smaller scales (i.e. a scale of 2 will halve the size), so we need to change the scale
                                texturescale.x = 1.0 / s.Fields.GetValue("xscaleceiling", 1.0);
                                texturescale.y = 1.0 / s.Fields.GetValue("yscaleceiling", 1.0);
                            }

                            // Create the transformation matrix
                            Matrix matrix = new Matrix();
                            matrix.Rotate(rotation);
                            matrix.Translate((float)(-offset.x * scale * rotationvector.x), (float)(offset.x * scale * rotationvector.y)); // Left/right offset from the map origin
                            matrix.Translate((float)(offset.y * scale * rotationvector.y), (float)(offset.y * scale * rotationvector.x));  // Up/down offset from the map origin
                            matrix.Translate(-(float)textureoffset.x, -(float)textureoffset.y);                                            // Texture offset
                            matrix.Scale((float)texturescale.x, (float)texturescale.y);

                            if (!settings.Fullbright)
                            {
                                int brightness = General.Clamp(s.Brightness, 0, 255);
                                AdjustBrightness(ref brushtexture, brightness > 0 ? brightness / 255.0f : 0.0f);
                            }

                            if (scale > 1.0f)
                            {
                                ResizeImage(ref brushtexture, brushtexture.Width * (int)scale, brushtexture.Height * (int)scale);
                            }

                            // Create the texture brush and apply the matrix
                            TextureBrush tbrush = new TextureBrush(brushtexture);
                            tbrush.Transform = matrix;

                            // Draw the islands of the sector
                            gtexture.FillPath(tbrush, gpath);

                            // Dispose unneeded objects
                            brushtexture.Dispose();
                            tbrush.Dispose();
                            matrix.Dispose();
                        }

                        // Reset the graphics path
                        gpath.Reset();
                    }
                }
            }
        }
Exemplo n.º 8
0
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }

            if (darkBackgroundBrush != null)
            {
                darkBackgroundBrush.Dispose();
            }
            if (lightBackgroundBrush != null)
            {
                lightBackgroundBrush.Dispose();
            }
            if (borderPen != null)
            {
                borderPen.Dispose();
            }
            if (borderDotPen != null)
            {
                borderDotPen.Dispose();
            }
            if (borderDotPen2 != null)
            {
                borderDotPen2.Dispose();
            }
            if (nodeBackgroundBrush != null)
            {
                nodeBackgroundBrush.Dispose();
            }
            if (textFont != null)
            {
                textFont.Dispose();
            }

            if (regionFillPath != null)
            {
                if (LastRegionFillPath != null)
                {
                    LastRegionFillPath.Dispose();
                }
                LastRegionFillPath = regionFillPath;
                if (LastRegionDrawPath != null)
                {
                    LastRegionDrawPath.Dispose();
                }
                LastRegionDrawPath = regionDrawPath;
            }
            else
            {
                if (regionFillPath != null)
                {
                    regionFillPath.Dispose();
                }
                if (regionDrawPath != null)
                {
                    regionDrawPath.Dispose();
                }
            }

            base.Dispose(disposing);
        }
Exemplo n.º 9
0
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }

            if (darkBackgroundBrush != null)
            {
                darkBackgroundBrush.Dispose();
            }
            if (lightBackgroundBrush != null)
            {
                lightBackgroundBrush.Dispose();
            }
            if (borderPen != null)
            {
                borderPen.Dispose();
            }
            if (borderDotPen != null)
            {
                borderDotPen.Dispose();
            }
            if (nodeBackgroundBrush != null)
            {
                nodeBackgroundBrush.Dispose();
            }
            if (infoFont != null)
            {
                infoFont.Dispose();
            }
            if (infoFontMedium != null)
            {
                infoFontMedium.Dispose();
            }
            if (infoFontBig != null)
            {
                infoFontBig.Dispose();
            }
            if (textBackgroundBrush != null)
            {
                textBackgroundBrush.Dispose();
            }
            if (textBackgroundPenWhite != null)
            {
                textBackgroundPenWhite.Dispose();
            }
            if (textBackgroundPenBlack != null)
            {
                textBackgroundPenBlack.Dispose();
            }
            if (markerPen != null)
            {
                markerPen.Dispose();
            }

            if (regionFillPath != null)
            {
                if (LastRegionFillPath != null)
                {
                    LastRegionFillPath.Dispose();
                }
                LastRegionFillPath = regionFillPath;
            }
            else
            {
                if (regionFillPath != null)
                {
                    regionFillPath.Dispose();
                }
                if (regionDrawPath != null)
                {
                    regionDrawPath.Dispose();
                }
            }

            if (backgroundImage != null)
            {
                backgroundImage.Dispose();
            }

            base.Dispose(disposing);
        }
Exemplo n.º 10
0
        protected override void Dispose(bool disposing)
        {
            if (ShapeManager != null)
            {
                ShapeManager.Dispose();
            }

            if (bmpBackgroundImage != null)
            {
                bmpBackgroundImage.Dispose();
            }

            if (disposing && (components != null))
            {
                components.Dispose();
            }

            if (backgroundBrush != null)
            {
                backgroundBrush.Dispose();
            }
            if (backgroundHighlightBrush != null)
            {
                backgroundHighlightBrush.Dispose();
            }
            if (borderPen != null)
            {
                borderPen.Dispose();
            }
            if (borderDotPen != null)
            {
                borderDotPen.Dispose();
            }
            if (nodeBackgroundBrush != null)
            {
                nodeBackgroundBrush.Dispose();
            }
            if (infoFont != null)
            {
                infoFont.Dispose();
            }
            if (infoFontMedium != null)
            {
                infoFontMedium.Dispose();
            }
            if (infoFontBig != null)
            {
                infoFontBig.Dispose();
            }
            if (textBackgroundBrush != null)
            {
                textBackgroundBrush.Dispose();
            }
            if (textOuterBorderPen != null)
            {
                textOuterBorderPen.Dispose();
            }
            if (textInnerBorderPen != null)
            {
                textInnerBorderPen.Dispose();
            }
            if (markerPen != null)
            {
                markerPen.Dispose();
            }

            if (regionFillPath != null)
            {
                if (Result == RegionResult.Region)
                {
                    if (LastRegionFillPath != null)
                    {
                        LastRegionFillPath.Dispose();
                    }

                    LastRegionFillPath = regionFillPath;
                }
                else
                {
                    regionFillPath.Dispose();
                }
            }

            if (regionDrawPath != null)
            {
                regionDrawPath.Dispose();
            }
            if (Image != null)
            {
                Image.Dispose();
            }

            base.Dispose(disposing);
        }
Exemplo n.º 11
0
        /// <summary>
        /// Draws a graph of friends into a Bitmap
        /// </summary>
        /// <param name="graph">Friend connection graf</param>
        /// <param name="srcDir">Where to take user profile picture thumbnails from</param>
        /// <param name="settings">Settings - when left blank, default settings are used</param>
        /// <param name="worker">To report the progress</param>
        /// <returns>Bitmap with the graph</returns>
        private static Bitmap DrawGraph(FriendGraph graph, string imageDir, BackgroundWorker worker = null)
        {
            Bitmap   bmp = new Bitmap(GraphSettings.ImageWidth, GraphSettings.ImageHeight);
            Graphics g   = Graphics.FromImage(bmp);

            g.Clear(Color.White);
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;

            // if we have the autosize option on, we find the maximum number of friends
            int maxFriends = 0;

            // we draw lines connecting friends
            int           i    = 0;
            List <Friend> done = new List <Friend>();           // so we dont draw lines both ways

            foreach (KeyValuePair <Friend, List <Friend> > pair in graph)
            {
                if (worker != null && worker.CancellationPending)
                {
                    throw new InterruptedException();
                }

                Pen pen = new Pen(Color.FromArgb(64, 0, 0, 0), 1);

                foreach (Friend f in pair.Value)
                {
                    if (!done.Contains(f))
                    {
                        g.DrawLine(pen, pair.Key.coordinates, f.coordinates);
                    }
                }

                if (pair.Value.Count > maxFriends)
                {
                    maxFriends = pair.Value.Count;
                }

                pen.Dispose();

                done.Add(pair.Key);

                if (worker != null)
                {
                    worker.ReportProgress(Math.Min(99, ++i * 50 / graph.Count));
                }
            }

            int photoSize = GraphSettings.PhotoSize;

            // if we have the autosize option on, we would like bigger pictures be on top of smaller
            // we sort them by their friend count asc
            if (GraphSettings.AutoSize)
            {
                done.Sort((x, y) =>
                {
                    if (graph[x].Count < graph[y].Count)
                    {
                        return(-1);
                    }
                    else if (graph[y].Count < graph[x].Count)
                    {
                        return(1);
                    }

                    return(0);
                });
            }

            // we draw profile photos inside
            foreach (Friend f in done)
            {
                if (worker != null && worker.CancellationPending)
                {
                    throw new InterruptedException();
                }

                Image photo = Image.FromFile(imageDir + "/photos/" + f.id + ".jpg");

                if (GraphSettings.AutoSize)
                {
                    photoSize = (int)(15 + 35 * ((float)graph[f].Count / (float)maxFriends));
                }

                if (GraphSettings.PhotoShape == Shape.Circle)                  // we must crop circle out of the profile picture

                // we create brush
                {
                    TextureBrush brush = new TextureBrush(photo, WrapMode.Clamp);

                    // resize the brush
                    brush.ScaleTransform(((float)photoSize) / 50f,
                                         ((float)photoSize) / 50f,
                                         MatrixOrder.Append);

                    // we reset the brush starting position
                    brush.TranslateTransform(f.coordinates.X - photoSize / 2,
                                             f.coordinates.Y - photoSize / 2, MatrixOrder.Append);

                    // and fill a circle with it
                    g.FillEllipse(brush,
                                  f.coordinates.X - photoSize / 2,
                                  f.coordinates.Y - photoSize / 2,
                                  photoSize,
                                  photoSize);

                    brush.Dispose();
                }
                else                     // square - just draw the image
                {
                    g.DrawImage(photo,
                                f.coordinates.X - photoSize / 2,
                                f.coordinates.Y - photoSize / 2,
                                photoSize,
                                photoSize);
                }

                photo.Dispose();

                if (worker != null)
                {
                    worker.ReportProgress(Math.Min(99, ++i * 50 / graph.Count));
                }
            }

            g.Dispose();

            return(bmp);
        }
Exemplo n.º 12
0
        private void button2_Click(object sender, EventArgs e)
        {
            /*
             * Создает новый объект Graphics из указанного дескриптора окна.
             * public static Graphics FromHwnd(
             *      IntPtr hwnd
             * )
             */
            Graphics gr = Graphics.FromHwnd(this.Handle);

            gr.DrawLine(new Pen(Color.Green), 10, 50, 10, 200); // рисуем на форме

            Graphics gr1 = Graphics.FromHwnd(label1.Handle);

            gr1.DrawLine(new Pen(Color.Green, 5.0f), 20, 10, 90, 10); // рисуем на статике

            /*
             * Рисует прямоугольник, который определен парой координат, шириной и высотой.
             * public void DrawRectangle(
             *      Pen pen, // Структура Pen, определяющая цвет, ширину и стиль прямоугольника.
             *      int x, // Координата X верхнего левого угла прямоугольника для рисования.
             *      int y, // Координата Y верхнего левого угла прямоугольника для рисования.
             *      int width, // Ширина прямоугольника для рисования.
             *      int height // Высота прямоугольника для рисования.
             * )
             */
            using (Pen p = new Pen(Color.Red, 4f))
            {
                p.DashStyle = DashStyle.DashDotDot;
                gr.DrawRectangle(p, 160, 100, 100, 100); // отрисовываем контур прямоугольника штриховой линией
            }


            // Определяет кисть одного цвета. Кисти используются для заливки графических фигур,
            // таких как прямоугольники, эллипсы, круги, многоугольники и контуры.
            SolidBrush brush = new SolidBrush(Color.Blue);

            /*
             * Заполняет внутреннюю часть прямоугольника, который определен парой координат, шириной и высотой.
             * public void FillRectangle(
             * Brush brush, // Объект Brush, определяющий параметры заливки.
             * int x, // Координата X верхнего левого угла прямоугольника для заливки.
             * int y, // Координата Y верхнего левого угла прямоугольника для заливки.
             * int width, // Ширина прямоугольника для заливки.
             * int height // Высота прямоугольника для заливки.
             * )
             */
            gr.FillRectangle(brush, 300, 10, 100, 100); // заполняем прямоугольник синей кистью

            // Задает прямоугольную кисть со стилем штриховки, основным цветом и цветом фона.
            HatchBrush hatch_brush = new HatchBrush(HatchStyle.ZigZag, Color.Green, Color.Tomato);

            /*
             * Заполняет внутреннюю часть эллипса, определяемого ограничивающим прямоугольником, заданным с помощью пары координат, ширины и высоты.
             * public void FillEllipse(
             *      Brush brush, //  Объект Brush, определяющий параметры заливки.
             *      int x, // Координата X верхнего левого угла ограничивающего прямоугольника, который определяет эллипс.
             *      int y, // Координата Y верхнего левого угла ограничивающего прямоугольника, который определяет эллипс.
             *      int width, // Ширина ограничивающего прямоугольника, определяющего эллипс.
             *      int height // Высота ограничивающего прямоугольника, определяющего эллипс.
             * )
             */
            gr.FillEllipse(hatch_brush, 300, 120, 100, 100); // заполняем прямоугольник узорчатой кистью

            using (Pen p = new Pen(hatch_brush, 10))
            {
                gr.DrawEllipse(p, 450, 10, 100, 100); // отрисовываем контур круга
            }

            Image        img     = Image.FromFile("fon2.bmp");
            TextureBrush texture = new TextureBrush(img);

            gr.FillRectangle(texture, 450, 120, 100, 100); // заполняем прямоугольник текстурой

            LinearGradientBrush gradient = new LinearGradientBrush(new Point(12, 12),
                                                                   new Point(110, 110), Color.Red, Color.Black);

            gr.FillRectangle(gradient, 600, 10, 100, 100); // заполняем прямоугольник градиентной заливкой

            Point[] pts = new Point[6] {
                new Point(600, 150), new Point(640, 130), new Point(680, 140), new Point(700, 200), new Point(680, 230), new Point(620, 200)
            };

            // Инкапсулирует объект Brush, заполняющий градиентом внутреннюю область объекта GraphicsPath
            PathGradientBrush path = new PathGradientBrush(pts);

            /*
             * Заполняет внутреннюю часть многоугольника, определяемого массивом точек, заданных структурами Point.
             * public void FillPolygon(
             *         Brush brush, // Объект Brush, определяющий параметры заливки.
             *         Point[] points, // Массив структур Point, которые представляют вершины закрашиваемого многоугольника.
             * )
             */
            gr.FillPolygon(path, pts);

            // Освобождаем системные ресурсы
            brush.Dispose();
            path.Dispose();
            img.Dispose();
            texture.Dispose();
            gradient.Dispose();
            gr1.Dispose();
            gr.Dispose();
        }