TranslateTransform() public méthode

public TranslateTransform ( float dx, float dy ) : void
dx float
dy float
Résultat void
Exemple #1
0
        public override System.Drawing.Brush CreateGDIBrush(RectangleF rc, float dx, float dy)
        {
            RectangleF rct = new RectangleF(0, 0, _image.Width, _image.Height);

            System.Drawing.TextureBrush brush =
                new System.Drawing.TextureBrush(_image, _wrapMode, rct);

            brush.TranslateTransform(dx, dy);
            brush.ScaleTransform(24.0f / 80, 24.0f / 80, MatrixOrder.Append);
            return(brush);
        }
        public override void Draw(Paddle onPaddle, Graphics g)
        {
            Rectangle rct = new Rectangle(Point.Empty, onPaddle.Getrect().Size);
            using (TextureBrush tb = new TextureBrush(drawimage, WrapMode.Tile,rct))
            {

                //calculate length to translate.
                int translateamount = (int) (((float)drawimage.Width / 1000f) * DateTime.Now.Millisecond);
                tb.TranslateTransform(translateamount, 0);
                g.FillRectangle(tb, onPaddle.Getrect());
            }
        }
Exemple #3
0
        public static Bitmap dropShadow(Bitmap original)
        {
            Bitmap dest = new Bitmap(original.Width + shadowSize, original.Height + shadowSize);
            Graphics g = Graphics.FromImage(dest);

            TextureBrush shadowRightBrush = new TextureBrush(shadowRight, WrapMode.Tile);
            TextureBrush shadowDownBrush = new TextureBrush(shadowDown, WrapMode.Tile);

            shadowRightBrush.TranslateTransform(original.Width - shadowSize, 0);
            shadowDownBrush.TranslateTransform(0, original.Height - shadowSize);

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

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

            // And draw the shadow on the right and at the bottom.

            g.FillRectangle(shadowDownBrush, shadowDownRectangle);
            g.FillRectangle(shadowRightBrush, shadowRightRectangle);

            // 隅っこ三つ
            g.DrawImage(shadowTopRight, new Rectangle(original.Width, 0, shadowSize, shadowSize));
            g.DrawImage(shadowDownRight, new Rectangle(original.Width, original.Height, shadowSize, shadowSize));
            g.DrawImage(shadowDownLeft, new Rectangle(0, original.Height, shadowSize, shadowSize));

            g.DrawImage(original, new Rectangle(new Point(0, 0), new Size(original.Width, original.Height)));

            shadowDownBrush.Dispose();
            shadowRightBrush.Dispose();

            shadowDownBrush = null;
            shadowRightBrush = null;

            return dest;
        }
Exemple #4
0
		public static void DrawImageTiled(Graphics g, Image image, Rectangle destRect)
		{
			using (ImageAttributes attr = new ImageAttributes())
			{
				// initialize wrap mode to tile
				attr.SetWrapMode(System.Drawing.Drawing2D.WrapMode.Tile);

				// create the texture brush 
				using (TextureBrush b = new TextureBrush(image, new Rectangle(0, 0, image.Width, image.Height), attr))
				{
					// adjust the origin of the brush to coincide with the destination rect 
					b.TranslateTransform((float)destRect.Left, (float)destRect.Top);

					// fill the area using the texture 
					g.FillRectangle(b, destRect);
				}
			}
		}
Exemple #5
0
        private void DrawMagnifier(Graphics g)
        {
            Point mousePos = InputManager.MousePosition0Based;
            Rectangle currentScreenRect0Based = CaptureHelpers.ScreenToClient(Screen.FromPoint(InputManager.MousePosition).Bounds);
            int offsetX = 10, offsetY = 10, infoTextOffset = 0, infoTextPadding = 3;
            Rectangle infoTextRect = Rectangle.Empty;
            string infoText = string.Empty;

            if (Config.ShowInfo)
            {
                infoTextOffset = 10;

                CurrentPosition = InputManager.MousePosition;

                infoText = GetInfoText();
                Size textSize = g.MeasureString(infoText, infoFont).ToSize();
                infoTextRect.Size = new Size(textSize.Width + infoTextPadding * 2, textSize.Height + infoTextPadding * 2);
            }

            using (Bitmap magnifier = Magnifier(SurfaceImage, mousePos, Config.MagnifierPixelCount, Config.MagnifierPixelCount, Config.MagnifierPixelSize))
            {
                int x = mousePos.X + offsetX;

                if (x + magnifier.Width > currentScreenRect0Based.Right)
                {
                    x = mousePos.X - offsetX - magnifier.Width;
                }

                int y = mousePos.Y + offsetY;

                if (y + magnifier.Height + infoTextOffset + infoTextRect.Height > currentScreenRect0Based.Bottom)
                {
                    y = mousePos.Y - offsetY - magnifier.Height - infoTextOffset - infoTextRect.Height;
                }

                if (Config.ShowInfo)
                {
                    infoTextRect.Location = new Point(x + (magnifier.Width / 2) - (infoTextRect.Width / 2), y + magnifier.Height + infoTextOffset);
                    DrawInfoText(g, infoText, infoTextRect, 3);
                }

                g.SetHighQuality();

                using (TextureBrush brush = new TextureBrush(magnifier))
                {
                    brush.TranslateTransform(x, y);

                    if (Config.UseSquareMagnifier)
                    {
                        g.FillRectangle(brush, x, y, magnifier.Width, magnifier.Height);
                        g.DrawRectangleProper(Pens.White, x - 1, y - 1, magnifier.Width + 2, magnifier.Height + 2);
                        g.DrawRectangleProper(Pens.Black, x, y, magnifier.Width, magnifier.Height);
                    }
                    else
                    {
                        g.FillEllipse(brush, x, y, magnifier.Width, magnifier.Height);
                        g.DrawEllipse(Pens.White, x - 1, y - 1, magnifier.Width + 2, magnifier.Height + 2);
                        g.DrawEllipse(Pens.Black, x, y, magnifier.Width, magnifier.Height);
                    }
                }
            }
        }
Exemple #6
0
        public override void setPaint(java.awt.Paint paint)
        {
            if (paint is java.awt.Color)
            {
                setColor((java.awt.Color)paint);
                return;
            }

            if (paint == null || this.javaPaint == paint)
            {
                return;
            }
            this.javaPaint = paint;

            if (paint is java.awt.GradientPaint)
            {
                java.awt.GradientPaint gradient = (java.awt.GradientPaint)paint;
                LinearGradientBrush linear;
                if (gradient.isCyclic())
                {
                    linear = new LinearGradientBrush(
                        J2C.ConvertPoint(gradient.getPoint1()),
                        J2C.ConvertPoint(gradient.getPoint2()),
                        composite.GetColor(gradient.getColor1()),
                        composite.GetColor(gradient.getColor2()));
                }
                else
                {
                    //HACK because .NET does not support continue gradient like Java else Tile Gradient
                    //that we receize the rectangle very large (factor z) and set 4 color values
                    // a exact solution will calculate the size of the Graphics with the current transform
                    Color color1 = composite.GetColor(gradient.getColor1());
                    Color color2 = composite.GetColor(gradient.getColor2());
                    float x1 = (float)gradient.getPoint1().getX();
                    float x2 = (float)gradient.getPoint2().getX();
                    float y1 = (float)gradient.getPoint1().getY();
                    float y2 = (float)gradient.getPoint2().getY();
                    float diffX = x2 - x1;
                    float diffY = y2 - y1;
                    const float z = 60; //HACK zoom factor, with a larger factor .NET will make the gradient wider.
                    linear = new LinearGradientBrush(
                        new PointF(x1 - z * diffX, y1 - z * diffY),
                        new PointF(x2 + z * diffX, y2 + z * diffY),
                        color1,
                        color1);
                    ColorBlend colorBlend = new ColorBlend(4);
                    Color[] colors = colorBlend.Colors;
                    colors[0] = colors[1] = color1;
                    colors[2] = colors[3] = color2;
                    float[] positions = colorBlend.Positions;
                    positions[1] = z / (2 * z + 1);
                    positions[2] = (z + 1) / (2 * z + 1);
                    positions[3] = 1.0f;
                    linear.InterpolationColors = colorBlend;
                }
                linear.WrapMode = WrapMode.TileFlipXY;
                brush = linear;
                pen.Brush = brush;
                return;
            }

            if (paint is java.awt.TexturePaint)
            {
                java.awt.TexturePaint texture = (java.awt.TexturePaint)paint;
                Bitmap txtr = J2C.ConvertImage(texture.getImage());
                java.awt.geom.Rectangle2D anchor = texture.getAnchorRect();
                TextureBrush txtBrush;
                brush = txtBrush = new TextureBrush(txtr, new Rectangle(0, 0, txtr.Width, txtr.Height), composite.GetImageAttributes());
                txtBrush.TranslateTransform((float)anchor.getX(), (float)anchor.getY());
                txtBrush.ScaleTransform((float)anchor.getWidth() / txtr.Width, (float)anchor.getHeight() / txtr.Height);
                txtBrush.WrapMode = WrapMode.Tile;
                pen.Brush = brush;
                return;
            }

            if (paint is java.awt.LinearGradientPaint) {
                java.awt.LinearGradientPaint gradient = (java.awt.LinearGradientPaint)paint;
                PointF start = J2C.ConvertPoint(gradient.getStartPoint());
                PointF end = J2C.ConvertPoint(gradient.getEndPoint());

                java.awt.Color[] javaColors = gradient.getColors();
                ColorBlend colorBlend;
                Color[] colors;
                bool noCycle = gradient.getCycleMethod() == java.awt.MultipleGradientPaint.CycleMethod.NO_CYCLE;
                if (noCycle) {
                    //HACK because .NET does not support continue gradient like Java else Tile Gradient
                    //that we receize the rectangle very large (factor z) and set 2 additional color values
                    //an exact solution will calculate the size of the Graphics with the current transform
                    float diffX = end.X - start.X;
                    float diffY = end.Y - start.Y;
                    SizeF size = GetSize();
                    //HACK zoom factor, with a larger factor .NET will make the gradient wider.
                    float z = Math.Min(10, Math.Max(size.Width / diffX, size.Height / diffY));
                    start.X -= z * diffX;
                    start.Y -= z * diffY;
                    end.X += z * diffX;
                    end.Y += z * diffY;

                    colorBlend = new ColorBlend(javaColors.Length + 2);
                    colors = colorBlend.Colors;
                    float[] fractions = gradient.getFractions();
                    float[] positions = colorBlend.Positions;
                    for (int i = 0; i < javaColors.Length; i++) {
                        colors[i + 1] = composite.GetColor(javaColors[i]);
                        positions[i + 1] = (z + fractions[i]) / (2 * z + 1);
                    }
                    colors[0] = colors[1];
                    colors[colors.Length - 1] = colors[colors.Length - 2];
                    positions[positions.Length - 1] = 1.0f;
                } else {
                    colorBlend = new ColorBlend(javaColors.Length);
                    colors = colorBlend.Colors;
                    colorBlend.Positions = gradient.getFractions();
                    for (int i = 0; i < javaColors.Length; i++) {
                        colors[i] = composite.GetColor(javaColors[i]);
                    }
                }
                LinearGradientBrush linear = new LinearGradientBrush(start, end, colors[0], colors[colors.Length - 1]);
                linear.InterpolationColors = colorBlend;
                switch (gradient.getCycleMethod().ordinal()) {
                    case (int)java.awt.MultipleGradientPaint.CycleMethod.__Enum.NO_CYCLE:
                    case (int)java.awt.MultipleGradientPaint.CycleMethod.__Enum.REFLECT:
                        linear.WrapMode = WrapMode.TileFlipXY;
                        break;
                    case (int)java.awt.MultipleGradientPaint.CycleMethod.__Enum.REPEAT:
                        linear.WrapMode = WrapMode.Tile;
                        break;
                }
                brush = linear;
                pen.Brush = brush;
                return;
            }

            if (paint is java.awt.RadialGradientPaint )
            {
                java.awt.RadialGradientPaint gradient = (java.awt.RadialGradientPaint)paint;
                GraphicsPath path = new GraphicsPath();
                SizeF size = GetSize();

                PointF center = J2C.ConvertPoint(gradient.getCenterPoint());

                float radius = gradient.getRadius();
                int factor = (int)Math.Ceiling(Math.Max(size.Width, size.Height) / radius);

                float diameter = radius * factor;
                path.AddEllipse(center.X - diameter, center.Y - diameter, diameter * 2, diameter * 2);

                java.awt.Color[] javaColors = gradient.getColors();
                float[] fractions = gradient.getFractions();
                int length = javaColors.Length;
                ColorBlend colorBlend = new ColorBlend(length * factor);
                Color[] colors = colorBlend.Colors;
                float[] positions = colorBlend.Positions;

                for (int c = 0, j = length - 1; j >= 0; )
                {
                    positions[c] = (1 - fractions[j]) / factor;
                    colors[c++] = composite.GetColor(javaColors[j--]);
                }

                java.awt.MultipleGradientPaint.CycleMethod.__Enum cycle = (java.awt.MultipleGradientPaint.CycleMethod.__Enum)gradient.getCycleMethod().ordinal();
                for (int f = 1; f < factor; f++)
                {
                    int off = f * length;
                    for (int c = 0, j = length - 1; j >= 0; j--, c++)
                    {
                        switch (cycle)
                        {
                            case java.awt.MultipleGradientPaint.CycleMethod.__Enum.REFLECT:
                                if (f % 2 == 0)
                                {
                                    positions[off + c] = (f + 1 - fractions[j]) / factor;
                                    colors[off + c] = colors[c];
                                }
                                else
                                {
                                    positions[off + c] = (f + fractions[c]) / factor;
                                    colors[off + c] = colors[j];
                                }
                                break;
                            case java.awt.MultipleGradientPaint.CycleMethod.__Enum.NO_CYCLE:
                                positions[off + c] = (f + 1 - fractions[j]) / factor;
                                break;
                            default: //CycleMethod.REPEAT
                                positions[off + c] = (f + 1 - fractions[j]) / factor;
                                colors[off + c] = colors[c];
                                break;
                        }
                    }
                }
                if (cycle == java.awt.MultipleGradientPaint.CycleMethod.__Enum.NO_CYCLE && factor > 1)
                {
                    Array.Copy(colors, 0, colors, colors.Length - length, length);
                    Color color = colors[length - 1];
                    for (int i = colors.Length - length - 1; i >= 0; i--)
                    {
                        colors[i] = color;
                    }
                }

                PathGradientBrush pathBrush = new PathGradientBrush(path);
                pathBrush.CenterPoint = center;
                pathBrush.InterpolationColors = colorBlend;

                brush = pathBrush;
                pen.Brush = brush;
                return;
            }

            //generic paint to brush conversion for custom paints
            //the tranform of the graphics should not change between the creation and it usage
            using (Matrix transform = g.Transform)
            {
                SizeF size = GetSize();
                int width = (int)size.Width;
                int height = (int)size.Height;
                java.awt.Rectangle bounds = new java.awt.Rectangle(0, 0, width, height);

                java.awt.PaintContext context = paint.createContext(ColorModel.getRGBdefault(), bounds, bounds, C2J.ConvertMatrix(transform), getRenderingHints());
                WritableRaster raster = (WritableRaster)context.getRaster(0, 0, width, height);
                BufferedImage txtrImage = new BufferedImage(context.getColorModel(), raster, true, null);
                Bitmap txtr = J2C.ConvertImage(txtrImage);

                TextureBrush txtBrush;
                brush = txtBrush = new TextureBrush(txtr, new Rectangle(0, 0, width, height), composite.GetImageAttributes());
                transform.Invert();
                txtBrush.Transform = transform;
                txtBrush.WrapMode = WrapMode.Tile;
                pen.Brush = brush;
                return;
            }
        }
Exemple #7
0
        protected void RenderRowBackground(
            Graphics g, TextRowVisualStyle style, Rectangle r)
        {
            r.Width--;
            r.Height--;

            using (Brush br = style.Background.GetBrush(r))
                g.FillRectangle(br, r);

            if (_BackgroundImage != null)
            {
                Rectangle sr = r;
                sr.Location = Point.Empty;

                switch (_BackgroundImageLayout)
                {
                    case GridBackgroundImageLayout.TopRight:
                        OffsetRight(ref sr, ref r);
                        g.DrawImage(_BackgroundImage, r, sr, GraphicsUnit.Pixel);
                        break;

                    case GridBackgroundImageLayout.BottomLeft:
                        OffsetBottom(ref sr, ref r);
                        g.DrawImage(_BackgroundImage, r, sr, GraphicsUnit.Pixel);
                        break;

                    case GridBackgroundImageLayout.BottomRight:
                        OffsetRight(ref sr, ref r);
                        OffsetBottom(ref sr, ref r);
                        g.DrawImage(_BackgroundImage, r, sr, GraphicsUnit.Pixel);
                        break;

                    case GridBackgroundImageLayout.Center:
                        RenderImageCentered(g, _BackgroundImage, r);
                        break;

                    case GridBackgroundImageLayout.Stretch:
                        g.DrawImage(_BackgroundImage, r);
                        break;

                    case GridBackgroundImageLayout.Zoom:
                        RenderImageScaled(g, _BackgroundImage, r);
                        break;

                    case GridBackgroundImageLayout.Tile:
                        using (TextureBrush tbr = new TextureBrush(_BackgroundImage))
                        {
                            tbr.TranslateTransform(r.X, r.Y);
                            g.FillRectangle(tbr, r);
                        }
                        break;

                    default:
                        g.DrawImage(_BackgroundImage, r, sr, GraphicsUnit.Pixel);
                        break;
                }
            }
        }
        public ActionResult FileUploadHandler()
        {
            string[] fileNames = null;
            bool canpass = true;
            string filename = "";
            
            for (int i = 0; i < Request.Files.Count; i++)
            {
                if (canpass)
                {
                    fileNames = new string[Request.Files.Count];
                    canpass = false;
                }
                try
                {
                    IAmazonS3 client;
                    //string logo = "logo2.png";
                    //using (client = new AmazonS3Client(Amazon.RegionEndpoint.USEast1))
                    //{
                    //    GetObjectRequest request = new GetObjectRequest
                    //         {
                    //             BucketName = _bucketName,
                    //             Key = logo
                    //         };
                    //    using (GetObjectResponse response = client.GetObject(request))
                    //    {
                         //   string dest =System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), logo);
                            //if (!System.IO.File.Exists(logo))
                            //{
                            //    response.WriteResponseStreamToFile(dest);
                            //}
                            Image imgg = Image.FromFile(Server.MapPath(@"\Images\others\WaterMark.png"));
                            float f = float.Parse("0.5");
                            Image img = SetImageOpacity(imgg, f);

                            HttpPostedFileBase file = Request.Files[i];
                            using (Image image = Image.FromStream(file.InputStream, true, true))
                          //  using (Image watermarkImage = Image.FromFile(Server.MapPath(@"\Images\others\WaterMark.png")))
                            using (Image watermarkImage = img)
                            using (Graphics imageGraphics = Graphics.FromImage(image))
                            using (TextureBrush watermarkBrush = new TextureBrush(watermarkImage))
                            {
                               // int x = (image.Width / 2 - watermarkImage.Width / 2);
                                int x = 4;
                                int y = image.Height - watermarkImage.Height;
                                //int y = (image.Height / 2 - watermarkImage.Height / 2);
                                watermarkBrush.TranslateTransform(x, y);
                                imageGraphics.FillRectangle(watermarkBrush, new Rectangle(new Point(x, y), new Size(watermarkImage.Width + 1, watermarkImage.Height)));
                            //    image.Save(file.FileName);
                                
                              //  image.Save(@"C:\Users\Irfan\Desktop\logo12.png");

                                

                                //upload on aws
                                string extension = System.IO.Path.GetExtension(file.FileName);
                                filename = "temp" + DateTime.UtcNow.Ticks + extension;
                                image.Save(Server.MapPath(@"\Images\Ads\" + filename));
                                if (file.ContentLength > 0) // accept the file
                                {
                                    AmazonS3Config config = new AmazonS3Config();
                                    config.ServiceURL = "https://s3.amazonaws.com/";
                                    Amazon.S3.IAmazonS3 s3Client = AWSClientFactory.CreateAmazonS3Client(_awsAccessKey, _awsSecretKey, config);

                                    var request2 = new PutObjectRequest()
                                    {
                                        BucketName = _bucketName,
                                        CannedACL = S3CannedACL.PublicRead,//PERMISSION TO FILE PUBLIC ACCESIBLE
                                        Key = _folderName + filename,
                                        //InputStream = file.InputStream//SEND THE FILE STREAM
                                        FilePath = Server.MapPath(@"\Images\Ads\" + filename)
                                    };
                                    s3Client.PutObject(request2);
                                }
                                if (System.IO.File.Exists(Server.MapPath(@"\Images\Ads\" + filename)))
                                {
                                    System.IO.File.Delete(Server.MapPath(@"\Images\Ads\" + filename));
                                }
                            }
                      //  }
                        fileNames[i] = filename;
                    }
               // }
                catch (Exception ex)
                {
                    return Json(new { Message = "Error in saving file" });
                }

            }
            return Json(fileNames);
        }
        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);

            bool linkBroken = this.ReferenceBroken;

            Color bgColorBright = Color.White;
            if (this.dragHover) bgColorBright = bgColorBright.MixWith(Color.FromArgb(192, 255, 0), 0.4f);
            else if (this.multiple) bgColorBright = Color.Bisque;
            else if (linkBroken) bgColorBright = Color.FromArgb(255, 128, 128);

            bool darkBg = false;
            Rectangle rectImage = new Rectangle(this.rectPanel.X + 2, this.rectPanel.Y + 2, this.rectPanel.Width - 4, this.rectPanel.Height - 4);
            if (this.prevImage == null)
            {
                if (this.ReadOnly || !this.Enabled)
                    e.Graphics.FillRectangle(new SolidBrush(Color.FromArgb(64, bgColorBright)), rectImage);
                else
                    e.Graphics.FillRectangle(new SolidBrush(bgColorBright), rectImage);
            }
            else
            {
                Color brightChecker = this.prevImageLum > 0.5f ? Color.FromArgb(48, 48, 48) : Color.FromArgb(224, 224, 224);
                Color darkChecker = this.prevImageLum > 0.5f ? Color.FromArgb(32, 32, 32) : Color.FromArgb(192, 192, 192);

                if (this.dragHover)
                {
                    brightChecker = brightChecker.MixWith(Color.FromArgb(192, 255, 0), 0.4f);
                    darkChecker = darkChecker.MixWith(Color.FromArgb(192, 255, 0), 0.4f);
                }
                else if (this.multiple)
                {
                    brightChecker = brightChecker.MixWith(Color.FromArgb(255, 200, 128), 0.4f);
                    darkChecker = darkChecker.MixWith(Color.FromArgb(255, 200, 128), 0.4f);
                }
                else if (linkBroken)
                {
                    brightChecker = brightChecker.MixWith(Color.FromArgb(255, 128, 128), 0.4f);
                    darkChecker = darkChecker.MixWith(Color.FromArgb(255, 128, 128), 0.4f);
                }

                e.Graphics.FillRectangle(new HatchBrush(HatchStyle.LargeCheckerBoard, brightChecker, darkChecker), rectImage);

                TextureBrush bgImageBrush = new TextureBrush(this.prevImage);
                bgImageBrush.ResetTransform();
                bgImageBrush.TranslateTransform(rectImage.X, rectImage.Y);
                e.Graphics.FillRectangle(bgImageBrush, rectImage);

                darkBg = this.prevImageLum > 0.5f;
                if (this.ReadOnly || !this.Enabled)
                {
                    e.Graphics.FillRectangle(new SolidBrush(Color.FromArgb(128, SystemColors.Control)), rectImage);
                    darkBg = (this.prevImageLum + SystemColors.Control.GetLuminance()) * 0.5f < 0.5f;
                }
            }

            StringFormat format = StringFormat.GenericDefault;
            format.Alignment = StringAlignment.Center;
            format.LineAlignment = StringAlignment.Center;
            format.Trimming = StringTrimming.EllipsisPath;
            SizeF textSize = e.Graphics.MeasureString(
                this.ReferenceName ?? "null",
                SystemFonts.DefaultFont,
                new SizeF(this.rectPanel.Width, this.rectPanel.Height),
                format);

            Rectangle rectText;
            if (this.prevImage == null)
                rectText = this.rectPanel;
            else
                rectText = new Rectangle(
                    this.rectPanel.X, this.rectPanel.Bottom - (int)textSize.Height - 2, this.rectPanel.Width, (int)textSize.Height);

            if (this.prevImage != null)
            {
                e.Graphics.FillRectangle(new SolidBrush(Color.FromArgb(192, bgColorBright)),
                    rectText.X + rectText.Width / 2 - textSize.Width / 2 - 1,
                    rectText.Y + rectText.Height / 2 - textSize.Height / 2 - 2,
                    textSize.Width + 1,
                    textSize.Height + 2);
            }
            e.Graphics.DrawString(
                this.ReferenceName ?? "null",
                SystemFonts.DefaultFont,
                new SolidBrush(this.Enabled ? SystemColors.ControlText : SystemColors.GrayText),
                rectText,
                format);

            ControlRenderer.DrawBorder(e.Graphics,
                this.rectPanel,
                BorderStyle.ContentBox,
                (this.ReadOnly || !this.Enabled) ? BorderState.Disabled : BorderState.Normal);

            ButtonState buttonStateSet = ButtonState.Disabled;
            if(!this.ReadOnly && this.Enabled)
            {
                if (this.buttonSetPressed) buttonStateSet = ButtonState.Pressed;
                else if (this.buttonSetHovered) buttonStateSet = ButtonState.Hot;
                else buttonStateSet = ButtonState.Normal;
            }
            ControlRenderer.DrawButton(
                e.Graphics,
                this.rectButtonSet,
                buttonStateSet,
                null,
                iconSet);

            ButtonState buttonStateReset = ButtonState.Disabled;
            if (!this.ReadOnly && this.Enabled && this.ReferenceName != null)
            {
                if (this.buttonResetPressed)		buttonStateReset = ButtonState.Pressed;
                else if (this.buttonResetHovered)	buttonStateReset = ButtonState.Hot;
                else								buttonStateReset = ButtonState.Normal;
            }
            ControlRenderer.DrawButton(
                e.Graphics,
                this.rectButtonReset,
                buttonStateReset,
                null,
                iconReset);

            ButtonState buttonStateShow = ButtonState.Disabled;
            if (this.Enabled && this.ReferenceName != null)
            {
                if (this.buttonShowPressed)							buttonStateShow = ButtonState.Pressed;
                else if (this.buttonShowHovered || this.Focused)	buttonStateShow = ButtonState.Hot;
                else												buttonStateShow = ButtonState.Normal;
            }
            ControlRenderer.DrawButton(
                e.Graphics,
                this.rectButtonShow,
                buttonStateShow,
                null,
                iconShow);
        }
        private void DrawCursorGraphics(Graphics g)
        {
            Point mousePos = InputManager.MousePosition0Based;
            Rectangle currentScreenRect0Based = CaptureHelpers.GetActiveScreenBounds0Based();
            int cursorOffsetX = 10, cursorOffsetY = 10, itemGap = 10, itemCount = 0;
            Size totalSize = Size.Empty;

            int magnifierPosition = 0;
            Bitmap magnifier = null;

            if (Config.ShowMagnifier)
            {
                if (itemCount > 0) totalSize.Height += itemGap;
                magnifierPosition = totalSize.Height;

                magnifier = Magnifier(backgroundImage, mousePos, Config.MagnifierPixelCount, Config.MagnifierPixelCount, Config.MagnifierPixelSize);
                totalSize.Width = Math.Max(totalSize.Width, magnifier.Width);

                totalSize.Height += magnifier.Height;
                itemCount++;
            }

            int infoTextPadding = 3;
            int infoTextPosition = 0;
            Rectangle infoTextRect = Rectangle.Empty;
            string infoText = "";

            if (Config.ShowInfo)
            {
                if (itemCount > 0) totalSize.Height += itemGap;
                infoTextPosition = totalSize.Height;

                CurrentPosition = InputManager.MousePosition;
                infoText = GetInfoText();
                Size textSize = g.MeasureString(infoText, infoFont).ToSize();
                infoTextRect.Size = new Size(textSize.Width + infoTextPadding * 2, textSize.Height + infoTextPadding * 2);
                totalSize.Width = Math.Max(totalSize.Width, infoTextRect.Width);

                totalSize.Height += infoTextRect.Height;
                itemCount++;
            }

            int x = mousePos.X + cursorOffsetX;

            if (x + totalSize.Width > currentScreenRect0Based.Right)
            {
                x = mousePos.X - cursorOffsetX - totalSize.Width;
            }

            int y = mousePos.Y + cursorOffsetY;

            if (y + totalSize.Height > currentScreenRect0Based.Bottom)
            {
                y = mousePos.Y - cursorOffsetY - totalSize.Height;
            }

            if (Config.ShowMagnifier)
            {
                using (GraphicsQualityManager quality = new GraphicsQualityManager(g))
                using (TextureBrush brush = new TextureBrush(magnifier))
                {
                    brush.TranslateTransform(x, y + magnifierPosition);

                    if (Config.UseSquareMagnifier)
                    {
                        g.FillRectangle(brush, x, y + magnifierPosition, magnifier.Width, magnifier.Height);
                        g.DrawRectangleProper(Pens.White, x - 1, y + magnifierPosition - 1, magnifier.Width + 2, magnifier.Height + 2);
                        g.DrawRectangleProper(Pens.Black, x, y + magnifierPosition, magnifier.Width, magnifier.Height);
                    }
                    else
                    {
                        g.FillEllipse(brush, x, y + magnifierPosition, magnifier.Width, magnifier.Height);
                        g.DrawEllipse(Pens.White, x - 1, y + magnifierPosition - 1, magnifier.Width + 2, magnifier.Height + 2);
                        g.DrawEllipse(Pens.Black, x, y + magnifierPosition, magnifier.Width, magnifier.Height);
                    }
                }
            }

            if (Config.ShowInfo)
            {
                infoTextRect.Location = new Point(x + (totalSize.Width / 2) - (infoTextRect.Width / 2), y + infoTextPosition);
                DrawInfoText(g, infoText, infoTextRect, infoFont, infoTextPadding);
            }
        }
        private bool RebarMessageCaptured(ref Message m)
        {
            // Make sure the menu bar obeys the Explorer setting.
            // Was this really so hard, Microsoft?
            if(m.Msg == RB.SETBANDINFO) {
                REBARBANDINFO pInfo = (REBARBANDINFO)Marshal.PtrToStructure(m.LParam, typeof(REBARBANDINFO));
                if((PInvoke.GetClassName(pInfo.hwndChild) == "ToolbarWindow32") && (pInfo.wID == 1)) {
                    if(MenuHasFocus || MenuBarShown) {
                        pInfo.fStyle &= ~RBBS.HIDDEN;
                    }
                    else {
                        pInfo.fStyle |= RBBS.HIDDEN;
                    }
                    Marshal.StructureToPtr(pInfo, m.LParam, false);
                }
                return false;
            }

            if(m.Msg == WM.ERASEBKGND && (Config.Skin.UseRebarBGColor || Config.Skin.UseRebarImage)) {
                bool fFilled = false;
                using(Graphics graphics = Graphics.FromHdc(m.WParam)) {
                    RECT rect;
                    PInvoke.GetWindowRect(Handle, out rect);
                    Rectangle rectRebar = new Rectangle(0, 0, rect.Width, rect.Height);

                    // Fill the Rebar background color
                    if(Config.Skin.UseRebarBGColor) {
                        using(SolidBrush brush = new SolidBrush(Config.Skin.RebarColor)) {
                            graphics.FillRectangle(brush, rectRebar);
                            fFilled = true;
                        }
                    }
                    else if(Config.Skin.RebarStretchMode == StretchMode.Real) {
                        rebarController.DefWndProc(ref m);
                    }

                    // Draw the Rebar image
                    if(VisualStyleRenderer.IsSupported && Config.Skin.UseRebarImage && Config.Skin.RebarImageFile.Length > 0) {
                        if(bmpRebar == null) {
                            CreateRebarImage();
                        }
                        if(bmpRebar != null) {
                            List<Rectangle> rectTargets = new List<Rectangle>();
                            if(Config.Skin.RebarImageSeperateBars) {
                                int bandCount = (int)PInvoke.SendMessage(rebarController.Handle, RB.GETBANDCOUNT, IntPtr.Zero, IntPtr.Zero);
                                graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
                                RECT rectBand = new RECT();
                                RECT rectMargin = new RECT();
                                for(int i = 0; i < bandCount; i++) {
                                    if(PInvoke.SendMessage(rebarController.Handle, RB.GETRECT, (IntPtr)i, ref rectBand) == IntPtr.Zero) {
                                        continue;
                                    }
                                    PInvoke.SendMessage(rebarController.Handle, RB.GETBANDBORDERS, (IntPtr)i, ref rectMargin);
                                    rectBand.left -= !QTUtility.IsXP ? 4 : rectMargin.left;
                                    rectBand.top -= rectMargin.top;
                                    rectBand.right += rectMargin.right;
                                    rectBand.bottom += rectMargin.bottom;
                                    rectTargets.Add(rectBand.ToRectangle());
                                }
                            }
                            else {
                                rectTargets.Add(rectRebar);
                            }

                            foreach(Rectangle destRect in rectTargets) {
                                switch(Config.Skin.RebarStretchMode) {
                                    case StretchMode.Real:
                                        Rectangle rectDest2 = new Rectangle(new Point(0, 0), destRect.Size);
                                        Rectangle rectBmp = new Rectangle(new Point(0, 0), bmpRebar.Size);
                                        rectBmp.Intersect(rectDest2);
                                        rectDest2.Intersect(rectBmp);
                                        rectDest2.Offset(destRect.Location);
                                        graphics.DrawImage(bmpRebar, rectDest2, rectBmp, GraphicsUnit.Pixel);
                                        break;

                                    case StretchMode.Tile:
                                        textureBrushRebar = textureBrushRebar ?? new TextureBrush(bmpRebar);
                                        textureBrushRebar.TranslateTransform(destRect.X, destRect.Y);
                                        graphics.FillRectangle(textureBrushRebar, destRect);
                                        textureBrushRebar.ResetTransform();
                                        break;

                                    default: // Full
                                        // todo: make this a function
                                        graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
                                        Padding margin = Config.Skin.RebarSizeMargin;
                                        int left = margin.Left;
                                        int top = margin.Top;
                                        int right = margin.Right;
                                        int bottom = margin.Bottom;
                                        int vertical = margin.Vertical;
                                        int horizontal = margin.Horizontal;
                                        int width = bmpRebar.Width;
                                        int height = bmpRebar.Height;
                                        Rectangle[] dstRects = new Rectangle[] {
                                            new Rectangle(destRect.X, destRect.Y, left, top),
                                            new Rectangle(destRect.X + left, destRect.Y, destRect.Width - horizontal, top),
                                            new Rectangle(destRect.Right - right, destRect.Y, right, top),
                                            new Rectangle(destRect.X, destRect.Y + top, left, destRect.Height - vertical),
                                            new Rectangle(destRect.X + left, destRect.Y + top, destRect.Width - horizontal, destRect.Height - vertical),
                                            new Rectangle(destRect.Right - right, destRect.Y + top, right, destRect.Height - vertical),
                                            new Rectangle(destRect.X, destRect.Bottom - bottom, left, bottom),
                                            new Rectangle(destRect.X + left, destRect.Bottom - bottom, destRect.Width - horizontal, bottom),
                                            new Rectangle(destRect.Right - right, destRect.Bottom - bottom, right, bottom)
                                        };
                                        Rectangle[] srcRects = new Rectangle[] {
                                            new Rectangle(0, 0, left, top),
                                            new Rectangle(left, 0, width - horizontal, top),
                                            new Rectangle(width - right, 0, right, top),
                                            new Rectangle(0, top, left, height - vertical),
                                            new Rectangle(left, top, width - horizontal, height - vertical),
                                            new Rectangle(width - right, top, right, height - vertical),
                                            new Rectangle(0, height - bottom, left, bottom),
                                            new Rectangle(left, height - bottom, width - horizontal, bottom),
                                            new Rectangle(width - right, height - bottom, right, bottom),
                                        };
                                        for(int i = 0; i < 9; i++) {
                                            graphics.DrawImage(bmpRebar, dstRects[i], srcRects[i], GraphicsUnit.Pixel);
                                        }
                                        break;
                                }
                            }
                            fFilled = true;
                        }
                    }
                }
                if(fFilled) {
                    m.Result = (IntPtr)1;
                    return true;
                }
            }
            return false;
        }
Exemple #12
0
        private void DrawMagnifier(Graphics g)
        {
            Point mousePos = InputManager.MousePosition0Based;
            Rectangle currentScreenRect0Based = CaptureHelpers.ScreenToClient(Screen.FromPoint(InputManager.MousePosition).Bounds);
            int offsetX = RulerMode ? 20 : 10, offsetY = RulerMode ? 20 : 10;

            if (Config.ShowInfo && ((AreaManager.IsCurrentAreaValid && AreaManager.CurrentArea.Location == mousePos) || OneClickMode))
            {
                offsetY = RulerMode ? 85 : 50;
            }

            using (Bitmap magnifier = Magnifier(SurfaceImage, mousePos, Config.MagnifierPixelCount, Config.MagnifierPixelCount, Config.MagnifierPixelSize))
            {
                int x = mousePos.X + offsetX;

                if (x + magnifier.Width > currentScreenRect0Based.Right)
                {
                    x = mousePos.X - offsetX - magnifier.Width;
                }

                int y = mousePos.Y + offsetY;

                if (y + magnifier.Height > currentScreenRect0Based.Bottom)
                {
                    y = mousePos.Y - offsetY - magnifier.Height;
                }

                g.SetHighQuality();

                using (TextureBrush brush = new TextureBrush(magnifier))
                {
                    brush.TranslateTransform(x, y);
                    g.FillEllipse(brush, x, y, magnifier.Width, magnifier.Height);
                    g.DrawEllipse(Pens.Black, x, y, magnifier.Width, magnifier.Height);
                }
            }
        }
 public override RBrush GetTextureBrush(RImage image, RRect dstRect, RPoint translateTransformLocation)
 {
     var brush = new TextureBrush(((ImageAdapter)image).Image, Utils.Convert(dstRect));
     brush.TranslateTransform((float)translateTransformLocation.X, (float)translateTransformLocation.Y);
     return new BrushAdapter(brush, true);
 }
Exemple #14
0
		public static d.Brush ToGdiPlus(this ImageBrush brush, Rect bounds) {
			var img = brush.ImageSource;
			var bt = new BrushTransform(brush, bounds);
			if (bt.DegenerateBrush != null) return bt.DegenerateBrush;

			var viewbox = brush.Viewbox;
			if (brush.ViewboxUnits == BrushMappingMode.RelativeToBoundingBox)
				viewbox.Scale(img.Width, img.Height);
			var viewport = brush.Viewport;
			if (brush.ViewportUnits == BrushMappingMode.RelativeToBoundingBox)
				viewport.Transform(bt.ToAbsolute);

			var ia = new di.ImageAttributes();
			ia.SetColorMatrix(new di.ColorMatrix { Matrix33 = (float)brush.Opacity });
			var b = new d.TextureBrush(img.ToGdiPlus(), viewbox.ToGdiPlus(), ia);
			b.WrapMode = brush.TileMode.ToGdiPlus();

			b.TranslateTransform((float)viewport.X, (float)viewport.Y);
			b.ScaleTransform((float)(viewport.Width/viewbox.Width), (float)(viewport.Height/viewbox.Height));
			b.MultiplyTransform(bt.ToBrush.ToGdiPlus(), d2.MatrixOrder.Append);

			return b;
		}
Exemple #15
0
		public void TranslateTransform_InvalidOrder ()
		{
			TextureBrush t = new TextureBrush (image);
			t.TranslateTransform (1, 1, (MatrixOrder) Int32.MinValue);
		}
        /// <summary>
        /// Processes the given bitmap to apply the current instance of <see cref="IEdgeFilter"/>.
        /// </summary>
        /// <param name="source">The image to process.</param>
        /// <returns>A processed bitmap.</returns>
        public Bitmap ProcessFilter(Image source)
        {
            int width = source.Width;
            int height = source.Height;
            int maxWidth = width + 1;
            int maxHeight = height + 1;
            int bufferedWidth = width + 2;
            int bufferedHeight = height + 2;

            Bitmap destination = new Bitmap(width, height, PixelFormat.Format32bppPArgb);
            Bitmap input = new Bitmap(bufferedWidth, bufferedHeight, PixelFormat.Format32bppPArgb);
            destination.SetResolution(source.HorizontalResolution, source.VerticalResolution);
            input.SetResolution(source.HorizontalResolution, source.VerticalResolution);

            using (Graphics graphics = Graphics.FromImage(input))
            {
                // Fixes an issue with transparency not converting properly.
                graphics.Clear(Color.Transparent);

                Rectangle destinationRectangle = new Rectangle(0, 0, bufferedWidth, bufferedHeight);
                Rectangle rectangle = new Rectangle(0, 0, width, height);

                // If it's greyscale apply a colormatrix to the image.
                using (ImageAttributes attributes = new ImageAttributes())
                {
                    if (this.greyscale)
                    {
                        attributes.SetColorMatrix(ColorMatrixes.GreyScale);
                    }

                    // We use a trick here to detect right to the edges of the image.
                    // flip/tile the image with a pixel in excess in each direction to duplicate pixels.
                    // Later on we draw pixels without that excess.
                    using (TextureBrush tb = new TextureBrush(source, rectangle, attributes))
                    {
                        tb.WrapMode = WrapMode.TileFlipXY;
                        tb.TranslateTransform(1, 1);

                        graphics.FillRectangle(tb, destinationRectangle);
                    }
                }
            }

            try
            {
                double[,] horizontalFilter = this.edgeFilter.HorizontalGradientOperator;

                int kernelLength = horizontalFilter.GetLength(0);
                int radius = kernelLength >> 1;

                using (FastBitmap sourceBitmap = new FastBitmap(input))
                {
                    using (FastBitmap destinationBitmap = new FastBitmap(destination))
                    {
                        // Loop through the pixels.
                        Parallel.For(
                            0,
                            bufferedHeight,
                            y =>
                            {
                                for (int x = 0; x < bufferedWidth; x++)
                                {
                                    double rX = 0;
                                    double gX = 0;
                                    double bX = 0;

                                    // Apply each matrix multiplier to the color components for each pixel.
                                    for (int fy = 0; fy < kernelLength; fy++)
                                    {
                                        int fyr = fy - radius;
                                        int offsetY = y + fyr;

                                        // Skip the current row
                                        if (offsetY < 0)
                                        {
                                            continue;
                                        }

                                        // Outwith the current bounds so break.
                                        if (offsetY >= bufferedHeight)
                                        {
                                            break;
                                        }

                                        for (int fx = 0; fx < kernelLength; fx++)
                                        {
                                            int fxr = fx - radius;
                                            int offsetX = x + fxr;

                                            // Skip the column
                                            if (offsetX < 0)
                                            {
                                                continue;
                                            }

                                            if (offsetX < bufferedWidth)
                                            {
                                                // ReSharper disable once AccessToDisposedClosure
                                                Color currentColor = sourceBitmap.GetPixel(offsetX, offsetY);
                                                double r = currentColor.R;
                                                double g = currentColor.G;
                                                double b = currentColor.B;

                                                rX += horizontalFilter[fy, fx] * r;

                                                gX += horizontalFilter[fy, fx] * g;

                                                bX += horizontalFilter[fy, fx] * b;
                                            }
                                        }
                                    }

                                    // Apply the equation and sanitize.
                                    byte red = rX.ToByte();
                                    byte green = gX.ToByte();
                                    byte blue = bX.ToByte();

                                    Color newColor = Color.FromArgb(red, green, blue);
                                    if (y > 0 && x > 0 && y < maxHeight && x < maxWidth)
                                    {
                                        // ReSharper disable once AccessToDisposedClosure
                                        destinationBitmap.SetPixel(x - 1, y - 1, newColor);
                                    }
                                }
                            });
                    }
                }
            }
            finally
            {
                // We created a new image. Cleanup.
                input.Dispose();
            }

            return destination;
        }
        /// <summary>
        /// Applies the halftone filter. 
        /// </summary>
        /// <param name="source">
        /// The <see cref="Bitmap"/> to apply the filter to.
        /// </param>
        /// <returns>
        /// The <see cref="Bitmap"/> with the filter applied.
        /// </returns>
        public Bitmap ApplyFilter(Bitmap source)
        {
            // TODO: Make this class implement an interface?
            Bitmap padded = null;
            Bitmap cyan = null;
            Bitmap magenta = null;
            Bitmap yellow = null;
            Bitmap keyline = null;
            Bitmap newImage = null;

            try
            {
                int sourceWidth = source.Width;
                int sourceHeight = source.Height;
                int width = source.Width + this.distance;
                int height = source.Height + this.distance;

                // Draw a slightly larger image, flipping the top/left pixels to prevent
                // jagged edge of output.
                padded = new Bitmap(width, height, PixelFormat.Format32bppPArgb);
                padded.SetResolution(source.HorizontalResolution, source.VerticalResolution);
                using (Graphics graphicsPadded = Graphics.FromImage(padded))
                {
                    graphicsPadded.Clear(Color.White);
                    Rectangle destinationRectangle = new Rectangle(0, 0, sourceWidth + this.distance, source.Height + this.distance);
                    using (TextureBrush tb = new TextureBrush(source))
                    {
                        tb.WrapMode = WrapMode.TileFlipXY;
                        tb.TranslateTransform(this.distance, this.distance);
                        graphicsPadded.FillRectangle(tb, destinationRectangle);
                    }
                }

                // Calculate min and max widths/heights.
                Rectangle rotatedBounds = this.GetBoundingRectangle(width, height);
                int minY = -(rotatedBounds.Height + height);
                int maxY = rotatedBounds.Height + height;
                int minX = -(rotatedBounds.Width + width);
                int maxX = rotatedBounds.Width + width;
                Point center = Point.Empty;

                // Yellow oversaturates the output.
                int offset = this.distance;
                float yellowMultiplier = this.distance * 1.587f;
                float magentaMultiplier = this.distance * 2.176f;
                float multiplier = this.distance * 2.2f;
                float max = this.distance * (float)Math.Sqrt(2);
                float magentaMax = this.distance * (float)Math.Sqrt(1.4545);

                // Bump up the keyline max so that black looks black.
                float keylineMax = max * (float)Math.Sqrt(2);

                // Color sampled process colours from Wikipedia pages.
                // Keyline brush is declared separately.
                Brush cyanBrush = new SolidBrush(Color.FromArgb(0, 183, 235));
                Brush magentaBrush = new SolidBrush(Color.FromArgb(255, 0, 144));
                Brush yellowBrush = new SolidBrush(Color.FromArgb(255, 239, 0));

                // Create our images.
                cyan = new Bitmap(width, height, PixelFormat.Format32bppPArgb);
                magenta = new Bitmap(width, height, PixelFormat.Format32bppPArgb);
                yellow = new Bitmap(width, height, PixelFormat.Format32bppPArgb);
                keyline = new Bitmap(width, height, PixelFormat.Format32bppPArgb);
                newImage = new Bitmap(sourceWidth, sourceHeight, PixelFormat.Format32bppPArgb);

                // Ensure the correct resolution is set.
                cyan.SetResolution(source.HorizontalResolution, source.VerticalResolution);
                magenta.SetResolution(source.HorizontalResolution, source.VerticalResolution);
                yellow.SetResolution(source.HorizontalResolution, source.VerticalResolution);
                keyline.SetResolution(source.HorizontalResolution, source.VerticalResolution);
                newImage.SetResolution(source.HorizontalResolution, source.VerticalResolution);

                // Check bounds against this.
                Rectangle rectangle = new Rectangle(0, 0, width, height);

                using (Graphics graphicsCyan = Graphics.FromImage(cyan))
                using (Graphics graphicsMagenta = Graphics.FromImage(magenta))
                using (Graphics graphicsYellow = Graphics.FromImage(yellow))
                using (Graphics graphicsKeyline = Graphics.FromImage(keyline))
                {
                    // Set the quality properties.
                    graphicsCyan.PixelOffsetMode = PixelOffsetMode.Half;
                    graphicsMagenta.PixelOffsetMode = PixelOffsetMode.Half;
                    graphicsYellow.PixelOffsetMode = PixelOffsetMode.Half;
                    graphicsKeyline.PixelOffsetMode = PixelOffsetMode.Half;

                    graphicsCyan.SmoothingMode = SmoothingMode.AntiAlias;
                    graphicsMagenta.SmoothingMode = SmoothingMode.AntiAlias;
                    graphicsYellow.SmoothingMode = SmoothingMode.AntiAlias;
                    graphicsKeyline.SmoothingMode = SmoothingMode.AntiAlias;

                    graphicsCyan.CompositingQuality = CompositingQuality.HighQuality;
                    graphicsMagenta.CompositingQuality = CompositingQuality.HighQuality;
                    graphicsYellow.CompositingQuality = CompositingQuality.HighQuality;
                    graphicsKeyline.CompositingQuality = CompositingQuality.HighQuality;

                    // Set up the canvas.
                    graphicsCyan.Clear(Color.White);
                    graphicsMagenta.Clear(Color.White);
                    graphicsYellow.Clear(Color.White);
                    graphicsKeyline.Clear(Color.White);

                    // This is too slow. The graphics object can't be called within a parallel
                    // loop so we have to do it old school. :(
                    using (FastBitmap sourceBitmap = new FastBitmap(padded))
                    {
                        for (int y = minY; y < maxY; y += offset)
                        {
                            for (int x = minX; x < maxX; x += offset)
                            {
                                Color color;
                                CmykColor cmykColor;
                                float brushWidth;

                                // Cyan
                                Point rotatedPoint = ImageMaths.RotatePoint(new Point(x, y), this.cyanAngle, center);
                                int angledX = rotatedPoint.X;
                                int angledY = rotatedPoint.Y;
                                if (rectangle.Contains(new Point(angledX, angledY)))
                                {
                                    color = sourceBitmap.GetPixel(angledX, angledY);
                                    cmykColor = color;
                                    brushWidth = Math.Min((cmykColor.C / 100f) * multiplier, max);
                                    graphicsCyan.FillEllipse(cyanBrush, angledX, angledY, brushWidth, brushWidth);
                                }

                                // Magenta
                                rotatedPoint = ImageMaths.RotatePoint(new Point(x, y), this.magentaAngle, center);
                                angledX = rotatedPoint.X;
                                angledY = rotatedPoint.Y;
                                if (rectangle.Contains(new Point(angledX, angledY)))
                                {
                                    color = sourceBitmap.GetPixel(angledX, angledY);
                                    cmykColor = color;
                                    brushWidth = Math.Min((cmykColor.M / 100f) * magentaMultiplier, magentaMax);
                                    graphicsMagenta.FillEllipse(magentaBrush, angledX, angledY, brushWidth, brushWidth);
                                }

                                // Yellow
                                rotatedPoint = ImageMaths.RotatePoint(new Point(x, y), this.yellowAngle, center);
                                angledX = rotatedPoint.X;
                                angledY = rotatedPoint.Y;
                                if (rectangle.Contains(new Point(angledX, angledY)))
                                {
                                    color = sourceBitmap.GetPixel(angledX, angledY);
                                    cmykColor = color;
                                    brushWidth = Math.Min((cmykColor.Y / 100f) * yellowMultiplier, max);
                                    graphicsYellow.FillEllipse(yellowBrush, angledX, angledY, brushWidth, brushWidth);
                                }

                                // Keyline
                                rotatedPoint = ImageMaths.RotatePoint(new Point(x, y), this.keylineAngle, center);
                                angledX = rotatedPoint.X;
                                angledY = rotatedPoint.Y;
                                if (rectangle.Contains(new Point(angledX, angledY)))
                                {
                                    color = sourceBitmap.GetPixel(angledX, angledY);
                                    cmykColor = color;
                                    brushWidth = Math.Min((cmykColor.K / 100f) * multiplier, keylineMax);

                                    // Just using black is too dark.
                                    Brush keylineBrush = new SolidBrush(CmykColor.FromCmykColor(0, 0, 0, cmykColor.K));
                                    graphicsKeyline.FillEllipse(keylineBrush, angledX, angledY, brushWidth, brushWidth);
                                }
                            }
                        }
                    }

                    // Set our white background.
                    using (Graphics graphics = Graphics.FromImage(newImage))
                    {
                        graphics.Clear(Color.White);
                    }

                    // Blend the colors now to mimic adaptive blending.
                    using (FastBitmap cyanBitmap = new FastBitmap(cyan))
                    using (FastBitmap magentaBitmap = new FastBitmap(magenta))
                    using (FastBitmap yellowBitmap = new FastBitmap(yellow))
                    using (FastBitmap keylineBitmap = new FastBitmap(keyline))
                    using (FastBitmap destinationBitmap = new FastBitmap(newImage))
                    {
                        Parallel.For(
                            offset,
                            height,
                            y =>
                            {
                                for (int x = offset; x < width; x++)
                                {
                                    // ReSharper disable AccessToDisposedClosure
                                    Color cyanPixel = cyanBitmap.GetPixel(x, y);
                                    Color magentaPixel = magentaBitmap.GetPixel(x, y);
                                    Color yellowPixel = yellowBitmap.GetPixel(x, y);
                                    Color keylinePixel = keylineBitmap.GetPixel(x, y);

                                    // Negate the offset.
                                    int xBack = x - offset;
                                    int yBack = y - offset;

                                    CmykColor blended = cyanPixel.AddAsCmykColor(magentaPixel, yellowPixel, keylinePixel);
                                    if (rectangle.Contains(new Point(xBack, yBack)))
                                    {
                                        destinationBitmap.SetPixel(xBack, yBack, blended);
                                    }
                                    // ReSharper restore AccessToDisposedClosure
                                }
                            });
                    }
                }

                padded.Dispose();
                cyan.Dispose();
                magenta.Dispose();
                yellow.Dispose();
                keyline.Dispose();
                source.Dispose();
                source = newImage;
            }
            catch
            {
                if (padded != null)
                {
                    padded.Dispose();
                }

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

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

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

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

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

            return source;
        }
Exemple #18
0
        private static Brush CreateImageBrush(Rectangle rect,
                                              Image image,
                                              PaletteImageStyle imageStyle)
        {
            // Create brush based on the provided image
            TextureBrush brush = new TextureBrush(image);

            // Create appropriate wrapping mode from image style
            switch (imageStyle)
            {
                case PaletteImageStyle.TopLeft:
                    brush.WrapMode = WrapMode.Clamp;
                    brush.TranslateTransform(rect.Left, rect.Top);
                    break;
                case PaletteImageStyle.TopMiddle:
                    brush.WrapMode = WrapMode.Clamp;
                    brush.TranslateTransform(rect.Left + (rect.Width - image.Width) / 2, rect.Top);
                    break;
                case PaletteImageStyle.TopRight:
                    brush.WrapMode = WrapMode.Clamp;
                    brush.TranslateTransform(rect.Right - image.Width, rect.Top);
                    break;
                case PaletteImageStyle.CenterLeft:
                    brush.WrapMode = WrapMode.Clamp;
                    brush.TranslateTransform(rect.Left, rect.Top + (rect.Height - image.Height) / 2);
                    break;
                case PaletteImageStyle.CenterMiddle:
                    brush.WrapMode = WrapMode.Clamp;
                    brush.TranslateTransform(rect.Left + (rect.Width - image.Width) / 2, rect.Top + (rect.Height - image.Height) / 2);
                    break;
                case PaletteImageStyle.CenterRight:
                    brush.WrapMode = WrapMode.Clamp;
                    brush.TranslateTransform(rect.Right - image.Width, rect.Top + (rect.Height - image.Height) / 2);
                    break;
                case PaletteImageStyle.BottomLeft:
                    brush.WrapMode = WrapMode.Clamp;
                    brush.TranslateTransform(rect.Left, rect.Bottom - image.Height);
                    break;
                case PaletteImageStyle.BottomMiddle:
                    brush.WrapMode = WrapMode.Clamp;
                    brush.TranslateTransform(rect.Left + (rect.Width - image.Width) / 2, rect.Bottom - image.Height);
                    break;
                case PaletteImageStyle.BottomRight:
                    brush.WrapMode = WrapMode.Clamp;
                    brush.TranslateTransform(rect.Right - image.Width, rect.Bottom - image.Height);
                    break;
                case PaletteImageStyle.Stretch:
                    brush.WrapMode = WrapMode.Clamp;
                    brush.TranslateTransform(rect.Left, rect.Top);
                    brush.ScaleTransform((float)rect.Width / (float)image.Width, (float)rect.Height / (float)image.Height);
                    break;
                case PaletteImageStyle.Tile:
                    brush.WrapMode = WrapMode.Tile;
                    brush.TranslateTransform(rect.Left, rect.Top);
                    break;
                case PaletteImageStyle.TileFlipX:
                    brush.WrapMode = WrapMode.TileFlipX;
                    brush.TranslateTransform(rect.Left, rect.Top);
                    break;
                case PaletteImageStyle.TileFlipY:
                    brush.WrapMode = WrapMode.TileFlipY;
                    brush.TranslateTransform(rect.Left, rect.Top);
                    break;
                case PaletteImageStyle.TileFlipXY:
                    brush.WrapMode = WrapMode.TileFlipXY;
                    brush.TranslateTransform(rect.Left, rect.Top);
                    break;
                default:
                    // Should never happen!
                    Debug.Assert(false);
                    throw new ArgumentOutOfRangeException("imageStyle");
            }

            return brush;
        }
Exemple #19
0
        private void DrawMagnifier(Graphics g)
        {
            Point mousePos = InputManager.MousePosition0Based;
            int offsetX = 10, offsetY = 10;

            if (Config.ShowInfo && AreaManager.IsCurrentAreaValid && AreaManager.CurrentArea.Location == mousePos)
            {
                offsetY = 50;
            }

            using (Bitmap magnifier = Magnifier(SurfaceImage, mousePos, Config.MagnifierPixelCount, Config.MagnifierPixelCount, Config.MagnifierPixelSize))
            {
                int x = mousePos.X + offsetX;

                if (x + magnifier.Width > ScreenRectangle0Based.Width)
                {
                    x = mousePos.X - offsetX - magnifier.Width;
                }

                int y = mousePos.Y + offsetY;

                if (y + magnifier.Height > ScreenRectangle0Based.Height)
                {
                    y = mousePos.Y - offsetY - magnifier.Height;
                }

                g.SetHighQuality();

                using (TextureBrush brush = new TextureBrush(magnifier))
                {
                    brush.TranslateTransform(x, y);
                    g.FillEllipse(brush, x, y, magnifier.Width, magnifier.Height);
                    g.DrawEllipse(Pens.Black, x, y, magnifier.Width, magnifier.Height);
                }
            }
        }
 static void FillRectangleTiled(Graphics g, TextureBrush brush, int x, int y, int w, int h)
 {
     brush.TranslateTransform(x, y);
     g.FillRectangle(brush, x, y, w, h);
 }
        public static void DrawShadow(Graphics g,Rectangle r)
        {

            r.Offset(shadowSize,shadowSize);
            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, r.Height - shadowSize);
            //shadowRightBrush.TranslateTransform(r.Width - shadowSize, 0);
            shadowDownBrush.TranslateTransform(0,r.Height + r.Y - shadowSize);
            shadowRightBrush.TranslateTransform(r.Width + r.X - shadowSize, 0);

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


            Rectangle shadowRightRectangle = new Rectangle(
                r.Width - shadowSize + r.X,                             // X
                shadowSize + shadowMargin + r.Y,                      // Y
                shadowSize,                                     // width
                r.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(r.Width - shadowSize+r.X, shadowMargin+r.Y, shadowSize, shadowSize));
            g.DrawImage(shadowDownRight, new Rectangle(r.Width - shadowSize+r.X, r.Height - shadowSize+r.Y, shadowSize, shadowSize));
            g.DrawImage(shadowDownLeft, new Rectangle(shadowMargin+r.X, r.Height - shadowSize+r.Y, shadowSize, shadowSize));

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

            shadowDownBrush = null;
            shadowRightBrush = null;

        }
Exemple #22
0
        private static void DrawShadow(Graphics context, Rectangle originalRect)
        {
            const int shadowSize = 5;
            const int shadowMargin = 2;

            // Create tiled brushes for the shadow on the right and at the bottom.
            var shadowRightBrush = new TextureBrush(shadowRight, WrapMode.Tile);
            var 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 drawn. 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, originalRect.Height - shadowSize);
            // shadowRightBrush.TranslateTransform(originalRect.Width - shadowSize, 0);
            shadowDownBrush.TranslateTransform(0, originalRect.Bottom);
            shadowRightBrush.TranslateTransform(originalRect.Right, 0);

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

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

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

            // Now for the corners, draw the 3 5X5 pixel images.
            context.DrawImage( shadowTopRight,  new Rectangle(  originalRect.Right, originalRect.Y + shadowMargin,  shadowSize, shadowSize  ));
            context.DrawImage( shadowDownRight, new Rectangle(  originalRect.Right, originalRect.Bottom,            shadowSize, shadowSize  ));
            context.DrawImage( shadowDownLeft,  new Rectangle(  originalRect.X + shadowMargin, originalRect.Bottom, shadowSize, shadowSize  ));
        }
 public void AddWaterMark(string watermark)
 {
     using (var image = convertFromByte(localBytes))
     using (var watermarkImage = Image.FromFile(watermark))
     using (var imageGraphics = Graphics.FromImage(image))
     using (var watermarkBrush = new TextureBrush(watermarkImage))
     {
         int x = (image.Width - watermarkImage.Width - 10);
         int y = (image.Height - watermarkImage.Height -10);
         watermarkBrush.TranslateTransform(x, y);
         imageGraphics.FillRectangle(watermarkBrush, new Rectangle(new Point(x, y), new Size(watermarkImage.Width + 1, watermarkImage.Height)));
         //image.Save(@"C:\Users\Public\Pictures\Sample Pictures\Desert_watermark.jpg");
         var ms = new MemoryStream();
         image.Save(ms, getImageFormat(Mime));
         localBytes = ms.ToArray();
     }
 }
Exemple #24
0
        private void DrawBorder(Graphics graphics, Bitmap image, Rectangle rectangle)
        {
            if (image == null)
                return;

            using (var brush = new TextureBrush(image))
            {
                brush.TranslateTransform(rectangle.Left, rectangle.Top);
                graphics.FillRectangle(brush, rectangle);
            }
        }
Exemple #25
0
		public override System.Drawing.Brush CreateGDIBrush(RectangleF rc, float dx, float dy)
		{
			RectangleF rct = new RectangleF(0, 0, _image.Width, _image.Height);
			System.Drawing.TextureBrush brush =
				new System.Drawing.TextureBrush(_image, _wrapMode, rct);

			brush.TranslateTransform(dx, dy);
			brush.ScaleTransform(24.0f/80, 24.0f/80, MatrixOrder.Append);
			return brush;
		}
        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);

            // Get the graphics object. We need something to draw with

            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 5�5 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;
        }
Exemple #27
0
        public override void draw(Graphics gfx)
        {
            // Determine the basic image to use
            Image basicimage;
            if (shield > 0)
            {
                switch (number) {
                default: basicimage = Resources.Robot.Basic1Shield; break;
                case 1:  basicimage = Resources.Robot.Basic2Shield; break;
                case 2:  basicimage = Resources.Robot.Basic3Shield; break;
                case 3:  basicimage = Resources.Robot.Basic4Shield; break;
                case 4:  basicimage = Resources.Robot.Basic5Shield; break;
                case 5:  basicimage = Resources.Robot.Basic6Shield; break;
                }
            }
            else
            {
                switch (number) {
                default: basicimage = Resources.Robot.Basic1; break;
                case 1:  basicimage = Resources.Robot.Basic2; break;
                case 2:  basicimage = Resources.Robot.Basic3; break;
                case 3:  basicimage = Resources.Robot.Basic4; break;
                case 4:  basicimage = Resources.Robot.Basic5; break;
                case 5:  basicimage = Resources.Robot.Basic6; break;
                }
            }

            if (alive)
            {
                // FIXME: we should just call RobotFile.draw here.
                gfx.DrawImage(basicimage, (int)x - 16, (int)y - 16);

                // FIXME: different turret types
                // FIXME: possibly invert color like the original?
                gfx.DrawLine(Pens.Black, (int)x, (int)y,
                    (int)(x + ((Constants.ROBOT_RADIUS - 1) * Math.Sin(aim * Constants.DEG_TO_RAD))),
                    (int)(y - ((Constants.ROBOT_RADIUS - 1) * Math.Cos(aim * Constants.DEG_TO_RAD))));
            }

            else if (aim > 0)
            {
                // Create a brush to fill pie pieces with. Don't do wrapping / tiling.
                TextureBrush brush = new TextureBrush(basicimage, WrapMode.Clamp);

                // The texture starts at (0,0). Here, we initialy position it correctly.
                brush.TranslateTransform((int)speedx - 16, (int)speedy - 16);

                // Our pie bounds. This is needs to fit a circle that fully encompasses the icon.
                Rectangle r = new Rectangle((int)speedx - 23, (int)speedy - 23, 46, 46);

                // We need to offset both the texture and the rectangle each time. :(
                // Utility function, ahoy!
                DrawOffsetHelper offset = delegate(int ox, int oy) {
                    r.Offset(ox, oy);
                    brush.TranslateTransform(ox, oy);
                };

                offset(2 * aim, aim);
                gfx.FillPie(brush, r, 0, 45);
                offset(-aim, aim);
                gfx.FillPie(brush, r, 45, 45);
                offset(-2 * aim, 0);
                gfx.FillPie(brush, r, 90, 45);
                offset(-aim, -aim);
                gfx.FillPie(brush, r, 135, 45);
                offset(0, -2 * aim);
                gfx.FillPie(brush, r, 180, 45);
                offset(aim, -aim);
                gfx.FillPie(brush, r, 225, 45);
                offset(2 * aim, 0);
                gfx.FillPie(brush, r, 270, 45);
                offset(aim, aim);
                gfx.FillPie(brush, r, 315, 45);
            }
        }
Exemple #28
0
        void CreatePatternBrush(float pixelSize)
        {
            //  Determine adjusted pixel size of the brush to create.
            const float MAX_PATTERN_SIZE = 80;
            const float MIN_PATTERN_SIZE = 10;
            if (pixelSize < patternWidth / MAX_PATTERN_SIZE)
                pixelSize = patternWidth / MAX_PATTERN_SIZE;
            if (pixelSize < patternHeight / MAX_PATTERN_SIZE)
                pixelSize = patternHeight / MAX_PATTERN_SIZE;
            if (pixelSize > patternWidth / MIN_PATTERN_SIZE)
                pixelSize = patternWidth / MIN_PATTERN_SIZE;
            if (pixelSize > patternHeight / MIN_PATTERN_SIZE)
                pixelSize = patternHeight / MIN_PATTERN_SIZE;

            if (patternBrushes != null && Math.Abs(pixelSize - pixelSizeCached) / pixelSize < 0.01)
                return;         // the pattern brush is already OK size.

            // Get size of bitmap to create with the image of the pattern.
            float width = (float) Math.Round(patternWidth / pixelSize);
            float height = (float) Math.Round(patternHeight / pixelSize);

            // Create dictionary to hold brushes for each color.
            patternBrushes = new Dictionary<SymColor, Brush>(2);
            pixelSizeCached = pixelSize;

            RenderOptions renderOpts = new RenderOptions();
            renderOpts.minResolution = pixelSize;
            renderOpts.usePatternBitmaps = false;

            foreach (SymColor color in map.colors) {
                if (!patternGlyph.HasColor(color))
                    continue;

                // Create a new bitmap and fill it transparent.
                Bitmap bitmap = new Bitmap((int) width, (int) (offsetRows ? height * 2 : height));
                Graphics g = Graphics.FromImage(bitmap);
                g.CompositingMode = CompositingMode.SourceCopy;
                g.SmoothingMode = SmoothingMode.HighQuality;
                g.FillRectangle(new SolidBrush(Color.Transparent), 0, 0, bitmap.Width, bitmap.Height);

                // Set the center of the bitmap to 0,0, and scale to mm (each pixel is 0.01 mm).
                g.TranslateTransform(width / 2.0F, height / 2.0F);
                g.ScaleTransform(width / patternWidth, height / patternHeight);

                // Draw the pattern into the bitmap.
                GraphicsTarget grTarget = new GraphicsTarget(g);
                patternGlyph.Draw(grTarget, new PointF(0F, 0F), -patternAngle, GraphicsUtil.IdentityMatrix, null, color, renderOpts);

                if (offsetRows) {
                    patternGlyph.Draw(grTarget, new PointF(patternWidth / 2, patternHeight), -patternAngle, GraphicsUtil.IdentityMatrix, null, color, renderOpts);
                    patternGlyph.Draw(grTarget, new PointF(-patternWidth / 2, patternHeight), -patternAngle, GraphicsUtil.IdentityMatrix, null, color, renderOpts);
                }

                // Create a TextureBrush on the bitmap.
                TextureBrush brush = new TextureBrush(bitmap);

                // Scale and the texture brush.
                brush.RotateTransform(patternAngle);
                brush.ScaleTransform(patternWidth / width, patternHeight / height);
                brush.TranslateTransform(-width / 2.0F, -height / 2.0F);

                // Dispose of the graphics.
                g.Dispose();

                // Add it to the collection of brushes.
                patternBrushes.Add(color, brush);
            }
        }
		protected override void OnPaint(PaintEventArgs e)
		{
			base.OnPaint(e);
			
			Rectangle rectPreview = this.ClientRectangle;
			Color brightChecker = this.prevImageLum > 0.5f ? Color.FromArgb(48, 48, 48) : Color.FromArgb(224, 224, 224);
			Color darkChecker = this.prevImageLum > 0.5f ? Color.FromArgb(32, 32, 32) : Color.FromArgb(192, 192, 192);
			e.Graphics.FillRectangle(new HatchBrush(HatchStyle.LargeCheckerBoard, brightChecker, darkChecker), this.rectImage);
			if (this.prevImage != null)
			{
				TextureBrush bgImageBrush = new TextureBrush(this.prevImage);
				bgImageBrush.ResetTransform();
				bgImageBrush.TranslateTransform(this.rectImage.X, this.rectImage.Y);
				e.Graphics.FillRectangle(bgImageBrush, this.rectImage);
			}

			if (this.prevSoundInst != null)
			{
				e.Graphics.DrawImage(this.prevImageLum > 0.5f ? EditorBaseResCache.IconSpeakerWhite : EditorBaseResCache.IconSpeakerBlack, 
					this.rectPrevSound.X, 
					this.rectPrevSound.Y);
			}
			else
			{
				e.Graphics.DrawImageAlpha(this.prevImageLum > 0.5f ? EditorBaseResCache.IconSpeakerWhite : EditorBaseResCache.IconSpeakerBlack, 
					0.5f,
					this.rectPrevSound.X, 
					this.rectPrevSound.Y);
			}

			ControlRenderer.DrawBorder(e.Graphics, 
				rectPreview, 
				BorderStyle.Simple, 
				!this.Enabled ? BorderState.Disabled : BorderState.Normal);
		}
        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);

            Rectangle rectPreview = this.ClientRectangle;
            Rectangle rectImage = new Rectangle(rectPreview.X + 1, rectPreview.Y + 1, rectPreview.Width - 2, rectPreview.Height - 2);
            Color brightChecker = this.prevImageLum > 0.5f ? Color.FromArgb(48, 48, 48) : Color.FromArgb(224, 224, 224);
            Color darkChecker = this.prevImageLum > 0.5f ? Color.FromArgb(32, 32, 32) : Color.FromArgb(192, 192, 192);
            e.Graphics.FillRectangle(new HatchBrush(HatchStyle.LargeCheckerBoard, brightChecker, darkChecker), rectImage);
            if (this.prevImage != null)
            {
                TextureBrush bgImageBrush = new TextureBrush(this.prevImage);
                bgImageBrush.ResetTransform();
                bgImageBrush.TranslateTransform(rectImage.X, rectImage.Y);
                e.Graphics.FillRectangle(bgImageBrush, rectImage);
            }

            ControlRenderer.DrawBorder(e.Graphics,
                rectPreview,
                BorderStyle.Simple,
                !this.Enabled ? BorderState.Disabled : BorderState.Normal);
        }
Exemple #31
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;
        }