Exemple #1
0
        public void Draw(DrawingContext gfx, TileMap map)
        {
            if (map.Sprite != null)
            {
                if (tiles == null)
                {
                    tiles = new RenderTargetBitmap(new PixelSize(map.Width, map.Height));
                    using DrawingContext mgfx = new DrawingContext(tiles.CreateDrawingContext(null));
                    //mgfx.Clip = new Region(new Rectangle(new Point(), new Size(map.Width, map.Height)));
                    int x = 0;
                    int y = 0;
                    foreach (int tile in map.Tiles)
                    {
                        using MemoryStream stream = new MemoryStream();
                        map.Image(tile).Save(stream, ImageFormat.Png);
                        stream.Position = 0;
                        mgfx.DrawImage(new Avalonia.Media.Imaging.Bitmap(stream), new Rect(0, 0, map.Sprite.Width, map.Sprite.Height), new Rect(x * map.Sprite.Width, y * map.Sprite.Height, map.Sprite.Width, map.Sprite.Height));
                        x++;
                        if (x >= map.Columns)
                        {
                            x = 0;
                            y++;
                        }
                    }
                }

                gfx?.DrawImage(tiles, new Rect(0, 0, tiles.Size.Width, tiles.Size.Height), new Rect(0, 0, tiles.Size.Width, tiles.Size.Height));
            }
        }
Exemple #2
0
        public void Draw(DrawingContext gfx, Description2D description)
        {
            if (description != null)
            {
                if (description.HasImage())
                {
                    Rect dest = new Rect((int)(description.X + description.DrawOffsetX) - (description?.Sprite?.X ?? 0), (int)(description.Y + description.DrawOffsetY) - (description?.Sprite?.Y ?? 0), description.Width, description.Height);

                    System.Drawing.Image img = description.Image();
                    if (!storedBitmaps.ContainsKey(description.Image()))
                    {
                        using MemoryStream stream = new MemoryStream();
                        img.Save(stream, ImageFormat.Png);
                        stream.Position = 0;
                        storedBitmaps.Add(img, new Bitmap(stream));
                    }

                    gfx?.DrawImage(storedBitmaps[img], new Rect(0, 0, description.Width, description.Height), dest);
                }
            }
        }
Exemple #3
0
        public static IntPtr GenerateHICON(ImageSource image, Size dimensions)
        {
            if (image == null)
            {
                return(IntPtr.Zero);
            }

            // If we're getting this from a ".ico" resource, then it comes through as a BitmapFrame.
            // We can use leverage this as a shortcut to get the right 16x16 representation
            // because DrawImage doesn't do that for us.
            var bf = image as BitmapFrame;

            if (bf != null)
            {
                bf = GetBestMatch(bf.Decoder.Frames, (int)dimensions.Width, (int)dimensions.Height);
            }
            else
            {
                // Constrain the dimensions based on the aspect ratio.
                var drawingDimensions = new Rect(0, 0, dimensions.Width, dimensions.Height);

                // There's no reason to assume that the requested image dimensions are square.
                double renderRatio = dimensions.Width / dimensions.Height;
                double aspectRatio = image.Width / image.Height;

                // If it's smaller than the requested size, then place it in the middle and pad the image.
                if (image.Width <= dimensions.Width && image.Height <= dimensions.Height)
                {
                    drawingDimensions = new Rect((dimensions.Width - image.Width) / 2, (dimensions.Height - image.Height) / 2, image.Width, image.Height);
                }
                else if (renderRatio > aspectRatio)
                {
                    double scaledRenderWidth = (image.Width / image.Height) * dimensions.Width;
                    drawingDimensions = new Rect((dimensions.Width - scaledRenderWidth) / 2, 0, scaledRenderWidth, dimensions.Height);
                }
                else if (renderRatio < aspectRatio)
                {
                    double scaledRenderHeight = (image.Height / image.Width) * dimensions.Height;
                    drawingDimensions = new Rect(0, (dimensions.Height - scaledRenderHeight) / 2, dimensions.Width, scaledRenderHeight);
                }

                var            dv = new DrawingVisual();
                DrawingContext dc = dv.RenderOpen();
                dc.DrawImage(image, drawingDimensions);
                dc.Close();

                var bmp = new RenderTargetBitmap((int)dimensions.Width, (int)dimensions.Height, 96, 96, PixelFormats.Pbgra32);
                bmp.Render(dv);
                bf = BitmapFrame.Create(bmp);
            }

            // Using GDI+ to convert to an HICON.
            // I'd rather not duplicate their code.
            using (MemoryStream memstm = new MemoryStream())
            {
                BitmapEncoder enc = new PngBitmapEncoder();
                enc.Frames.Add(bf);
                enc.Save(memstm);

                using (var istm = new ManagedIStream(memstm))
                {
                    // We are not bubbling out GDI+ errors when creating the native image fails.
                    IntPtr bitmap = IntPtr.Zero;
                    try
                    {
                        Status gpStatus = NativeMethods.GdipCreateBitmapFromStream(istm, out bitmap);
                        if (Status.Ok != gpStatus)
                        {
                            return(IntPtr.Zero);
                        }

                        IntPtr hicon;
                        gpStatus = NativeMethods.GdipCreateHICONFromBitmap(bitmap, out hicon);
                        if (Status.Ok != gpStatus)
                        {
                            return(IntPtr.Zero);
                        }

                        // Caller is responsible for freeing this.
                        return(hicon);
                    }
                    finally
                    {
                        Utility.SafeDisposeImage(ref bitmap);
                    }
                }
            }
        }
Exemple #4
0
        //Afiseaza imaginile si apeleaza Detect Face
        private async void BrowseButton_Click(object sender, RoutedEventArgs e)
        {
            //Primeste imaginea de scanat de la user.
            var openDlg = new Microsoft.Win32.OpenFileDialog();

            openDlg.Filter = "JPEG Image(*.jpg)|*.jpg";
            bool?result = openDlg.ShowDialog(this);

            //Returneaza daca se da cancel
            if (!(bool)result)
            {
                return;
            }

            //Afiseaza imaginea
            string filePath = openDlg.FileName;

            Uri         fileUri      = new Uri(filePath);
            BitmapImage bitmapSource = new BitmapImage();

            bitmapSource.BeginInit();
            bitmapSource.CacheOption = BitmapCacheOption.None;
            bitmapSource.UriSource   = fileUri;
            bitmapSource.EndInit();

            FacePhoto.Source = bitmapSource;

            //Detecteaza fetele din imagine
            Title = "Detecting...";
            faces = await UploadAndDetectFaces(filePath);

            Title = String.Format("Detection Finished. {0} face(s) detected", faces.Length);

            if (faces.Length > 0)
            {
                //Pregateste desenarea dreptunghiului in jurul fetelor
                DrawingVisual  visual         = new DrawingVisual();
                DrawingContext drawingContext = visual.RenderOpen();
                drawingContext.DrawImage(bitmapSource,
                                         new Rect(0, 0, bitmapSource.Width, bitmapSource.Height));
                double dpi = bitmapSource.DpiX;
                resizeFactor     = 96 / dpi;
                faceDescriptions = new String[faces.Length];

                for (int i = 0; i < faces.Length; ++i)
                {
                    Face face = faces[i];

                    //Deseneaza un dreptunghi in jurul fetei
                    drawingContext.DrawRectangle(
                        Brushes.Transparent,
                        new Pen(Brushes.Red, 2),
                        new Rect(
                            face.FaceRectangle.Left * resizeFactor,
                            face.FaceRectangle.Top * resizeFactor,
                            face.FaceRectangle.Width * resizeFactor,
                            face.FaceRectangle.Height * resizeFactor
                            )
                        );

                    //Salveaza descrierea fetei
                    faceDescriptions[i] = FaceDescription(face);
                }

                drawingContext.Close();

                //Afiseaza imaginea cu dreptunghiuri in jurul fetelor
                RenderTargetBitmap faceWithRectBitmap = new RenderTargetBitmap(
                    (int)(bitmapSource.PixelWidth * resizeFactor),
                    (int)(bitmapSource.PixelHeight * resizeFactor),
                    96,
                    96,
                    PixelFormats.Pbgra32);

                faceWithRectBitmap.Render(visual);
                FacePhoto.Source = faceWithRectBitmap;

                //Seteaza textul pentru bara de jos
                faceDescriptionStatusBar.Text = "Place the mouse pointer over a face to see the face description.";
            }
        }
Exemple #5
0
        public bool Perform(DrawingContext context, GraphControl self, Point mousePos)
        {
            //DrawBG;
            Brush brush = ColorIdentifier.Background.get().toBrush();

            context.DrawRoundedRectangle(brush,
                                         new Pen(ColorIdentifier.InserterOutline.get().toBrush(),
                                                 DoubleIdentifier.InserterOutlineThickness.get()),
                                         new Rect(_pos, _size), DoubleIdentifier.InserterCornerRadius.get(), DoubleIdentifier.InserterCornerRadius.get());

            //Draw heading
            var f = new FormattedText(
                "Insert Node",
                CultureInfo.CurrentCulture,
                FlowDirection.LeftToRight,
                new Typeface("Verdana"), 12, ColorIdentifier.TilteText.get().toBrush(), VisualTreeHelper.GetDpi(self).PixelsPerDip);

            context.DrawText(
                f,
                new Point(_pos.X + (_size.Width - f.Width) / 2, _pos.Y + 2)
                );
            context.DrawLine(
                new Pen(
                    ColorIdentifier.InserterOutline.get().toBrush(), 1),
                new Point(_pos.X, _pos.Y + f.Height + 4),
                new Point(_pos.X + _size.Width, _pos.Y + f.Height + 4));

            //Draw SearchBox
            context.DrawImage(_searchIcon, new Rect(_pos.X + 4, _pos.Y + f.Height + 8, f.Height, f.Height));

            //TODO: DrawSearch String

            context.DrawLine(
                new Pen(
                    ColorIdentifier.InserterOutline.get().toBrush(),
                    DoubleIdentifier.InserterSeperatorThickness.get()),
                new Point(_pos.X, _pos.Y + f.Height + 12 + f.Height),
                new Point(_pos.X + _size.Width, _pos.Y + f.Height + 12 + f.Height)
                );
            //Draw Path
            double curY = _pos.Y + f.Height + 14 + f.Height;

            _rects = new List <Tuple <Rect, bool, string, Type> >();
            if (_path.Length > 0)
            {
                var sFormattedText = new FormattedText(
                    _path,
                    CultureInfo.CurrentCulture,
                    FlowDirection.LeftToRight,
                    new Typeface("Verdana"), 12, Brushes.White, VisualTreeHelper.GetDpi(self).PixelsPerDip)
                {
                    MaxTextWidth = _size.Width - 5
                };

                if (new Rect(new Point(_pos.X, curY), new Size(_size.Width, sFormattedText.Height)).Contains(mousePos))
                {
                    context.DrawRectangle(ColorIdentifier.Line2.get().toBrush(), null, new Rect(new Point(_pos.X, curY), new Size(_size.Width, sFormattedText.Height)));
                }

                context.DrawText(
                    sFormattedText,
                    new Point(_pos.X + 3, curY + 1)
                    );
                _rects.Add(new Tuple <Rect, bool, string, Type>(
                               new Rect(new Point(_pos.X, curY), new Size(_size.Width, sFormattedText.Height)), true, "\nReverse", null
                               ));
                curY += sFormattedText.Height + 4;
            }

            //Draw Items
            double toY = _pos.Y + _size.Height - 8;

            List <Tuple <string, Type> > items = new List <Tuple <string, Type> >(
                _nodeDict.Where(x => x.Item1.StartsWith(_path))
                );

            _drawnFolders = new List <string>();

            //apply scroll
            int tScroll = _scroll;

            tScroll = tScroll.InRange(0, items.Count - 1);

            for (int i = tScroll; i < items.Count; i++)
            {
                if (curY < toY)
                {
                    DrawElement(context, self, items[i].Item1, mousePos, items[i].Item2, ref curY);
                }
            }

            return(false);
        }
Exemple #6
0
        protected override void OnRender(DrawingContext dc)
        {
            if (PointsToDisplay != null)
            {
                Log.Debug("PointsToDisplay is not empty - rendering points");

                var canvasWidth  = (int)ActualWidth;
                var canvasHeight = (int)ActualHeight;

                if (canvasWidth > 0 && canvasHeight > 0)
                {
                    //Create the bitModeScreenCoordinateToKeyMap
                    var wb = new WriteableBitmap(canvasWidth, canvasHeight, 96, 96, PixelFormats.Bgra32, null);

                    //Create a new image
                    var img = new Image
                    {
                        Source              = wb,
                        Stretch             = Stretch.None,
                        HorizontalAlignment = HorizontalAlignment.Left,
                        VerticalAlignment   = VerticalAlignment.Top
                    };

                    //Set scaling mode, edge mode and z index on canvas
                    RenderOptions.SetBitmapScalingMode(img, BitmapScalingMode.NearestNeighbor);
                    RenderOptions.SetEdgeMode(img, EdgeMode.Aliased);
                    SetZIndex(img, -100);

                    //Each "dot" is 3x3 rectangle (centered on the coordinate detected)
                    var rect   = new Int32Rect(0, 0, 3, 3);
                    int size   = rect.Width * rect.Height * 4;
                    var pixels = new byte[size];

                    int screenCoordinatesIndex           = 0;
                    int screenCoordinatesIndexUpperBound = PointsToDisplay.Count - 1;

                    foreach (Point capturedCoordinate in PointsToDisplay)
                    {
                        Point canvasPoint = PointFromScreen(capturedCoordinate); //Convert screen to canvas point

                        if (canvasPoint.X >= 0 && canvasPoint.X < canvasWidth &&
                            canvasPoint.Y >= 0 && canvasPoint.Y < canvasHeight)
                        {
                            SetPixelValuesToRainbow(pixels, rect, screenCoordinatesIndex, screenCoordinatesIndexUpperBound); //Set up pixel colours (as RGB and Alpha array of bytes)

                            //We are drawing a 3x3 dot so try to start one pixel up and left (center pixel of rectangle will be the co-ordinate)
                            //If coord in against the top or left side (x=0 and/or y=0) this cannot be done, so just place as close as possible
                            //If coord in against the bottom or right side (x>=canvasWidth-1 and/or y>=canvasHeight-1) this cannot be done either, so just place as close as possible
                            rect.X = (int)canvasPoint.X == 0
                                ? (int)canvasPoint.X
                                : (int)canvasPoint.X > 0 && (int)canvasPoint.X < canvasWidth - 1
                                    ? (int)canvasPoint.X - 1
                                    : (int)canvasPoint.X - 2;

                            rect.Y = (int)canvasPoint.Y == 0
                                ? (int)canvasPoint.Y
                                : (int)canvasPoint.Y > 0 && (int)canvasPoint.Y < canvasHeight - 1
                                    ? (int)canvasPoint.Y - 1
                                    : (int)canvasPoint.Y - 2;

                            wb.WritePixels(rect, pixels, rect.Width * 4, 0);

                            screenCoordinatesIndex++;
                        }
                    }

                    dc.DrawImage(wb, new Rect(0, 0, canvasWidth, canvasHeight));
                }
            }
            else
            {
                Log.Debug("OnRender - PointsToDisplay is empty - nothing to render");
            }

            base.OnRender(dc);
        }
Exemple #7
0
        public void DrawImage(Image image, RectangleF destRect, RectangleF srcRect, long transparentColor, int brightness, int contrast, int gamma, Color shadowColor, Stream imgData)
        {
            if (PointOutside.Check(ref srcRect))
            {
                return;
            }
            if (PointOutside.Check(ref destRect))
            {
                return;
            }
            if (image.Height <= 0 || image.Width <= 0)
            {
                return;
            }
            bool ChangedParams = brightness != FlxConsts.DefaultBrightness ||
                                 contrast != FlxConsts.DefaultContrast ||
                                 gamma != FlxConsts.DefaultGamma ||
                                 shadowColor != Colors.Transparent;

            ImageAttributes imgAtt = null;

            try
            {
                if (transparentColor != FlxConsts.NoTransparentColor)
                {
                    long  cl  = transparentColor;
                    Color tcl = ColorUtil.FromArgb(0xFF, (byte)(cl & 0xFF), (byte)((cl & 0xFF00) >> 8), (byte)((cl & 0xFF0000) >> 16));
                    imgAtt = new ImageAttributes();
                    imgAtt.SetColorKey(tcl, tcl);
                }

                if (gamma != FlxConsts.DefaultGamma)
                {
                    if (imgAtt == null)
                    {
                        imgAtt = new ImageAttributes();
                    }
                    imgAtt.SetGamma((real)((UInt32)gamma) / 65536f);
                }

                if (!ChangedParams && srcRect.Top == 0 && srcRect.Left == 0 && srcRect.Width == image.Width && srcRect.Height == image.Height && imgAtt == null)
                {
                    FCanvas.DrawImage(image, destRect);
                }
                else
                {
                    Image FinalImage = image;
                    try
                    {
                        if (image.RawFormat.Equals(ImageFormat.Wmf) || image.RawFormat.Equals(ImageFormat.Emf))
                        {
                            FinalImage = FlgConsts.RasterizeWMF(image);                             //metafiles do not like cropping or changing attributes.
                        }

                        if (ChangedParams)
                        {
                            if (shadowColor != ColorUtil.Empty)
                            {
                                FlgConsts.MakeImageGray(ref imgAtt, shadowColor);
                            }
                            else
                            {
                                FlgConsts.AdjustImage(ref imgAtt, brightness, contrast);
                            }
                        }

                        PointF[] ImageRect = new PointF[] { new PointF(destRect.Left, destRect.Top), new PointF(destRect.Right, destRect.Top), new PointF(destRect.Left, destRect.Bottom) };
                        FCanvas.DrawImage(FinalImage,
                                          ImageRect,
                                          srcRect, GraphicsUnit.Pixel, imgAtt);
                    }
                    finally
                    {
                        if (FinalImage != image)
                        {
                            FinalImage.Dispose();
                        }
                    }
                }
            }
            finally
            {
                if (imgAtt != null)
                {
                    imgAtt.Dispose();
                }
            }
        }
Exemple #8
0
        protected override void OnRender(DrawingContext drawingContext)
        {
            if (DesignerProperties.GetIsInDesignMode(this))
            {
                return;
            }
            if (plotter == null)
            {
                return;
            }

            rendering         = true;
            invalidatePending = false;

            base.OnRender(drawingContext);

            var      transform = plotter.Viewport.Transform;
            Rect     output    = plotter.Viewport.Output;
            DataRect visible   = plotter.Viewport.Visible;

            visibleBounds = visible;

            var tileInfos = GetVisibleTiles();

            //Debug.WriteLine(String.Format("OnRender: {0}", DateTime.Now.TimeOfDay.ToString()));

            var dc             = drawingContext;
            var lowerTilesList = GetLoadedLowerTiles(tileInfos);

            // displaying lower tiles
            if (showLowerTiles)
            {
                foreach (var tileInfo in lowerTilesList)
                {
                    var tile = tileInfo.Id;

                    if (server.IsLoaded(tile))
                    {
                        var      bmp          = server[tile];
                        DataRect visibleRect  = tileProvider.GetTileBounds(tile);
                        Rect     screenRect   = visibleRect.ViewportToScreen(transform);
                        Rect     enlargedRect = EnlargeRect(screenRect);

                        dc.PushClip(tileInfo.Clip);
                        dc.DrawImage(bmp, enlargedRect);
                        dc.Pop();

                        //if (!visibleRect.IntersectsWith(visible))
                        //{
                        //    dc.DrawRectangle(Brushes.Red, null, output);
                        //}

                        if (drawDebugBounds)
                        {
                            DrawDebugInfo(dc, enlargedRect, tile);
                        }
                    }
                    else
                    {
                        server.BeginLoadImage(tile);
                    }
                }
            }

            foreach (var tileInfo in tileInfos)
            {
                if (server.IsLoaded(tileInfo.Tile))
                {
                    var bmp = server[tileInfo.Tile];

                    Rect enlargedRect = EnlargeRect(tileInfo.ScreenBounds);
                    drawingContext.DrawImage(bmp, enlargedRect);

                    // drawing debug bounds
                    if (drawDebugBounds)
                    {
                        DrawDebugInfo(drawingContext, tileInfo.ScreenBounds, tileInfo.Tile);
                    }
                }
                else
                {
                    server.BeginLoadImage(tileInfo.Tile);
                }
            }

            rendering = false;
        }
        private void DrawPlayerIcon(DrawingContext drawingContext, Character player, Coordinate screenCoordinate)
        {
            switch (player.Job)
            {
            case JOB.ACN:
            case JOB.SCH:
                drawingContext.DrawImage(_playerSch,
                                         new Rect(new Point(screenCoordinate.X, screenCoordinate.Y),
                                                  new Size(16, 16)));
                break;

            case JOB.ARC:
            case JOB.BRD:
                drawingContext.DrawImage(_playerBrd,
                                         new Rect(new Point(screenCoordinate.X, screenCoordinate.Y),
                                                  new Size(16, 16)));
                break;

            case JOB.THM:
            case JOB.BLM:
                drawingContext.DrawImage(_playerBlm,
                                         new Rect(new Point(screenCoordinate.X, screenCoordinate.Y),
                                                  new Size(16, 16)));
                break;

            case JOB.LNC:
            case JOB.DRG:
                drawingContext.DrawImage(_playerDrg,
                                         new Rect(new Point(screenCoordinate.X, screenCoordinate.Y),
                                                  new Size(16, 16)));
                break;

            case JOB.WAR:
            case JOB.MRD:
                drawingContext.DrawImage(_playerMrd,
                                         new Rect(new Point(screenCoordinate.X, screenCoordinate.Y),
                                                  new Size(16, 16)));
                break;

            case JOB.PGL:
            case JOB.MNK:
                drawingContext.DrawImage(_playerMnk,
                                         new Rect(new Point(screenCoordinate.X, screenCoordinate.Y),
                                                  new Size(16, 16)));
                break;

            case JOB.GLD:
            case JOB.PLD:
                drawingContext.DrawImage(_playerPld,
                                         new Rect(new Point(screenCoordinate.X, screenCoordinate.Y),
                                                  new Size(16, 16)));
                break;

            case JOB.CNJ:
            case JOB.WHM:
                drawingContext.DrawImage(_playerWhm,
                                         new Rect(new Point(screenCoordinate.X, screenCoordinate.Y),
                                                  new Size(16, 16)));
                break;

            case JOB.SMN:
                drawingContext.DrawImage(_playerSmn,
                                         new Rect(new Point(screenCoordinate.X, screenCoordinate.Y),
                                                  new Size(16, 16)));
                break;

            default:
                drawingContext.DrawImage(_playericon,
                                         new Rect(new Point(screenCoordinate.X, screenCoordinate.Y),
                                                  new Size(16, 16)));
                break;
            }
        }
        protected override void OnRender(DrawingContext drawingContext)
        {
            base.OnRender(drawingContext);

            if (MemoryLocations.Database.Count == 0)
            {
                return;
            }

            Coordinate origin = new Coordinate((float)((this.ActualWidth / 2)),
                                               (float)((this.ActualHeight / 2)), 0);


            float scale    = ((float)(this.ActualHeight / 2.0f) / 125.0f);
            int   targetID = -1;

            List <int> aggroList = _aggrohelper.GetAggroList();

            Pen dashedPen = new Pen(new SolidColorBrush(Colors.White), 2);

            dashedPen.DashStyle = DashStyles.DashDotDot;

            Pen targetedPen = new Pen(new SolidColorBrush(Colors.Yellow), 1);

            targetedPen.DashStyle = DashStyles.DashDotDot;

            try // Added this because the designer was going crazy without it.
            {
                targetID = MemoryFunctions.GetTarget();
                MemoryFunctions.GetCharacters(_monsters, _fate, _players, ref _user);
                MemoryFunctions.GetNPCs(_npcs);
                MemoryFunctions.GetGathering(_gathering);
            } catch
            {
                return;
            }


            float rotationAmount;

            if (CompassMode)
            {
                rotationAmount = _user.Heading;

                drawingContext.DrawImage(_radarheading,
                                         new Rect(new Point(origin.X - 128, origin.Y - 256),
                                                  new Size(256, 256)));
            }
            else
            {
                rotationAmount = (float)3.14159265;
            }


            if (ShowPlayers)
            {
                foreach (Character player in _players)
                {
                    if (player.Valid == false)
                    {
                        continue;
                    }

                    if (player.Name.ToLower().Contains(Filter) == false)
                    {
                        continue;
                    }

                    if (_user.Valid == false)
                    {
                        return;
                    }

                    if (_user.IsHidden)
                    {
                        continue;
                    }


                    Coordinate offset           = _user.Coordinate.Subtract(player.Coordinate).Rotate2d(rotationAmount).Scale(scale);
                    Coordinate screenCoordinate = offset.Add(origin);

                    if (player.Address == targetID)
                    {
                        drawingContext.DrawEllipse(Brushes.Transparent, new Pen(new SolidColorBrush(Colors.Cyan), 2),
                                                   new Point(screenCoordinate.X, screenCoordinate.Y), 13, 13);
                    }

                    if (player.Name == _user.Name)
                    {
                        continue;
                    }

                    if (player.TargetID == _user.Address)
                    {
                        drawingContext.DrawLine(targetedPen, new Point(origin.X, origin.Y), new Point(screenCoordinate.X, screenCoordinate.Y));
                    }

                    screenCoordinate = screenCoordinate.Add(-8, -8, 0);

                    if (player.Health_Current == 0)
                    {
                        drawingContext.DrawImage(_skullicon,
                                                 new Rect(new Point(screenCoordinate.X, screenCoordinate.Y),
                                                          new Size(16, 16)));
                    }
                    else
                    {
                        DrawPlayerIcon(drawingContext, player, screenCoordinate);
                    }



                    if (ShowPlayerName)
                    {
                        FormattedText playerLabel = new FormattedText(player.ToString(), System.Globalization.CultureInfo.InvariantCulture, FlowDirection.LeftToRight, new Typeface("Arial"), 8, Brushes.White);

                        drawingContext.DrawText(playerLabel, new Point(screenCoordinate.X - 15, screenCoordinate.Y - 13));
                    }
                }
            }



            if (ShowMonsters)
            {
                foreach (Character monster in _monsters)
                {
                    if (monster.Name.ToLower().Contains(Filter) == false)
                    {
                        continue;
                    }

                    if (monster.IsHidden)
                    {
                        continue;
                    }

                    Coordinate offset;

                    try
                    {
                        offset = _user.Coordinate.Subtract(monster.Coordinate).Rotate2d(rotationAmount).Scale(scale);
                    } catch
                    {
                        return;
                    }

                    Coordinate screenCoordinate = offset.Add(origin);

                    if (monster.Address == targetID)
                    {
                        drawingContext.DrawEllipse(Brushes.Transparent, new Pen(new SolidColorBrush(Colors.Cyan), 2),
                                                   new Point(screenCoordinate.X, screenCoordinate.Y), 12, 12);
                    }

                    // System.Diagnostics.Debug.Print(aggroList.Count.ToString());
                    // Check for aggro!
                    if (aggroList.Contains(monster.ID))
                    {
                        drawingContext.DrawLine(targetedPen, new Point(origin.X, origin.Y),
                                                new Point(screenCoordinate.X, screenCoordinate.Y));

                        drawingContext.DrawEllipse(Brushes.Red, new Pen(new SolidColorBrush(Colors.Red), 2),
                                                   new Point(screenCoordinate.X, screenCoordinate.Y), 8, 8);
                    }

                    screenCoordinate = screenCoordinate.Add(-8, -8, 0);


                    if (monster.Health_Current == 0)
                    {
                        drawingContext.DrawImage(_skullicon,
                                                 new Rect(new Point(screenCoordinate.X, screenCoordinate.Y),
                                                          new Size(16, 16)));
                    }
                    else
                    {
                        drawingContext.DrawImage(monster.IsClaimed?_monsterclaimedicon:_monstericon,
                                                 new Rect(new Point(screenCoordinate.X, screenCoordinate.Y),
                                                          new Size(16, 16)));
                    }

                    if (ShowMonsterName)
                    {
                        FormattedText monsterLabel = new FormattedText(monster.ToString() + " " + monster.UsingAbilityID.ToString("X"),
                                                                       System.Globalization.CultureInfo.InvariantCulture,
                                                                       FlowDirection.LeftToRight, new Typeface("Arial"), 8,
                                                                       Brushes.White);

                        drawingContext.DrawText(monsterLabel, new Point(screenCoordinate.X - 15, screenCoordinate.Y - 13));
                    }
                }
            }

            if (ShowHunts)
            {
                foreach (Character monster in _monsters)
                {
                    if (monster.Name.Contains("Bloody Mary") == false &&
                        monster.Name.Contains("Hellsclaw") == false &&
                        monster.Name.Contains("Garlok") == false &&
                        monster.Name.Contains("Barbastelle") == false &&
                        monster.Name.Contains("Unktehi") == false &&
                        monster.Name.Contains("Croakadile") == false &&
                        monster.Name.Contains("Skogs Fru") == false &&
                        monster.Name.Contains("Vogaal Ja") == false &&
                        monster.Name.Contains("Croque-Mitaine") == false &&
                        monster.Name.Contains("Vuokho") == false &&
                        monster.Name.Contains("Cornu") == false &&
                        monster.Name.Contains("Mahisha") == false &&
                        monster.Name.Contains("Myradrosh") == false &&
                        monster.Name.Contains("Marberry") == false &&
                        monster.Name.Contains("Nandi") == false &&
                        monster.Name.Contains("Dark Helmet") == false &&
                        monster.Name.Contains("Nahn") == false &&
                        monster.Name.Contains("Bonnacon") == false &&
                        monster.Name.Contains("White Joker") == false &&
                        monster.Name.Contains("Forneus") == false &&
                        monster.Name.Contains("Laideronnette") == false &&
                        monster.Name.Contains("Stinging Sophie") == false &&
                        monster.Name.Contains("Melt") == false &&
                        monster.Name.Contains("Wulgaru") == false &&
                        monster.Name.Contains("Phecda") == false &&
                        monster.Name.Contains("Girtab") == false &&
                        monster.Name.Contains("Thousand-cast Theda") == false &&
                        monster.Name.Contains("Ghede Ti Malice") == false &&
                        monster.Name.Contains("Mindflayer") == false &&
                        monster.Name.Contains("Naul") == false &&
                        monster.Name.Contains("Marraco") == false &&
                        monster.Name.Contains("Safat") == false &&
                        monster.Name.Contains("Ovjang") == false &&
                        monster.Name.Contains("Sabotender Bailarina") == false &&
                        monster.Name.Contains("Brontes") == false &&
                        monster.Name.Contains("Gatling") == false &&
                        monster.Name.Contains("Maahes") == false &&
                        monster.Name.Contains("Lampalagua") == false &&
                        monster.Name.Contains("Flame Sergeant Dalvag") == false &&
                        monster.Name.Contains("Dalvag's Final Flame") == false &&
                        monster.Name.Contains("Minhocao") == false &&
                        monster.Name.Contains("Albin the Ashen") == false &&
                        monster.Name.Contains("Zanig'oh") == false &&
                        monster.Name.Contains("Nunyunuwi") == false &&
                        monster.Name.Contains("Sewer Syrup") == false &&
                        monster.Name.Contains("Alectyron") == false &&
                        monster.Name.Contains("Zona Seeker") == false &&
                        monster.Name.Contains("Leech King") == false &&
                        monster.Name.Contains("Kurrea") == false &&
                        monster.Name.Contains("Agrippa") == false)
                    {
                        continue;
                    }


                    if (monster.IsHidden)
                    {
                        continue;
                    }

                    Coordinate offset;

                    try
                    {
                        offset = _user.Coordinate.Subtract(monster.Coordinate).Rotate2d(rotationAmount).Scale(scale);
                    }
                    catch
                    {
                        return;
                    }

                    Coordinate screenCoordinate = offset.Add(origin);

                    if (monster.Address == targetID)
                    {
                        drawingContext.DrawEllipse(Brushes.Transparent, new Pen(new SolidColorBrush(Colors.Cyan), 2),
                                                   new Point(screenCoordinate.X, screenCoordinate.Y), 12, 12);
                    }

                    // System.Diagnostics.Debug.Print(aggroList.Count.ToString());
                    // Check for aggro!
                    if (aggroList.Contains(monster.ID))
                    {
                        drawingContext.DrawLine(targetedPen, new Point(origin.X, origin.Y),
                                                new Point(screenCoordinate.X, screenCoordinate.Y));

                        drawingContext.DrawEllipse(Brushes.Red, new Pen(new SolidColorBrush(Colors.Red), 2),
                                                   new Point(screenCoordinate.X, screenCoordinate.Y), 8, 8);
                    }

                    screenCoordinate = screenCoordinate.Add(-8, -8, 0);


                    if (monster.Health_Current == 0)
                    {
                        drawingContext.DrawImage(_skullicon,
                                                 new Rect(new Point(screenCoordinate.X, screenCoordinate.Y),
                                                          new Size(16, 16)));
                    }
                    else
                    {
                        drawingContext.DrawImage(monster.IsClaimed ? _monsterclaimedicon : _monstericon,
                                                 new Rect(new Point(screenCoordinate.X, screenCoordinate.Y),
                                                          new Size(16, 16)));
                    }

                    if (ShowHuntsName)
                    {
                        FormattedText monsterLabel = new FormattedText(monster.ToString() + " " + monster.UsingAbilityID.ToString("X"),
                                                                       System.Globalization.CultureInfo.InvariantCulture,
                                                                       FlowDirection.LeftToRight, new Typeface("Arial"), 8,
                                                                       Brushes.White);

                        drawingContext.DrawText(monsterLabel, new Point(screenCoordinate.X - 15, screenCoordinate.Y - 13));
                    }
                }
            }

            if (ShowFate)
            {
                foreach (Character monster in _fate)
                {
                    if (monster.Name.ToLower().Contains(Filter) == false)
                    {
                        continue;
                    }

                    if (monster.IsHidden)
                    {
                        continue;
                    }

                    Coordinate offset;

                    try
                    {
                        offset = _user.Coordinate.Subtract(monster.Coordinate).Rotate2d(rotationAmount).Scale(scale);
                    }
                    catch
                    {
                        return;
                    }

                    Coordinate screenCoordinate = offset.Add(origin);

                    if (monster.Address == targetID)
                    {
                        drawingContext.DrawEllipse(Brushes.Transparent, new Pen(new SolidColorBrush(Colors.Cyan), 2),
                                                   new Point(screenCoordinate.X, screenCoordinate.Y), 12, 12);
                    }

                    // Check for aggro!
                    if (aggroList.Contains(monster.ID))
                    {
                        drawingContext.DrawLine(targetedPen, new Point(origin.X, origin.Y),
                                                new Point(screenCoordinate.X, screenCoordinate.Y));

                        drawingContext.DrawEllipse(Brushes.BlueViolet, new Pen(new SolidColorBrush(Colors.BlueViolet), 2),
                                                   new Point(screenCoordinate.X, screenCoordinate.Y), 8, 8);
                    }

                    screenCoordinate = screenCoordinate.Add(-8, -8, 0);


                    if (monster.Health_Current == 0)
                    {
                        drawingContext.DrawImage(_skullicon,
                                                 new Rect(new Point(screenCoordinate.X, screenCoordinate.Y),
                                                          new Size(16, 16)));
                    }
                    else
                    {
                        drawingContext.DrawImage(_fateicon,
                                                 new Rect(new Point(screenCoordinate.X, screenCoordinate.Y),
                                                          new Size(16, 16)));
                    }

                    if (ShowMonsterName)
                    {
                        FormattedText monsterLabel = new FormattedText(monster.ToString(),
                                                                       System.Globalization.CultureInfo.InvariantCulture,
                                                                       FlowDirection.LeftToRight, new Typeface("Arial"), 8,
                                                                       Brushes.White);

                        drawingContext.DrawText(monsterLabel, new Point(screenCoordinate.X - 15, screenCoordinate.Y - 13));
                    }
                }
            }

            if (ShowNPCs)
            {
                foreach (Character NPC in _npcs)
                {
                    if (NPC.Name.ToLower().Contains(Filter) == false)
                    {
                        continue;
                    }

                    if (NPC.Type == CharacterType.NPC && ShowNPCs == false)
                    {
                        continue;
                    }

                    if (NPC.IsHidden)
                    {
                        continue;
                    }

                    Coordinate screenCoordinate;

                    try
                    {
                        Coordinate offset = _user.Coordinate.Subtract(NPC.Coordinate).Rotate2d(rotationAmount).Scale(scale);
                        screenCoordinate = offset.Add(origin);
                    }
                    catch (Exception)
                    {
                        return;
                    }


                    if (NPC.Address == targetID)
                    {
                        drawingContext.DrawEllipse(Brushes.Transparent, new Pen(new SolidColorBrush(Colors.Cyan), 2),
                                                   new Point(screenCoordinate.X, screenCoordinate.Y), 13, 13);
                    }

                    screenCoordinate = screenCoordinate.Add(-8, -8, 0);


                    drawingContext.DrawImage(_npcicon,
                                             new Rect(new Point(screenCoordinate.X, screenCoordinate.Y),
                                                      new Size(16, 16)));

                    if (ShowNPCName)
                    {
                        FormattedText npcLabel = new FormattedText(NPC.Name,
                                                                   System.Globalization.CultureInfo.InvariantCulture,
                                                                   FlowDirection.LeftToRight, new Typeface("Arial"),
                                                                   8,
                                                                   Brushes.Wheat);

                        drawingContext.DrawText(npcLabel,
                                                new Point(screenCoordinate.X - 15, screenCoordinate.Y - 13));
                    }
                }
            }



            if (ShowGathering)
            {
                foreach (Gathering gather in _gathering)
                {
                    if (gather.Name.ToLower().Contains(Filter) == false)
                    {
                        continue;
                    }

                    if (gather.IsHidden && ShowHidden == false)
                    {
                        continue;
                    }


                    gather.IsHidden = false;

                    Coordinate screenCoordinate;

                    try
                    {
                        Coordinate offset = _user.Coordinate.Subtract(gather.Coordinate).Rotate2d(rotationAmount).Scale(scale);
                        screenCoordinate = offset.Add(origin);
                    }
                    catch (Exception)
                    {
                        return;
                    }


                    if (gather.Address == targetID)
                    {
                        drawingContext.DrawEllipse(Brushes.Transparent, new Pen(new SolidColorBrush(Colors.Cyan), 2),
                                                   new Point(screenCoordinate.X, screenCoordinate.Y), 13, 13);
                    }

                    screenCoordinate = screenCoordinate.Add(-8, -8, 0);


                    drawingContext.DrawImage(_woodicon,
                                             new Rect(new Point(screenCoordinate.X, screenCoordinate.Y),
                                                      new Size(16, 16)));

                    if (ShowGatheringName)
                    {
                        FormattedText npcLabel = new FormattedText(gather.Name,
                                                                   System.Globalization.CultureInfo.InvariantCulture,
                                                                   FlowDirection.LeftToRight, new Typeface("Arial"),
                                                                   8,
                                                                   Brushes.DarkOrange);

                        drawingContext.DrawText(npcLabel,
                                                new Point(screenCoordinate.X - 15, screenCoordinate.Y - 13));
                    }
                }
            }

            drawingContext.DrawEllipse(Brushes.Green, new Pen(new SolidColorBrush(Colors.Green), 1),
                                       new Point(origin.X, origin.Y), 4, 4);

            if (!CompassMode)
            {
                Coordinate heading = new Coordinate(0, 8, 0);
                heading = heading.Rotate2d(-_user.Heading);
                heading = heading.Add(origin);

                drawingContext.DrawLine(new Pen(new SolidColorBrush(Colors.Green), 5),
                                        new Point(origin.X, origin.Y),
                                        new Point(heading.X, heading.Y));
            }
        }
        protected override void OnRender(DrawingContext drawingContext)
        {
            Size renderSize = this.RenderSize;

            drawingContext.DrawRectangle(SystemColors.ControlBrush, null,
                                         new Rect(0, 0, renderSize.Width, renderSize.Height));
            drawingContext.DrawLine(new Pen(SystemColors.ControlDarkBrush, 1),
                                    new Point(renderSize.Width - 0.5, 0),
                                    new Point(renderSize.Width - 0.5, renderSize.Height));

            ICSharpCode.AvalonEdit.Rendering.TextView textView = this.TextView;
            if (textView != null && textView.VisualLinesValid)
            {
                // create a dictionary line number => first bookmark
                Dictionary <int, IBookmark> bookmarkDict = new Dictionary <int, IBookmark>();
                foreach (var bm in BookmarkManager.Bookmarks)
                {
                    if (bm is BreakpointBookmark)
                    {
                        if (DebugInformation.CodeMappings == null || DebugInformation.CodeMappings.Count == 0 ||
                            !DebugInformation.CodeMappings.ContainsKey(((BreakpointBookmark)bm).FunctionToken))
                        {
                            continue;
                        }
                    }
                    else
                    {
                        if (DebugInformation.DecompiledMemberReferences == null || DebugInformation.DecompiledMemberReferences.Count == 0 ||
                            !DebugInformation.DecompiledMemberReferences.ContainsKey(((MarkerBookmark)bm).MemberReference.MetadataToken.ToInt32()))
                        {
                            continue;
                        }
                    }
                    int       line = bm.LineNumber;
                    IBookmark existingBookmark;
                    if (!bookmarkDict.TryGetValue(line, out existingBookmark) || bm.ZOrder > existingBookmark.ZOrder)
                    {
                        bookmarkDict[line] = bm;
                    }
                }

                foreach (var bm in manager.Bookmarks)
                {
                    int       line = bm.LineNumber;
                    IBookmark existingBookmark;
                    if (!bookmarkDict.TryGetValue(line, out existingBookmark) || bm.ZOrder > existingBookmark.ZOrder)
                    {
                        bookmarkDict[line] = bm;
                    }
                }

                Size pixelSize = PixelSnapHelpers.GetPixelSize(this);
                foreach (VisualLine line in textView.VisualLines)
                {
                    int       lineNumber = line.FirstDocumentLine.LineNumber;
                    IBookmark bm;
                    if (bookmarkDict.TryGetValue(lineNumber, out bm))
                    {
                        Rect rect = new Rect(0, PixelSnapHelpers.Round(line.VisualTop - textView.VerticalOffset, pixelSize.Height), 16, 16);
                        if (dragDropBookmark == bm && dragStarted)
                        {
                            drawingContext.PushOpacity(0.5);
                        }
                        drawingContext.DrawImage(bm.Image, rect);
                        if (dragDropBookmark == bm && dragStarted)
                        {
                            drawingContext.Pop();
                        }
                    }
                }
                if (dragDropBookmark != null && dragStarted)
                {
                    Rect rect = new Rect(0, PixelSnapHelpers.Round(dragDropCurrentPoint - 8, pixelSize.Height), 16, 16);
                    drawingContext.DrawImage(dragDropBookmark.Image, rect);
                }
            }
        }
        public MainWindow()
        {
            string packindex = "WDK03";
            string packst    = File.ReadAllText(@"..\..\Texts\" + packindex + ".json");
            JArray pack      = JArray.Parse(packst);

            foreach (JObject card in pack)
            {
                String no       = card["no"].ToObject <String>();
                String name     = card["name"].ToObject <String>();
                String category = card["category"].ToObject <String>();
                String imgurl;
                if ((card["imgurl"] != null))
                {
                    imgurl = card["imgurl"].ToObject <String>();
                }
                else
                {
                    imgurl = "https://www.takaratomy.co.jp/products/wixoss/wxwp/images/card/" + packindex + "/" + no + ".jpg";
                }
                String cardcolor = card["color"].ToObject <String>();

                bool   vertical = (category != "키");
                double width    = vertical ? 1000 : 1396;
                double height   = vertical ? 1396 : 1000;
                Canvas canvas   = new Canvas
                {
                    Background = Brushes.Transparent,
                    Width      = width,
                    Height     = height,
                };

                if (category == "루리그")
                {
                    String type = card["type"].ToObject <String>();


                    TextBlock Lrig_index = new TextBlock
                    {
                        Text          = "루리그",
                        Background    = Brushes.Black,
                        Foreground    = Brushes.White,
                        TextWrapping  = TextWrapping.Wrap,
                        TextAlignment = TextAlignment.Center,
                        Width         = 76,
                        Height        = 24,
                        FontSize      = 18,
                        FontWeight    = FontWeights.Bold
                    };
                    Canvas.SetTop(Lrig_index, 36);
                    Canvas.SetLeft(Lrig_index, 40);
                    canvas.Children.Add(Lrig_index);

                    TextBlock Lrig_name = new TextBlock
                    {
                        Text          = name,
                        Background    = Colorfeed(cardcolor),
                        Foreground    = Brushes.Black,
                        TextWrapping  = TextWrapping.NoWrap,
                        TextAlignment = TextAlignment.Center,
                        Width         = 728,
                        Height        = 68,
                        FontSize      = (card["namesize"] != null) ? card["namesize"].ToObject <int>() : 50,
                        FontWeight    = FontWeights.Bold
                    };


                    Canvas.SetTop(Lrig_name, 68);
                    Canvas.SetLeft(Lrig_name, 136);
                    canvas.Children.Add(Lrig_name);

                    TextBlock Lrig_limit = new TextBlock
                    {
                        Text          = "리미트",
                        Background    = Brushes.Black,
                        Foreground    = Brushes.White,
                        TextWrapping  = TextWrapping.Wrap,
                        TextAlignment = TextAlignment.Center,
                        Width         = 76,
                        Height        = 24,
                        FontSize      = 18,
                        FontWeight    = FontWeights.Bold
                    };
                    Canvas.SetTop(Lrig_limit, 244);
                    Canvas.SetLeft(Lrig_limit, 40);
                    canvas.Children.Add(Lrig_limit);

                    TextBlock Lrig_type = new TextBlock
                    {
                        Text          = type,
                        Background    = Brushes.Black,
                        Foreground    = Brushes.White,
                        TextWrapping  = TextWrapping.Wrap,
                        TextAlignment = TextAlignment.Center,
                        Width         = typeboxsize(type),
                        Height        = 32,
                        FontSize      = 22,
                        FontWeight    = FontWeights.Bold,
                    };
                    Canvas.SetTop(Lrig_type, 928);
                    Canvas.SetRight(Lrig_type, 68);
                    canvas.Children.Add(Lrig_type);

                    if ((card["effect"] != null))
                    {
                        RichTextBox Lrig_text = new RichTextBox
                        {
                            Background = Colorfeed(cardcolor),
                            Foreground = Brushes.Black,
                            VerticalContentAlignment = VerticalAlignment.Top,
                            Width           = 816,
                            Height          = 244,
                            FontSize        = (card["textsize"] != null) ? card["textsize"].ToObject <int>() : 27,
                            Padding         = new Thickness(0, 5, 0, 5),
                            FontWeight      = FontWeights.DemiBold,
                            IsReadOnly      = true,
                            BorderThickness = new Thickness(0)
                        };

                        Paragraph paragraph = new Paragraph();

                        foreach (JArray line in card["effect"] as JArray)
                        {
                            foreach (var wordtoken in line)
                            {
                                String word = wordtoken.ToObject <String>();
                                wordadd(word, paragraph, (int)Lrig_text.FontSize);
                            }
                            if (line != card["effect"].Last)
                            {
                                paragraph.Inlines.Add("\n");
                            }
                        }
                        Lrig_text.Document.Blocks.Clear();
                        Lrig_text.Document.Blocks.Add(paragraph);

                        Canvas.SetTop(Lrig_text, 1000);
                        Canvas.SetLeft(Lrig_text, 92);
                        canvas.Children.Add(Lrig_text);
                    }

                    if ((card["coin"] != null))
                    {
                        int       coin      = card["coin"].ToObject <int>();
                        TextBlock Lrig_coin = new TextBlock
                        {
                            Text          = "코인",
                            Background    = Brushes.Black,
                            Foreground    = Brushes.White,
                            TextWrapping  = TextWrapping.Wrap,
                            TextAlignment = TextAlignment.Center,
                            Width         = 56,
                            Height        = 20,
                            FontSize      = 15,
                            FontWeight    = FontWeights.Bold,
                        };
                        Canvas.SetTop(Lrig_coin, 1220);
                        Canvas.SetLeft(Lrig_coin, 888);
                        canvas.Children.Add(Lrig_coin);
                    }

                    TextBlock Lrig_cost = new TextBlock
                    {
                        Text          = "그로우",
                        Background    = Brushes.Black,
                        Foreground    = Brushes.White,
                        TextWrapping  = TextWrapping.Wrap,
                        TextAlignment = TextAlignment.Center,
                        Width         = 68,
                        Height        = 20,
                        FontSize      = 15,
                        FontWeight    = FontWeights.Bold
                    };
                    Canvas.SetTop(Lrig_cost, 1240);
                    Canvas.SetLeft(Lrig_cost, 48);
                    canvas.Children.Add(Lrig_cost);
                }

                if (category == "아츠")
                {
                    JArray timings = card["timing"] as JArray;

                    TextBlock Arts_index = new TextBlock
                    {
                        Text          = "아츠",
                        Background    = Brushes.Black,
                        Foreground    = Brushes.White,
                        TextWrapping  = TextWrapping.Wrap,
                        TextAlignment = TextAlignment.Center,
                        Width         = 76,
                        Height        = 24,
                        FontSize      = 18,
                        FontWeight    = FontWeights.Bold
                    };
                    Canvas.SetTop(Arts_index, 36);
                    Canvas.SetLeft(Arts_index, 40);
                    canvas.Children.Add(Arts_index);

                    if ((card["craft"] != null))
                    {
                        TextBlock Arts_craft = new TextBlock
                        {
                            Text          = "크래프트",
                            Background    = Brushes.Black,
                            Foreground    = Brushes.White,
                            TextWrapping  = TextWrapping.Wrap,
                            TextAlignment = TextAlignment.Center,
                            Width         = 82,
                            Height        = 24,
                            FontSize      = 18,
                            FontWeight    = FontWeights.Bold
                        };
                        Canvas.SetTop(Arts_craft, 36);
                        Canvas.SetLeft(Arts_craft, 144);
                        canvas.Children.Add(Arts_craft);
                    }

                    TextBlock Arts_name = new TextBlock
                    {
                        Text          = name,
                        Background    = Colorfeed(cardcolor),
                        Foreground    = Brushes.Black,
                        TextWrapping  = TextWrapping.NoWrap,
                        TextAlignment = TextAlignment.Center,
                        Width         = 728,
                        Height        = 68,
                        FontSize      = (card["namesize"] != null) ? card["namesize"].ToObject <int>() : 50,
                        FontWeight    = FontWeights.Bold
                    };
                    Canvas.SetTop(Arts_name, 68);
                    Canvas.SetLeft(Arts_name, 136);
                    canvas.Children.Add(Arts_name);

                    for (int i = 0; i < timings.Count; i++)
                    {
                        TextBlock Arts_timing = new TextBlock
                        {
                            Text              = timings[i].ToObject <String>(),
                            Background        = Brushes.Black,
                            Foreground        = Brushes.White,
                            TextWrapping      = TextWrapping.Wrap,
                            TextAlignment     = TextAlignment.Center,
                            VerticalAlignment = VerticalAlignment.Bottom,
                            Width             = 136,
                            Height            = 32,
                            FontSize          = 22,
                            FontWeight        = FontWeights.Bold,
                        };
                        Canvas.SetBottom(Arts_timing, 436 + 44 * i);
                        Canvas.SetRight(Arts_timing, 68);
                        canvas.Children.Add(Arts_timing);
                    }

                    if ((card["limitation"] != null))
                    {
                        String    limitation      = card["limitation"].ToObject <String>();
                        TextBlock Arts_limitation = new TextBlock
                        {
                            Text          = limitation,
                            Background    = Brushes.Black,
                            Foreground    = Brushes.White,
                            TextWrapping  = TextWrapping.Wrap,
                            TextAlignment = TextAlignment.Center,
                            Width         = limitationboxsize(limitation),
                            Height        = 32,
                            FontSize      = 22,
                            FontWeight    = FontWeights.Bold,
                        };
                        Canvas.SetTop(Arts_limitation, 928);
                        Canvas.SetLeft(Arts_limitation, 68);
                        canvas.Children.Add(Arts_limitation);
                    }

                    RichTextBox Arts_text = new RichTextBox
                    {
                        Background = Colorfeed(cardcolor),
                        Foreground = Brushes.Black,
                        VerticalContentAlignment = VerticalAlignment.Top,
                        Width           = 816,
                        Height          = 270,
                        FontSize        = (card["textsize"] != null) ? card["textsize"].ToObject <int>() : 27,
                        Padding         = new Thickness(0, 5, 0, 5),
                        FontWeight      = FontWeights.DemiBold,
                        IsReadOnly      = true,
                        BorderThickness = new Thickness(0)
                    };

                    Paragraph paragraph = new Paragraph();

                    foreach (JArray line in card["effect"] as JArray)
                    {
                        foreach (var wordtoken in line)
                        {
                            String word = wordtoken.ToObject <String>();
                            wordadd(word, paragraph, (int)Arts_text.FontSize);
                        }
                        if (line != card["effect"].Last)
                        {
                            paragraph.Inlines.Add("\n");
                        }
                    }
                    Arts_text.Document.Blocks.Clear();
                    Arts_text.Document.Blocks.Add(paragraph);


                    Canvas.SetTop(Arts_text, 1000);
                    Canvas.SetLeft(Arts_text, 92);
                    canvas.Children.Add(Arts_text);
                }
                if (category == "키")
                {
                    TextBlock Key_name = new TextBlock
                    {
                        Text          = name,
                        Background    = Colorfeed(cardcolor),
                        Foreground    = Brushes.Black,
                        TextWrapping  = TextWrapping.NoWrap,
                        TextAlignment = TextAlignment.Center,
                        Width         = 768,
                        Height        = 68,
                        FontSize      = (card["namesize"] != null) ? card["namesize"].ToObject <int>() : 50,
                        FontWeight    = FontWeights.Bold
                    };
                    Canvas.SetTop(Key_name, 48);
                    Canvas.SetLeft(Key_name, 100);
                    canvas.Children.Add(Key_name);

                    TextBlock Key_index = new TextBlock
                    {
                        Text          = "키",
                        Background    = Brushes.Black,
                        Foreground    = Brushes.White,
                        TextWrapping  = TextWrapping.Wrap,
                        TextAlignment = TextAlignment.Center,
                        Width         = 68,
                        Height        = 24,
                        FontSize      = 18,
                        FontWeight    = FontWeights.Bold
                    };
                    Canvas.SetTop(Key_index, 36);
                    Canvas.SetLeft(Key_index, 40);
                    canvas.Children.Add(Key_index);

                    if ((card["limitation"] != null))
                    {
                        String    limitation     = card["limitation"].ToObject <String>();
                        TextBlock Key_limitation = new TextBlock
                        {
                            Text          = limitation,
                            Background    = Brushes.Black,
                            Foreground    = Brushes.White,
                            TextWrapping  = TextWrapping.Wrap,
                            TextAlignment = TextAlignment.Center,
                            Width         = limitationboxsize(limitation),
                            Height        = 32,
                            FontSize      = 22,
                            FontWeight    = FontWeights.Bold,
                        };
                        Canvas.SetTop(Key_limitation, 644);
                        Canvas.SetLeft(Key_limitation, 68);
                        canvas.Children.Add(Key_limitation);
                    }

                    RichTextBox Key_text = new RichTextBox
                    {
                        Background = Colorfeed(cardcolor),
                        Foreground = Brushes.Black,
                        VerticalContentAlignment = VerticalAlignment.Top,
                        Width           = 1184,
                        FontSize        = (card["textsize"] != null) ? card["textsize"].ToObject <int>() : 27,
                        Padding         = new Thickness(0, 5, 0, 5),
                        FontWeight      = FontWeights.DemiBold,
                        IsReadOnly      = true,
                        BorderThickness = new Thickness(0)
                    };

                    Paragraph paragraph = new Paragraph();

                    foreach (JArray line in card["effect"] as JArray)
                    {
                        foreach (var wordtoken in line)
                        {
                            String word = wordtoken.ToObject <String>();
                            wordadd(word, paragraph, (int)Key_text.FontSize);
                        }
                        if (line != card["effect"].Last)
                        {
                            paragraph.Inlines.Add("\n");
                        }
                    }


                    Key_text.Document.Blocks.Clear();
                    Key_text.Document.Blocks.Add(paragraph);


                    Canvas.SetBottom(Key_text, 128);
                    Canvas.SetLeft(Key_text, 112);
                    canvas.Children.Add(Key_text);
                }

                if (category == "시그니")
                {
                    String signiclass = card["class"].ToObject <String>();

                    TextBlock Signi_index = new TextBlock
                    {
                        Text          = "시그니",
                        Background    = Brushes.Black,
                        Foreground    = Brushes.White,
                        TextWrapping  = TextWrapping.Wrap,
                        TextAlignment = TextAlignment.Center,
                        Width         = 76,
                        Height        = 24,
                        FontSize      = 18,
                        FontWeight    = FontWeights.Bold
                    };
                    Canvas.SetTop(Signi_index, 36);
                    Canvas.SetLeft(Signi_index, 40);
                    canvas.Children.Add(Signi_index);

                    TextBlock Signi_name = new TextBlock
                    {
                        Text          = name,
                        Background    = Colorfeed(cardcolor),
                        Foreground    = Brushes.Black,
                        TextWrapping  = TextWrapping.NoWrap,
                        TextAlignment = TextAlignment.Center,
                        Width         = 728,
                        Height        = 68,
                        FontSize      = (card["namesize"] != null) ? card["namesize"].ToObject <int>() : 50,
                        FontWeight    = FontWeights.Bold
                    };
                    Canvas.SetTop(Signi_name, 68);
                    Canvas.SetLeft(Signi_name, 136);
                    canvas.Children.Add(Signi_name);

                    TextBlock Signi_class = new TextBlock
                    {
                        Text          = signiclass,
                        Background    = Brushes.Black,
                        Foreground    = Brushes.White,
                        TextWrapping  = TextWrapping.Wrap,
                        TextAlignment = TextAlignment.Center,
                        Width         = classboxsize(signiclass),
                        Height        = 32,
                        FontSize      = 22,
                        FontWeight    = FontWeights.Bold,
                    };
                    Canvas.SetTop(Signi_class, 928);
                    Canvas.SetRight(Signi_class, 68);
                    canvas.Children.Add(Signi_class);

                    if ((card["limitation"] != null))
                    {
                        String    limitation       = card["limitation"].ToObject <String>();
                        TextBlock Signi_limitation = new TextBlock
                        {
                            Text          = limitation,
                            Background    = Brushes.Black,
                            Foreground    = Brushes.White,
                            TextWrapping  = TextWrapping.Wrap,
                            TextAlignment = TextAlignment.Center,
                            Width         = limitationboxsize(limitation),
                            Height        = 32,
                            FontSize      = 22,
                            FontWeight    = FontWeights.Bold,
                        };
                        Canvas.SetTop(Signi_limitation, 928);
                        Canvas.SetLeft(Signi_limitation, 68);
                        canvas.Children.Add(Signi_limitation);
                    }
                    if ((card["effect"] != null))
                    {
                        RichTextBox Signi_text = new RichTextBox
                        {
                            Background = Colorfeed(cardcolor),
                            Foreground = Brushes.Black,
                            VerticalContentAlignment = VerticalAlignment.Top,
                            Width           = 816,
                            Height          = 244,
                            FontSize        = (card["textsize"] != null) ? card["textsize"].ToObject <int>() : 27,
                            Padding         = new Thickness(0, 5, 0, 5),
                            FontWeight      = FontWeights.DemiBold,
                            IsReadOnly      = true,
                            BorderThickness = new Thickness(0)
                        };

                        Paragraph paragraph = new Paragraph();

                        foreach (JArray line in card["effect"] as JArray)
                        {
                            foreach (var wordtoken in line)
                            {
                                String word = wordtoken.ToObject <String>();
                                wordadd(word, paragraph, (int)Signi_text.FontSize);
                            }
                            if (line != card["effect"].Last)
                            {
                                paragraph.Inlines.Add("\n");
                            }
                        }
                        Signi_text.Document.Blocks.Clear();
                        Signi_text.Document.Blocks.Add(paragraph);


                        Canvas.SetTop(Signi_text, 1000);
                        Canvas.SetLeft(Signi_text, 92);
                        canvas.Children.Add(Signi_text);
                    }

                    if ((card["lifeburst"] != null))
                    {
                        RichTextBox Signi_lifeburst = new RichTextBox
                        {
                            Background = Brushes.Black,
                            Foreground = Brushes.White,
                            VerticalContentAlignment = VerticalAlignment.Bottom,
                            Width           = 816,
                            FontSize        = (card["textsize"] != null) ? card["textsize"].ToObject <int>() : 27,
                            Padding         = new Thickness(0, 5, 0, 5),
                            FontWeight      = FontWeights.DemiBold,
                            IsReadOnly      = true,
                            BorderThickness = new Thickness(0)
                        };

                        Paragraph burstparagraph = new Paragraph();

                        foreach (JArray line in card["lifeburst"] as JArray)
                        {
                            foreach (var wordtoken in line)
                            {
                                String word = wordtoken.ToObject <String>();
                                wordadd(word, burstparagraph, (int)Signi_lifeburst.FontSize);
                            }
                            if (line != card["lifeburst"].Last)
                            {
                                burstparagraph.Inlines.Add("\n");
                            }
                        }
                        Signi_lifeburst.Document.Blocks.Clear();
                        Signi_lifeburst.Document.Blocks.Add(burstparagraph);


                        Canvas.SetBottom(Signi_lifeburst, 150);
                        Canvas.SetLeft(Signi_lifeburst, 92);
                        canvas.Children.Add(Signi_lifeburst);
                    }
                }

                if (category == "스펠")
                {
                    TextBlock Spell_index = new TextBlock
                    {
                        Text          = "스펠",
                        Background    = Brushes.Black,
                        Foreground    = Brushes.White,
                        TextWrapping  = TextWrapping.Wrap,
                        TextAlignment = TextAlignment.Center,
                        Width         = 76,
                        Height        = 24,
                        FontSize      = 18,
                        FontWeight    = FontWeights.Bold
                    };
                    Canvas.SetTop(Spell_index, 36);
                    Canvas.SetLeft(Spell_index, 40);
                    canvas.Children.Add(Spell_index);

                    TextBlock Spell_name = new TextBlock
                    {
                        Text          = name,
                        Background    = Colorfeed(cardcolor),
                        Foreground    = Brushes.Black,
                        TextWrapping  = TextWrapping.NoWrap,
                        TextAlignment = TextAlignment.Center,
                        Width         = 728,
                        Height        = 68,
                        FontSize      = (card["namesize"] != null) ? card["namesize"].ToObject <int>() : 50,
                        FontWeight    = FontWeights.Bold
                    };
                    Canvas.SetTop(Spell_name, 68);
                    Canvas.SetLeft(Spell_name, 136);
                    canvas.Children.Add(Spell_name);

                    if ((card["limitation"] != null))
                    {
                        String    limitation       = card["limitation"].ToObject <String>();
                        TextBlock Spell_limitation = new TextBlock
                        {
                            Text          = limitation,
                            Background    = Brushes.Black,
                            Foreground    = Brushes.White,
                            TextWrapping  = TextWrapping.Wrap,
                            TextAlignment = TextAlignment.Center,
                            Width         = limitationboxsize(limitation),
                            Height        = 32,
                            FontSize      = 22,
                            FontWeight    = FontWeights.Bold,
                        };
                        Canvas.SetTop(Spell_limitation, 928);
                        Canvas.SetLeft(Spell_limitation, 68);
                        canvas.Children.Add(Spell_limitation);
                    }

                    RichTextBox Spell_text = new RichTextBox
                    {
                        Background = Colorfeed(cardcolor),
                        Foreground = Brushes.Black,
                        VerticalContentAlignment = VerticalAlignment.Top,
                        Width           = 816,
                        Height          = 244,
                        FontSize        = (card["textsize"] != null) ? card["textsize"].ToObject <int>() : 27,
                        Padding         = new Thickness(0, 5, 0, 5),
                        FontWeight      = FontWeights.DemiBold,
                        IsReadOnly      = true,
                        BorderThickness = new Thickness(0)
                    };

                    Paragraph paragraph = new Paragraph();

                    foreach (JArray line in card["effect"] as JArray)
                    {
                        foreach (var wordtoken in line)
                        {
                            String word = wordtoken.ToObject <String>();
                            wordadd(word, paragraph, (int)Spell_text.FontSize);
                        }
                        if (line != card["effect"].Last)
                        {
                            paragraph.Inlines.Add("\n");
                        }
                    }
                    Spell_text.Document.Blocks.Clear();
                    Spell_text.Document.Blocks.Add(paragraph);


                    Canvas.SetTop(Spell_text, 1000);
                    Canvas.SetLeft(Spell_text, 92);
                    canvas.Children.Add(Spell_text);

                    if ((card["lifeburst"] != null))
                    {
                        RichTextBox Spell_lifeburst = new RichTextBox
                        {
                            Background = Brushes.Black,
                            Foreground = Brushes.White,
                            VerticalContentAlignment = VerticalAlignment.Bottom,
                            Width           = 816,
                            FontSize        = (card["textsize"] != null) ? card["textsize"].ToObject <int>() : 27,
                            Padding         = new Thickness(0, 5, 0, 7),
                            FontWeight      = FontWeights.DemiBold,
                            IsReadOnly      = true,
                            BorderThickness = new Thickness(0)
                        };

                        Paragraph burstparagraph = new Paragraph();

                        foreach (JArray line in card["lifeburst"] as JArray)
                        {
                            foreach (var wordtoken in line)
                            {
                                String word = wordtoken.ToObject <String>();
                                wordadd(word, burstparagraph, (int)Spell_lifeburst.FontSize);
                            }
                            if (line != card["lifeburst"].Last)
                            {
                                paragraph.Inlines.Add("\n");
                            }
                        }
                        Spell_lifeburst.Document.Blocks.Clear();
                        Spell_lifeburst.Document.Blocks.Add(burstparagraph);


                        Canvas.SetBottom(Spell_lifeburst, 150);
                        Canvas.SetLeft(Spell_lifeburst, 92);
                        canvas.Children.Add(Spell_lifeburst);
                    }
                }



                this.Content = canvas;
                canvas.Measure(new Size(width, height));
                canvas.Arrange(new Rect(0, 0, width, height));

                Rect               rect = new Rect(0, 0, canvas.Width, canvas.Height);
                double             dpi  = 96d;
                RenderTargetBitmap rtb  = new RenderTargetBitmap((int)rect.Right, (int)rect.Bottom, dpi, dpi, System.Windows.Media.PixelFormats.Default);
                rtb.Render(canvas);

                BitmapEncoder pngEncoder = new PngBitmapEncoder();

                WebClient            wc    = new WebClient();
                byte[]               bytes = wc.DownloadData(imgurl);
                MemoryStream         mss   = new MemoryStream(bytes);
                System.Drawing.Image imgg  = System.Drawing.Image.FromStream(mss);


                DrawingVisual dv = new DrawingVisual();
                using (DrawingContext dc = dv.RenderOpen())
                {
                    dc.DrawImage(ToWpfBitmapImage(imgg), rect);
                    dc.DrawImage(rtb, rect);
                }
                RenderTargetBitmap res = new RenderTargetBitmap((int)rect.Right, (int)rect.Bottom, dpi, dpi, PixelFormats.Pbgra32);
                res.Render(dv);

                pngEncoder.Frames.Add(BitmapFrame.Create(res));

                try
                {
                    System.IO.MemoryStream ms = new System.IO.MemoryStream();

                    pngEncoder.Save(ms);
                    ms.Close();

                    System.IO.File.WriteAllBytes(@"..\..\Processed\" + packindex + @"\" + card["no"].ToObject <String>() + ".png", ms.ToArray());
                }
                catch (Exception err)
                {
                    MessageBox.Show(err.ToString(), "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }
Exemple #13
0
 protected override void OnRender(DrawingContext drawingContext)
 {
     drawingContext.DrawImage(this.Bitmap, new Rect(this.RenderSize));
 }
Exemple #14
0
        protected void DrawHsvDial(DrawingContext drawingContext)
        {
            float cx = (float)this.ActualWidth / 2.0f;
            float cy = (float)this.ActualHeight / 2.0f;

            float outer_radius = (float)Math.Min(cx, cy);

            ActualOuterRadius = outer_radius;

            //double outer_circumference = 2.0 * Math.PI * outer_radius;

            int bmp_width  = (int)this.ActualWidth;
            int bmp_height = (int)this.ActualHeight;

            if (bmp_width <= 0 || bmp_height <= 0)
            {
                return;
            }

            bitmap = new WriteableBitmap(bmp_width, bmp_height, 96.0, 96.0, PixelFormats.Bgra32, null);

            bitmap.Lock();
            unsafe
            {
                int pBackBuffer = (int)bitmap.BackBuffer;

                for (int y = 0; y < bmp_height; y++)
                {
                    for (int x = 0; x < bmp_width; x++)
                    {
                        int color_data = 0;
                        //double inner_radius = radius * InnerRadius;

                        // Convert xy to normalized polar co-ordinates
                        double dx = x - cx;
                        double dy = y - cy;
                        double pr = Math.Sqrt(dx * dx + dy * dy);

                        // Only draw stuff within the circle
                        if (pr <= outer_radius)
                        {
                            // Compute the colour for the given pixel using polar co-ordinates
                            double    pa = Math.Atan2(dx, dy);
                            RGBStruct c  = ColourFunction(pr / outer_radius, ((pa + Math.PI) * 180.0 / Math.PI));

                            // Anti-aliasing
                            // This works by adjusting the alpha to the alias error between the outer radius (which is integer)
                            // and the computed radius, pr (which is float).
                            double aadelta = pr - (outer_radius - 1.0);
                            if (aadelta >= 0.0)
                            {
                                c.a = (byte)(255 - aadelta * 255);
                            }

                            color_data = c.ToARGB32();
                        }

                        *((int *)pBackBuffer) = color_data;
                        pBackBuffer          += 4;
                    }
                }
            }
            bitmap.AddDirtyRect(new Int32Rect(0, 0, bmp_width, bmp_height)); // I like to get dirty
            bitmap.Unlock();


            drawingContext.DrawImage(bitmap, new Rect(this.RenderSize));
        }
        private async void searchImage_Click(object sender, RoutedEventArgs e)
        {
            double resizeX;
            double resizeY;

            Title = "Authenticating..";

            // Get the image file to scan from the user.
            var openDlg = new Microsoft.Win32.OpenFileDialog();

            openDlg.Filter = "JPEG Image(*.jpg)|*.jpg";
            bool?result = openDlg.ShowDialog(this);

            // Return if canceled.
            if (!(bool)result)
            {
                return;
            }

            // Display the image file.
            string testImageFile = openDlg.FileName;

            txtLoginImage.Text = testImageFile;

            Uri         fileUri      = new Uri(testImageFile);
            BitmapImage bitmapSource = new BitmapImage();

            bitmapSource.BeginInit();
            bitmapSource.CacheOption = BitmapCacheOption.None;
            bitmapSource.UriSource   = fileUri;
            bitmapSource.EndInit();

            displayImage.Source = bitmapSource;

            Face[] faces = await UploadAndDetectFaces(testImageFile);

            //Draw Box on Face?
            // Prepare to draw rectangles around the faces.
            DrawingVisual  visual         = new DrawingVisual();
            DrawingContext drawingContext = visual.RenderOpen();

            drawingContext.DrawImage(bitmapSource,
                                     new Rect(0, 0, bitmapSource.Width, bitmapSource.Height));

            resizeX = 96.0 / bitmapSource.DpiX;
            resizeY = 96.0 / bitmapSource.DpiY;

            for (int i = 0; i < faces.Length; ++i)
            {
                Face face   = faces[i];
                var  person = new Person();

                // Draw a rectangle on the face.
                drawingContext.DrawRectangle(
                    Brushes.Transparent,
                    new Pen(Brushes.Red, 2 * (96 / bitmapSource.DpiX)),
                    new Rect(
                        face.FaceRectangle.Left * resizeX,
                        face.FaceRectangle.Top * resizeY,
                        face.FaceRectangle.Width * resizeX,
                        face.FaceRectangle.Height * resizeY
                        )
                    );
            }

            drawingContext.Close();

            // Display the image with the rectangle around the face.
            RenderTargetBitmap faceWithRectBitmap = new RenderTargetBitmap(
                (int)((bitmapSource.PixelWidth / 96d) * bitmapSource.DpiX * resizeX),
                (int)((bitmapSource.PixelHeight / 96d) * bitmapSource.DpiY * resizeY),
                bitmapSource.DpiX,
                bitmapSource.DpiY,
                PixelFormats.Pbgra32);

            faceWithRectBitmap.Render(visual);
            displayImage.Source = faceWithRectBitmap;

            //Only one face can be tested against the API
            VerifyResult autheticated = null;

            if (faces.Count() == 1)
            {
                autheticated = await verifyUser(txtUserName.Text, faces[0]);
            }

            if (autheticated != null)
            {
                if (autheticated.IsIdentical)
                {
                    Title = "Is Authenticated";
                    MessageBox.Show("User is Verified");
                }
            }
        }
Exemple #16
0
        /// <summary>
        /// Handle the processing when Kinect frame arrived
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MultiSourceFrameReader_MultiSourceFrameArrived(object sender, MultiSourceFrameArrivedEventArgs e)
        {
            if (isDownApplication)
            {
                Application.Current.Shutdown();
            }

            MultiSourceFrame multiSourceFrame = e.FrameReference.AcquireFrame();

            if (multiSourceFrame != null)
            {
                using (DepthFrame depthFrame = multiSourceFrame.DepthFrameReference.AcquireFrame())
                {
                    using (BodyFrame bodyFrame = multiSourceFrame.BodyFrameReference.AcquireFrame())
                    {
                        using (DrawingContext drawingContext = drawingGroup.Open())
                        {
                            if (depthFrame != null && bodyFrame != null)
                            {
                                // Refresh the foreground of 2D top view for positioning
                                Plot.RefreshForegroundCanvas(Canvas_Position_Foreground, activities);

                                // Find templates
                                if (isFindingTemplate)
                                {
                                    ushort[] depthFrameData = new ushort[depthFrame.FrameDescription.Height * depthFrame.FrameDescription.Width];
                                    depthFrame.CopyFrameDataToArray(depthFrameData);

                                    cameraSpacePoints = new CameraSpacePoint[depthFrame.FrameDescription.Height * depthFrame.FrameDescription.Width];
                                    kinectSensor.CoordinateMapper.MapDepthFrameToCameraSpace(depthFrameData, cameraSpacePoints);

                                    TemplateDetector.heightLow          = -2.4f;
                                    TemplateDetector.heightHigh         = -1.9f;
                                    TemplateDetector.canvas_width       = Canvas_Position_Background.Width;
                                    TemplateDetector.canvas_height      = Canvas_Position_Background.Height;
                                    TemplateDetector.canvas_environment = Canvas_Position_Environment;

                                    // AsyncTask
                                    BackgroundWorker worker = new BackgroundWorker();
                                    worker.WorkerReportsProgress = true;
                                    worker.DoWork             += TemplateDetector.DoInBackgrond;
                                    worker.ProgressChanged    += TemplateDetector.OnProgress;
                                    worker.RunWorkerCompleted += TemplateDetector.OnPostExecute;
                                    worker.RunWorkerAsync();

                                    isFindingTemplate = false;
                                }

                                // Display depth frame
                                // Uncomment to enable the display for height segmentation result
                                //if (!isHeightSegmented)
                                if (true)
                                {
                                    drawingContext.DrawImage(Transformation.ToBitmap(depthFrame, depthFramePixels, true),
                                                             new Rect(0.0, 0.0, kinectSensor.DepthFrameSource.FrameDescription.Width, kinectSensor.DepthFrameSource.FrameDescription.Height));
                                }
                                else
                                {
                                    drawingContext.DrawImage(Transformation.ToBitmap(depthFrame, segmentedDepthFramePixels, false),
                                                             new Rect(0.0, 0.0, kinectSensor.DepthFrameSource.FrameDescription.Width, kinectSensor.DepthFrameSource.FrameDescription.Height));
                                }

                                // Display top view in height
                                if (TemplateDetector.isDrawDone)
                                {
                                    using (DrawingContext drawingContext_heightview = drawingGroup_topView.Open())
                                    {
                                        drawingContext_heightview.DrawImage(Transformation.ToBitmap(TemplateDetector.area_width, TemplateDetector.area_height, TemplateDetector.pixels),
                                                                            new Rect(0.0, 0.0, TemplateDetector.area_width, TemplateDetector.area_height));

                                        foreach (Template t in TemplateDetector.templates)
                                        {
                                            drawingContext_heightview.DrawRectangle(null, new Pen(t.Brush, 2),
                                                                                    new Rect(new Point(t.TopLeft.X, t.TopLeft.Y), new Size(t.Width, t.Height)));
                                        }
                                    }

                                    TemplateDetector.isDrawDone = false;
                                }

                                // Load raw body joints info from Kinect
                                bodyFrame.GetAndRefreshBodyData(bodies);

                                // Update personal infomation from raw joints
                                for (int i = 0; i < kinectSensor.BodyFrameSource.BodyCount; ++i)
                                {
                                    if (persons[i] == null)
                                    {
                                        persons[i] = new Person();
                                    }

                                    ulong trackingId = bodies[i].TrackingId;
                                    if (trackingId != gestureDetectorList[i].TrackingId)
                                    {
                                        gestureDetectorList[i].TrackingId = trackingId;
                                        gestureDetectorList[i].IsPaused   = trackingId == 0;
                                    }

                                    if (bodies[i].IsTracked)
                                    {
                                        // Update tracking status
                                        persons[i].IsTracked = true;

                                        persons[i].ID = bodies[i].TrackingId;

                                        // Assign color to person in the top view for positioning
                                        persons[i].Color = Plot.BodyColors[i];

                                        // Get person's 3D postion in camera's coordinate system
                                        CameraSpacePoint headPositionCamera = bodies[i].Joints[JointType.Head].Position; // Meter

                                        // Convert to 3D position in horizontal coordinate system
                                        CameraSpacePoint headPositionGournd = Transformation.RotateBackFromTilt(TILT_ANGLE, true, headPositionCamera);

                                        // Convert to 2D top view position on canvas
                                        Transformation.ConvertGroundSpaceToPlane(headPositionGournd, persons[i]);

                                        // Determine body orientation using shoulder joints
                                        CameraSpacePoint leftShoulderPositionGround  = Transformation.RotateBackFromTilt(TILT_ANGLE, true, bodies[i].Joints[JointType.ShoulderLeft].Position);
                                        CameraSpacePoint rightShoulderPositionGround = Transformation.RotateBackFromTilt(TILT_ANGLE, true, bodies[i].Joints[JointType.ShoulderRight].Position);
                                        BodyOrientation.DecideOrientation(leftShoulderPositionGround, rightShoulderPositionGround, persons[i],
                                                                          Transformation.CountZeroInRec(depthFramePixels, kinectSensor.CoordinateMapper.MapCameraPointToDepthSpace(headPositionCamera),
                                                                                                        16, kinectSensor.DepthFrameSource.FrameDescription.Width), Canvas_Position_Foreground);
                                    }
                                    else
                                    {
                                        persons[i].IsTracked = false;
                                    }
                                }

                                DrawPeopleOnDepth(drawingContext);
                                DrawPeopleOnCanvas();
                                DetermineSystemStatus();
                                DrawSystemStatus();

                                // Recognize and record activities when recording requirements are satisfied
                                if (isRecording)
                                {
                                    CheckActivity();
                                    DrawActivityOnCanvas();
                                    Record();
                                }
                            }
                        }
                    }
                }
            }
        }
 protected void Image(ImageSource img, double x, double y, double w, double h)
 {
     context.DrawImage(img, new System.Windows.Rect(x, y, w, h));
 }
Exemple #18
0
        private void Reader_FrameArrived(object sender, BodyFrameArrivedEventArgs e)
        {
            bool dataReceived = false;

            using (BodyFrame bodyFrame = e.FrameReference.AcquireFrame())
            {
                if (bodyFrame != null)
                {
                    if (this.bodies == null)
                    {
                        this.bodies = new Body[bodyFrame.BodyCount];
                    }

                    // The first time GetAndRefreshBodyData is called, Kinect will allocate each Body in the array.
                    // As long as those body objects are not disposed and not set to null in the array,
                    // those body objects will be re-used.
                    bodyFrame.GetAndRefreshBodyData(this.bodies);
                    dataReceived = true;
                }
            }

            if (dataReceived)
            {
                using (DrawingContext dc = this.drawingGroup.Open())
                {
                    dc.DrawImage(this.colorBitmap, new Rect(0.0, 0.0, this.displayWidth, this.displayHeight));


                    int penIndex = 0;
                    foreach (Body body in this.bodies)
                    {
                        Pen drawPen = this.bodyColors[penIndex++];

                        if (body.IsTracked)
                        {
                            this.DrawClippedEdges(body, dc);

                            IReadOnlyDictionary <JointType, Joint> joints = body.Joints;

                            // convert the joint points to depth (display) space --> convert 필요없음!
                            Dictionary <JointType, Point> jointPoints = new Dictionary <JointType, Point>();

                            //joing point 가져오는 부분*********************
                            foreach (JointType jointType in joints.Keys)
                            {
                                CameraSpacePoint position = joints[jointType].Position;

                                ColorSpacePoint colorSpacePoint = this.coordinateMapper.MapCameraPointToColorSpace(position);

                                jointPoints[jointType] = new Point(colorSpacePoint.X, colorSpacePoint.Y);
                            }

                            //skeleton 그리기******************************
                            this.DrawBody(joints, jointPoints, dc, drawPen);

                            this.DrawHand(body.HandLeftState, jointPoints[JointType.HandLeft], dc);
                            this.DrawHand(body.HandRightState, jointPoints[JointType.HandRight], dc);
                        }
                    }

                    // prevent drawing outside of our render area
                    this.drawingGroup.ClipGeometry = new RectangleGeometry(new Rect(0.0, 0.0, this.displayWidth, this.displayHeight));
                }
            }
        }
Exemple #19
0
        private async Task UpdateImageWithWatermark()
        {
            bool   watermarkEnabled = (bool)bWatermarkIcon.IsChecked;
            string rarityDesign     = ((ComboBoxItem)ComboBox_Design.SelectedItem).Content.ToString();
            bool   isFeatured       = (bool)bFeaturedIcon.IsChecked;
            int    opacity          = Convert.ToInt32(Opacity_Slider.Value);
            double scale            = Scale_Slider.Value;
            double xPos             = xPos_Slider.Value;
            double yPos             = yPos_Slider.Value;

            await Task.Run(() =>
            {
                DrawingVisual drawingVisual = new DrawingVisual();
                using (DrawingContext drawingContext = drawingVisual.RenderOpen())
                {
                    //INITIALIZATION
                    drawingContext.DrawRectangle(Brushes.Transparent, null, new Rect(new Point(0, 0), new Size(515, 515)));

                    BitmapImage source = null;
                    switch (rarityDesign)
                    {
                    case "Default":
                        source = new BitmapImage(new Uri(isFeatured ? RARITY_DEFAULT_FEATURED : RARITY_DEFAULT_NORMAL));
                        break;

                    case "Flat":
                        source = new BitmapImage(new Uri(isFeatured ? RARITY_FLAT_FEATURED : RARITY_FLAT_NORMAL));
                        break;

                    case "Minimalist":
                        source = new BitmapImage(new Uri(isFeatured ? RARITY_MINIMALIST_FEATURED : RARITY_MINIMALIST_NORMAL));
                        break;

                    case "Accurate Colors":
                        source = new BitmapImage(new Uri(isFeatured ? RARITY_ACCURATECOLORS_FEATURED : RARITY_ACCURATECOLORS_NORMAL));
                        break;
                    }
                    drawingContext.DrawImage(source, new Rect(new Point(0, 0), new Size(515, 515)));

                    if (!string.IsNullOrEmpty(FProp.Default.FWatermarkFilePath) && watermarkEnabled)
                    {
                        using (StreamReader image = new StreamReader(FProp.Default.FWatermarkFilePath))
                        {
                            BitmapImage bmp = new BitmapImage();
                            bmp.BeginInit();
                            bmp.CacheOption  = BitmapCacheOption.OnLoad;
                            bmp.StreamSource = image.BaseStream;
                            bmp.EndInit();

                            drawingContext.DrawImage(ImagesUtility.CreateTransparency(bmp, opacity), new Rect(xPos, yPos, bmp.Width * (scale / 515), bmp.Height * (scale / 515)));
                        }
                    }
                }

                RenderTargetBitmap RTB = new RenderTargetBitmap(515, 515, 96, 96, PixelFormats.Pbgra32);
                RTB.Render(drawingVisual);
                RTB.Freeze(); //We freeze to apply the RTB to our imagesource from the UI Thread

                FWindow.FMain.Dispatcher.InvokeAsync(() =>
                {
                    ImageBox_RarityPreview.Source = BitmapFrame.Create(RTB); //thread safe and fast af
                });
            }).ContinueWith(TheTask =>
            {
                TasksUtility.TaskCompleted(TheTask.Exception);
            });
        }
        private void RenderPages(DrawingContext drawingContext)
        {
            // Draw background
            drawingContext.DrawRectangle(Background, null, new Rect(0, 0, ViewportWidth, ViewportHeight));

            var pageOnCenter = _renderedPages.FirstOrDefault(page => page.IsOnCenter);

            // Determine pages to draw.
            _renderedPages.Clear();
            _renderedPages.AddRange(PDFPageComponent[PageLayoutType.Thumbnail].DeterminePagesToRender(
                                        VerticalOffset,
                                        VerticalOffset + ViewportHeight,
                                        2d * FontSize,
                                        _thumbnailZoomFactor));

            // Determine viewport rectangle
            var viewportRectangle = new Rect(0, 0, _viewport.Width, _viewport.Height);

            // Iterate the pages, adjust some values, and draw them.
            foreach (var pageInfo in _renderedPages)
            {
                // Current page width
                var currentPageWidth = pageInfo.Page.ThumbnailWidth * _thumbnailZoomFactor;

                // Center the page horizontally
                pageInfo.Left  = (ViewportWidth / 2d) - (currentPageWidth / 2d);
                pageInfo.Right = (ViewportWidth / 2d) + (currentPageWidth / 2d);

                // Take offsets into account
                pageInfo.Left   -= HorizontalOffset;
                pageInfo.Right  -= HorizontalOffset;
                pageInfo.Top    -= VerticalOffset;
                pageInfo.Bottom -= VerticalOffset;

                var pageRect = new Rect(pageInfo.Left, pageInfo.Top, Math.Max(1d, pageInfo.Right - pageInfo.Left), Math.Max(0d, pageInfo.Bottom - pageInfo.Top));

                ////////var pageOnViewport = pageRect;
                ////////pageOnViewport.Intersect(viewportRectangle);
                ////////if (pageOnViewport.IsEmpty)
                ////////{
                ////////    continue;
                ////////}

                ////////pageOnViewport.Width = Math.Max(1d, pageOnViewport.Width);
                ////////pageOnViewport.Height = Math.Max(1d, pageOnViewport.Height);

                var pageRectForPDFium = pageRect;
                pageRectForPDFium.Y      = pageRect.Y > 0d ? 0d : pageRect.Y;
                pageRectForPDFium.X      = pageRect.X > 0d ? 0d : pageRect.X;
                pageRectForPDFium.Width  = Math.Max(1d, pageRectForPDFium.Width);
                pageRectForPDFium.Height = Math.Max(1d, pageRectForPDFium.Height);

                // Draw page background
                drawingContext.DrawRectangle(PDFPageBackground, null, new Rect(pageRect.TopLeft, pageRect.BottomRight));

                try
                {
                    var bitmap = new WriteableBitmap((int)pageInfo.Page.ThumbnailWidth, (int)pageInfo.Page.ThumbnailHeight, 96, 96, PixelFormats.Bgra32, null);
                    var format = BitmapFormatConverter.GetFormat(bitmap.Format);

                    bitmap.Lock();
                    pageInfo.Page.RenderThumbnailBitmap(format, bitmap.BackBuffer, bitmap.BackBufferStride);
                    bitmap.AddDirtyRect(new Int32Rect(0, 0, (int)pageRect.Width, (int)pageRect.Height));
                    bitmap.Unlock();

                    // Draw page content.
                    drawingContext.DrawImage(bitmap, new Rect(pageRect.TopLeft, pageRect.BottomRight));
                }
#pragma warning disable CA1031 // Do not catch general exception types
                catch
                {
                }
#pragma warning restore CA1031 // Do not catch general exception types

                // Draw page label
                var ft = new FormattedText(
                    pageInfo.Page.PageLabel,
                    CultureInfo.InvariantCulture,
                    FlowDirection.LeftToRight,
                    new Typeface(FontFamily, FontStyle, FontWeight, FontStretch),
                    FontSize,
                    Foreground,
                    VisualTreeHelper.GetDpi(this).PixelsPerDip);
                var textLocation = new Point(pageInfo.Left + ((pageInfo.Right - pageInfo.Left) / 2d) - (ft.WidthIncludingTrailingWhitespace / 2), pageInfo.Bottom);
                drawingContext.DrawText(ft, textLocation);

                // Draw page border - left
                drawingContext.DrawLine(new Pen(PDFPageBorderBrush, PDFPageBorderThickness.Left), new Point(pageInfo.Left, pageInfo.Top), new Point(pageInfo.Left, pageInfo.Bottom));

                // Draw page border - top
                drawingContext.DrawLine(new Pen(PDFPageBorderBrush, PDFPageBorderThickness.Top), new Point(pageInfo.Left, pageInfo.Top), new Point(pageInfo.Right, pageInfo.Top));

                // Draw page border - right
                drawingContext.DrawLine(new Pen(PDFPageBorderBrush, PDFPageBorderThickness.Right), new Point(pageInfo.Right, pageInfo.Top), new Point(pageInfo.Right, pageInfo.Bottom));

                // Draw page border - bottom
                drawingContext.DrawLine(new Pen(PDFPageBorderBrush, PDFPageBorderThickness.Bottom), new Point(pageInfo.Left, pageInfo.Bottom), new Point(pageInfo.Right, pageInfo.Bottom));
            }

            // Draw background border - left
            drawingContext.DrawLine(new Pen(BorderBrush, BorderThickness.Left), new Point(0, 0), new Point(0, ViewportHeight));

            // Draw background border - top
            drawingContext.DrawLine(new Pen(BorderBrush, BorderThickness.Top), new Point(0, 0), new Point(ViewportWidth, 0));

            // Draw background border - right
            drawingContext.DrawLine(new Pen(BorderBrush, BorderThickness.Right), new Point(ViewportWidth, 0), new Point(ViewportWidth, ViewportHeight));

            // Draw background border - bottom
            drawingContext.DrawLine(new Pen(BorderBrush, BorderThickness.Bottom), new Point(0, ViewportHeight), new Point(ViewportWidth, ViewportHeight));
        }
Exemple #21
0
        private void UpdateChallengeCustomTheme()
        {
            bool   watermarkEnabled = (bool)bCustomChallenge.IsChecked;
            string watermark        = WatermarkChallenge_TextBox.Text;
            string path             = FProp.Default.FBannerFilePath;
            int    opacity          = Convert.ToInt32(OpacityBanner_Slider.Value);

            string[]        primaryParts   = FProp.Default.FPrimaryColor.Split(':');
            string[]        secondaryParts = FProp.Default.FSecondaryColor.Split(':');
            SolidColorBrush PrimaryColor   = new SolidColorBrush(Color.FromRgb(Convert.ToByte(primaryParts[0]), Convert.ToByte(primaryParts[1]), Convert.ToByte(primaryParts[2])));
            SolidColorBrush SecondaryColor = new SolidColorBrush(Color.FromRgb(Convert.ToByte(secondaryParts[0]), Convert.ToByte(secondaryParts[1]), Convert.ToByte(secondaryParts[2])));

            if (watermarkEnabled)
            {
                DrawingVisual drawingVisual = new DrawingVisual();
                double        PPD           = VisualTreeHelper.GetDpi(drawingVisual).PixelsPerDip;
                using (DrawingContext drawingContext = drawingVisual.RenderOpen())
                {
                    //INITIALIZATION
                    drawingContext.DrawRectangle(Brushes.Transparent, null, new Rect(new Point(0, 0), new Size(1024, 410)));

                    Point         dStart    = new Point(0, 256);
                    LineSegment[] dSegments = new[]
                    {
                        new LineSegment(new Point(1024, 256), true),
                        new LineSegment(new Point(1024, 241), true),
                        new LineSegment(new Point(537, 236), true),
                        new LineSegment(new Point(547, 249), true),
                        new LineSegment(new Point(0, 241), true)
                    };
                    PathFigure   dFigure = new PathFigure(dStart, dSegments, true);
                    PathGeometry dGeo    = new PathGeometry(new[] { dFigure });

                    Typeface      typeface      = new Typeface(TextsUtility.Burbank, FontStyles.Normal, FontWeights.Black, FontStretches.Normal);
                    FormattedText formattedText =
                        new FormattedText(
                            "{BUNDLE DISPLAY NAME HERE}",
                            CultureInfo.CurrentUICulture,
                            FlowDirection.LeftToRight,
                            typeface,
                            55,
                            Brushes.White,
                            PPD
                            );
                    formattedText.TextAlignment = TextAlignment.Left;
                    formattedText.MaxTextWidth  = 768;
                    formattedText.MaxLineCount  = 1;
                    Point textLocation = new Point(50, 165 - formattedText.Height);

                    drawingContext.DrawRectangle(PrimaryColor, null, new Rect(0, 0, 1024, 256));
                    if (!string.IsNullOrEmpty(path))
                    {
                        BitmapImage bmp = new BitmapImage(new Uri(path));
                        drawingContext.DrawImage(ImagesUtility.CreateTransparency(bmp, opacity), new Rect(0, 0, 1024, 256));
                    }
                    drawingContext.DrawGeometry(SecondaryColor, null, dGeo);
                    drawingContext.DrawText(formattedText, textLocation);

                    formattedText =
                        new FormattedText(
                            "{LAST FOLDER HERE}",
                            CultureInfo.CurrentUICulture,
                            FlowDirection.LeftToRight,
                            typeface,
                            30,
                            SecondaryColor,
                            IconCreator.PPD
                            );
                    formattedText.TextAlignment = TextAlignment.Left;
                    formattedText.MaxTextWidth  = 768;
                    formattedText.MaxLineCount  = 1;
                    textLocation = new Point(50, 100 - formattedText.Height);
                    Geometry geometry = formattedText.BuildGeometry(textLocation);
                    Pen      pen      = new Pen(ChallengesUtility.DarkBrush(SecondaryColor, 0.3f), 1);
                    pen.LineJoin = PenLineJoin.Round;
                    drawingContext.DrawGeometry(SecondaryColor, pen, geometry);

                    typeface      = new Typeface(TextsUtility.FBurbank, FontStyles.Normal, FontWeights.Normal, FontStretches.Normal);
                    formattedText =
                        new FormattedText(
                            watermark,
                            CultureInfo.CurrentUICulture,
                            FlowDirection.LeftToRight,
                            typeface,
                            20,
                            new SolidColorBrush(Color.FromArgb(150, 255, 255, 255)),
                            IconCreator.PPD
                            );
                    formattedText.TextAlignment = TextAlignment.Right;
                    formattedText.MaxTextWidth  = 1014;
                    formattedText.MaxLineCount  = 1;
                    textLocation = new Point(0, 205);
                    drawingContext.DrawText(formattedText, textLocation);

                    LinearGradientBrush linGrBrush = new LinearGradientBrush();
                    linGrBrush.StartPoint = new Point(0, 0);
                    linGrBrush.EndPoint   = new Point(0, 1);
                    linGrBrush.GradientStops.Add(new GradientStop(Color.FromArgb(75, SecondaryColor.Color.R, SecondaryColor.Color.G, SecondaryColor.Color.B), 0));
                    linGrBrush.GradientStops.Add(new GradientStop(Color.FromArgb(25, PrimaryColor.Color.R, PrimaryColor.Color.G, PrimaryColor.Color.B), 0.15));
                    linGrBrush.GradientStops.Add(new GradientStop(Color.FromArgb(0, 0, 0, 0), 1));

                    drawingContext.DrawRectangle(ChallengesUtility.DarkBrush(PrimaryColor, 0.3f), null, new Rect(0, 256, 1024, 144));
                    drawingContext.DrawRectangle(linGrBrush, null, new Rect(0, 256, 1024, 144));

                    typeface = new Typeface(TextsUtility.Burbank, FontStyles.Normal, FontWeights.Black, FontStretches.Normal);
                    int y = 300;

                    drawingContext.DrawRectangle(ChallengesUtility.DarkBrush(PrimaryColor, 0.3f), null, new Rect(0, y, 1024, 90));
                    drawingContext.DrawRectangle(PrimaryColor, null, new Rect(25, y, 1024 - 50, 70));

                    dStart    = new Point(32, y + 5);
                    dSegments = new[]
                    {
                        new LineSegment(new Point(29, y + 67), true),
                        new LineSegment(new Point(1024 - 160, y + 62), true),
                        new LineSegment(new Point(1024 - 150, y + 4), true)
                    };
                    dFigure = new PathFigure(dStart, dSegments, true);
                    dGeo    = new PathGeometry(new[] { dFigure });
                    drawingContext.DrawGeometry(ChallengesUtility.LightBrush(PrimaryColor, 0.04f), null, dGeo);

                    drawingContext.DrawRectangle(SecondaryColor, null, new Rect(60, y + 47, 500, 7));

                    dStart    = new Point(39, y + 35);
                    dSegments = new[]
                    {
                        new LineSegment(new Point(45, y + 32), true),
                        new LineSegment(new Point(48, y + 37), true),
                        new LineSegment(new Point(42, y + 40), true)
                    };
                    dFigure = new PathFigure(dStart, dSegments, true);
                    dGeo    = new PathGeometry(new[] { dFigure });
                    drawingContext.DrawGeometry(SecondaryColor, null, dGeo);
                }

                if (drawingVisual != null)
                {
                    RenderTargetBitmap RTB = new RenderTargetBitmap(1024, 410, 96, 96, PixelFormats.Pbgra32);
                    RTB.Render(drawingVisual);
                    RTB.Freeze(); //We freeze to apply the RTB to our imagesource from the UI Thread

                    FWindow.FMain.Dispatcher.InvokeAsync(() =>
                    {
                        ImageBox_ChallengePreview.Source = BitmapFrame.Create(RTB); //thread safe and fast af
                    });
                }
            }
            else
            {
                BitmapImage source = new BitmapImage(new Uri(CHALLENGE_TEMPLATE_ICON));
                ImageBox_ChallengePreview.Source = source;
            }
        }
Exemple #22
0
        //Detected images and calls detect faces

        private async void BrowseButton_Click(object sender, RoutedEventArgs e)
        {
            // Get the image file to scan from the user.
            var openDlg = new Microsoft.Win32.OpenFileDialog();

            openDlg.Filter = "JPEG Image(*.jpg)|*.jpg";
            bool?result = openDlg.ShowDialog(this);

            // Return if canceled.
            if (!(bool)result)
            {
                return;
            }

            // Display the image file.
            string filePath = openDlg.FileName;

            Uri         fileUri      = new Uri(filePath);
            BitmapImage bitmapSource = new BitmapImage();

            bitmapSource.BeginInit();
            bitmapSource.CacheOption = BitmapCacheOption.None;
            bitmapSource.UriSource   = fileUri;
            bitmapSource.EndInit();

            FacePhoto.Source = bitmapSource;

            // Detect any faces in the image.
            Title = "Detecting...";
            faces = await UploadAndDetectFaces(filePath);

            Title = String.Format("Detection Finished. {0} face(s) detected", faces.Length);

            if (faces.Length > 0)
            {
                // Prepare to draw rectangles around the faces.
                DrawingVisual  visual         = new DrawingVisual();
                DrawingContext drawingContext = visual.RenderOpen();
                drawingContext.DrawImage(bitmapSource,
                                         new Rect(0, 0, bitmapSource.Width, bitmapSource.Height));
                double dpi = bitmapSource.DpiX;
                resizeFactor     = 96 / dpi;
                faceDescriptions = new String[faces.Length];

                for (int i = 0; i < faces.Length; ++i)
                {
                    Face face = faces[i];

                    // Draw a rectangle on the face.
                    drawingContext.DrawRectangle(
                        Brushes.Transparent,
                        new Pen(Brushes.Red, 2),
                        new Rect(
                            face.FaceRectangle.Left * resizeFactor,
                            face.FaceRectangle.Top * resizeFactor,
                            face.FaceRectangle.Width * resizeFactor,
                            face.FaceRectangle.Height * resizeFactor
                            )
                        );

                    // Store the face description.
                    faceDescriptions[i] = FaceDescription(face);
                }

                drawingContext.Close();

                // Display the image with the rectangle around the face.
                RenderTargetBitmap faceWithRectBitmap = new RenderTargetBitmap(
                    (int)(bitmapSource.PixelWidth * resizeFactor),
                    (int)(bitmapSource.PixelHeight * resizeFactor),
                    96,
                    96,
                    PixelFormats.Pbgra32);

                faceWithRectBitmap.Render(visual);
                FacePhoto.Source = faceWithRectBitmap;

                // Set the status bar text.
                faceDescriptionStatusBar.Text = "Place the mouse pointer over a face to see the face description.";
            }
        }
Exemple #23
0
        /// <summary>
        /// Draws an image frame that is centered within the specified <see cref="RectD"/>.
        /// </summary>
        /// <param name="targetBitmap">
        /// The <see cref="WriteableBitmap"/> for the drawing, assuming that <paramref
        /// name="targetContext"/> is a null reference.</param>
        /// <param name="targetContext">
        /// The <see cref="DrawingContext"/> for the drawing, assuming that <paramref
        /// name="targetBitmap"/> is a null reference.</param>
        /// <param name="target">
        /// The region within <paramref name="targetContext"/> on which the copied image frame is
        /// centered.</param>
        /// <param name="sourceBitmap">
        /// A <see cref="WriteableBitmap"/> containing the image frame to copy.</param>
        /// <param name="source">
        /// The region within <paramref name="sourceBitmap"/> that covers the image frame to copy.
        /// </param>
        /// <param name="scalingX">
        /// An <see cref="ImageScaling"/> value indicating the horizontal scaling of the <paramref
        /// name="source"/> region to fit the specified <paramref name="target"/> region.</param>
        /// <param name="scalingY">
        /// An <see cref="ImageScaling"/> value indicating the vertical scaling of the <paramref
        /// name="source"/> region to fit the specified <paramref name="target"/> region.</param>
        /// <param name="colorShift">
        /// An optional <see cref="ColorVector"/> applied to all pixels within the drawing. Specify
        /// <see cref="ColorVector.Empty"/> if colors should remain unchanged.</param>
        /// <param name="offset">
        /// An optional pixel offset that is added to the centered location within the <paramref
        /// name="target"/> region.</param>
        /// <param name="scalingVector">
        /// An optional scaling vector for the drawing. Specify <see cref="PointI.Empty"/> if no
        /// scaling vector should be applied.</param>
        /// <exception cref="ArgumentException">
        /// <paramref name="targetBitmap"/> and <paramref name="targetContext"/> are both valid or
        /// both null references.</exception>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="sourceBitmap"/> is a null reference.</exception>
        /// <remarks><para>
        /// <b>DrawFrame</b> expects that the specified <paramref name="target"/> region equals the
        /// <see cref="RegularPolygon.Bounds"/> of the desired <see cref="RegularPolygon"/> shape.
        /// <b>DrawFrame</b> does not apply a mask or draw an outline around the frame.
        /// </para><para>
        /// Either the specified <paramref name="targetBitmap"/> or the specified <paramref
        /// name="targetContext"/> must be valid, but not both. <b>DrawFrame</b> internally draws to
        /// a <see cref="WriteableBitmap"/> whenever possible to preserve visual quality, then
        /// copies the result to the specified drawing target if different. Alpha blending is
        /// performed only when drawing to a valid <paramref name="targetContext"/>.
        /// </para><para>
        /// If <paramref name="targetBitmap"/> is valid, it must be locked before <b>DrawFrame</b>
        /// is called. If <paramref name="targetContext"/> is valid, the specified <paramref
        /// name="scalingVector"/> is applied to its transformation matrix; otherwise, negative
        /// components indicate mirroring along the corresponding axis of the <paramref
        /// name="targetBitmap"/>.</para></remarks>

        internal static void DrawFrame(WriteableBitmap targetBitmap,
                                       DrawingContext targetContext, RectD target,
                                       WriteableBitmap sourceBitmap, RectI source,
                                       ImageScaling scalingX, ImageScaling scalingY,
                                       ColorVector colorShift, PointI offset, PointI scalingVector)
        {
            // exactly one drawing target must be valid
            if ((targetContext == null && targetBitmap == null) ||
                (targetContext != null && targetBitmap != null))
            {
                ThrowHelper.ThrowArgumentExceptionWithFormat(
                    "targetBitmap", Tektosyne.Strings.ArgumentConflict, targetContext);
            }

            if (sourceBitmap == null)
            {
                ThrowHelper.ThrowArgumentNullException("sourceBitmap");
            }

            // copy source tile to buffer bitmap
            var frameBitmap = new WriteableBitmap(
                source.Width, source.Height, 96, 96, PixelFormats.Pbgra32, null);

            frameBitmap.Lock();
            frameBitmap.Read(0, 0, sourceBitmap, source);

            // shift color channels if desired
            if (!colorShift.IsEmpty)
            {
                frameBitmap.Shift(colorShift.R, colorShift.G, colorShift.B);
            }

            frameBitmap.Unlock();

            // round target coordinates for bitmaps
            RectI targetI = target.Round();

            // use WPF drawing for Stretch scaling, else bitmap copying
            if (scalingX == ImageScaling.Stretch || scalingY == ImageScaling.Stretch)
            {
                // create intermediate context if necessary
                DrawingVisual visual = null;
                if (targetContext == null)
                {
                    visual        = new DrawingVisual();
                    targetContext = visual.RenderOpen();
                }

                // draw frame to target or intermediate context
                DrawFrameCore(targetContext, target, frameBitmap,
                              scalingX, scalingY, offset, scalingVector);

                // copy intermediate context to target bitmap
                if (visual != null)
                {
                    targetContext.Close();
                    var bitmap = new RenderTargetBitmap(
                        targetI.Right, targetI.Bottom, 96, 96, PixelFormats.Pbgra32);
                    bitmap.Render(visual);
                    targetBitmap.Read(targetI.X, targetI.Y, bitmap, targetI);
                }
            }
            else
            {
                // create intermediate bitmap if necessary
                if (targetContext != null)
                {
                    Debug.Assert(targetBitmap == null);
                    targetBitmap = new WriteableBitmap(
                        targetI.Right, targetI.Bottom, 96, 96, PixelFormats.Pbgra32, null);
                    targetBitmap.Lock();
                }

                // draw frame to target or intermediate bitmap
                DrawFrameCore(targetBitmap, targetI, frameBitmap,
                              scalingX, scalingY, offset, scalingVector);

                // copy intermediate bitmap to target context
                if (targetContext != null)
                {
                    targetBitmap.Unlock();
                    targetContext.DrawImage(targetBitmap,
                                            new Rect(0, 0, targetBitmap.Width, targetBitmap.Height));
                }
            }
        }
Exemple #24
0
        /// <summary>
        /// Create a deep zoom image from a single source image
        /// </summary>
        /// <param name = "sourceImage" > Source image path</param>
        /// <param name = "destinationImage" > Destination path (must be .dzi or .xml)</param>
        public void CreateSingleComposition(string sourceImage, string destinationImage, ImageType type)
        {
            imageType = type;
            string source        = sourceImage;
            string destDirectory = Path.GetDirectoryName(destinationImage);
            string leafname      = Path.GetFileNameWithoutExtension(destinationImage);
            string root          = Path.Combine(destDirectory, leafname);;
            string filesdir      = root + "_files";

            Directory.CreateDirectory(filesdir);
            BitmapImage img         = new BitmapImage(new Uri(source));
            double      dWidth      = img.PixelWidth;
            double      dHeight     = img.PixelHeight;
            double      AspectRatio = dWidth / dHeight;

            // The Maximum level for the pyramid of images is
            // Log2(maxdimension)

            double maxdimension = Math.Max(dWidth, dHeight);
            double logvalue     = Math.Log(maxdimension, 2);
            int    MaxLevel     = (int)Math.Ceiling(logvalue);
            string topleveldir  = Path.Combine(filesdir, MaxLevel.ToString());

            // Create the directory for the top level tiles
            Directory.CreateDirectory(topleveldir);

            // Calculate how many tiles across and down
            int maxcols = img.PixelWidth / 256;
            int maxrows = img.PixelHeight / 256;

            // Get the bounding rectangle of the source image, for clipping
            Rect MainRect = new Rect(0, 0, img.PixelWidth, img.PixelHeight);

            for (int j = 0; j <= maxrows; j++)
            {
                for (int i = 0; i <= maxcols; i++)
                {
                    // Calculate the bounds of the tile
                    // including a 1 pixel overlap each side
                    Rect smallrect = new Rect((double)(i * 256) - 1, (double)(j * 256) - 1, 258.0, 258.0);

                    // Adjust for the rectangles at the edges by intersecting
                    smallrect.Intersect(MainRect);

                    // We want a RenderTargetBitmap to render this tile into
                    // Create one with the dimensions of this tile
                    RenderTargetBitmap outbmp  = new RenderTargetBitmap((int)smallrect.Width, (int)smallrect.Height, 96, 96, PixelFormats.Pbgra32);
                    DrawingVisual      visual  = new DrawingVisual();
                    DrawingContext     context = visual.RenderOpen();

                    // Set the offset of the source image into the destination bitmap
                    // and render it
                    Rect rect = new Rect(-smallrect.Left, -smallrect.Top, img.PixelWidth, img.PixelHeight);
                    context.DrawImage(img, rect);
                    context.Close();
                    outbmp.Render(visual);

                    // Save the bitmap tile
                    string destination = Path.Combine(topleveldir, string.Format("{0}_{1}", i, j));
                    EncodeBitmap(outbmp, destination);

                    // null out everything we've used so the Garbage Collector
                    // knows they're free. This could easily be voodoo since they'll go
                    // out of scope, but it can't hurt.
                    outbmp  = null;
                    context = null;
                    visual  = null;
                }
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }

            // clear the source image since we don't need it anymore
            img = null;
            GC.Collect();
            GC.WaitForPendingFinalizers();

            // Now render the lower levels by rendering the tiles from the level
            // above to the next level down
            for (int level = MaxLevel - 1; level >= 0; level--)
            {
                RenderSubtiles(filesdir, dWidth, dHeight, MaxLevel, level);
            }

            // Now generate the .dzi file

            string format = "png";

            if (imageType == ImageType.Jpeg)
            {
                format = "jpg";
            }

            XElement dzi = new XElement("Image",
                                        new XAttribute("TileSize", 256),
                                        new XAttribute("Overlap", 1),
                                        new XAttribute("Format", format), // xmlns="http://schemas.microsoft.com/deepzoom/2008">
                                        new XElement("Size",
                                                     new XAttribute("Width", dWidth),
                                                     new XAttribute("Height", dHeight)),
                                        new XElement("DisplayRects",
                                                     new XElement("DisplayRect",
                                                                  new XAttribute("MinLevel", 1),
                                                                  new XAttribute("MaxLevel", MaxLevel),
                                                                  new XElement("Rect",
                                                                               new XAttribute("X", 0),
                                                                               new XAttribute("Y", 0),
                                                                               new XAttribute("Width", dWidth),
                                                                               new XAttribute("Height", dHeight)))));

            dzi.Save(destinationImage);
        }
Exemple #25
0
        /// <overloads>
        /// Draws the specified image frame to the specified <see cref="DrawingContext"/> or <see
        /// cref="WriteableBitmap"/>.</overloads>
        /// <summary>
        /// Draws the specified image frame to the specified <see cref="DrawingContext"/>.</summary>
        /// <param name="targetContext">
        /// The <see cref="DrawingContext"/> for the drawing.</param>
        /// <param name="target">
        /// The region within <paramref name="targetContext"/> on which the copied image frame is
        /// centered.</param>
        /// <param name="frameBitmap">
        /// A <see cref="WriteableBitmap"/> containing exactly the image frame to copy.</param>
        /// <param name="scalingX">
        /// An <see cref="ImageScaling"/> value indicating the horizontal scaling of the <paramref
        /// name="frameBitmap"/> to fit the specified <paramref name="target"/> region.</param>
        /// <param name="scalingY">
        /// An <see cref="ImageScaling"/> value indicating the vertical scaling of the <paramref
        /// name="frameBitmap"/> fit the specified <paramref name="target"/> region.</param>
        /// <param name="offset">
        /// An optional pixel offset that is added to the centered location within the <paramref
        /// name="target"/> region.</param>
        /// <param name="scalingVector">
        /// An optional scaling vector that is applied to the transformation matrix of the specified
        /// <paramref name="targetContext"/>. Specify <see cref="PointI.Empty"/> if no scaling
        /// vector should be applied.</param>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="targetContext"/> or <paramref name="frameBitmap"/> is a null reference.
        /// </exception>
        /// <remarks>
        /// <b>DrawFrameCore</b> is called by <see cref="DrawFrame"/> when drawing to a <see
        /// cref="DrawingContext"/>, or to a <see cref="WriteableBitmap"/> with <see
        /// cref="ImageScaling.Stretch"/> scaling.</remarks>

        private static void DrawFrameCore(DrawingContext targetContext, RectD target,
                                          WriteableBitmap frameBitmap, ImageScaling scalingX, ImageScaling scalingY,
                                          PointI offset, PointI scalingVector)
        {
            if (targetContext == null)
            {
                ThrowHelper.ThrowArgumentNullException("targetContext");
            }
            if (frameBitmap == null)
            {
                ThrowHelper.ThrowArgumentNullException("frameBitmap");
            }

            // compute upper left corner of centered & offset frame
            SizeI  source = new SizeI(frameBitmap.PixelWidth, frameBitmap.PixelHeight);
            double x      = target.X + offset.X + (target.Width - source.Width) / 2.0;
            double y      = target.Y + offset.Y + (target.Height - source.Height) / 2.0;

            // default coordinates for single unscaled frame
            Rect  frame      = new Rect(0, 0, source.Width, source.Height);
            Point frameStart = new Point(x, y);
            Point frameStop  = new Point(x + source.Width, y + source.Height);

            // adjust horizontal coordinates for desired scaling
            switch (scalingX)
            {
            case ImageScaling.Repeat:
                while (frameStart.X > target.X)
                {
                    frameStart.X -= source.Width;
                }
                frameStop.X = target.Right;
                break;

            case ImageScaling.Stretch:
                frameStart.X = target.X + offset.X;
                frame.Width  = target.Width;
                break;
            }

            // adjust vertical coordinates for desired scaling
            switch (scalingY)
            {
            case ImageScaling.Repeat:
                while (frameStart.Y > target.Y)
                {
                    frameStart.Y -= source.Height;
                }
                frameStop.Y = target.Bottom;
                break;

            case ImageScaling.Stretch:
                frameStart.Y = target.Y + offset.Y;
                frame.Height = target.Height;
                break;
            }

            // apply scaling vector if specified
            double mx = 0, my = 0;

            if (scalingVector != PointI.Empty)
            {
                Matrix matrix = new Matrix();
                matrix.Scale(scalingVector.X, scalingVector.Y);
                targetContext.PushTransform(new MatrixTransform(matrix));

                // compensate for any coordinate inversion
                if (scalingVector.X < 0)
                {
                    mx = -2 * x - source.Width;
                }
                if (scalingVector.Y < 0)
                {
                    my = -2 * y - source.Height;
                }
            }

            // repeatedly copy frame to fill target bounds
            for (double dx = frameStart.X; dx < frameStop.X; dx += frame.Width)
            {
                for (double dy = frameStart.Y; dy < frameStop.Y; dy += frame.Height)
                {
                    frame.Location = new Point(dx + mx, dy + my);
                    targetContext.DrawImage(frameBitmap, frame);
                }
            }

            // pop scaling transformation, if any
            if (scalingVector != PointI.Empty)
            {
                targetContext.Pop();
            }
        }
 protected override void Render(DrawingContext context, Camera camera, IStandardRenderableBlock block, IntRectangle rectangle)
 {
     context.PushOpacity(0.75f + 0.25f * block.IntegrityRatio);
     context.DrawImage(block.Image, camera.CastRectangle(rectangle).ToWindowsRect());
     context.Pop();
 }
        private void UpdateGridTile(BorderGrid mainGrid, Point gridPosition)
        {
            // get the current entity selected from the palette. could be an ore or a critter!
            var item = ViewModel.SelectedTileEntity;

            // get the template cell in the main grid
            var targetTemplateCell = ViewModel.Cells.First(x => x.Column == gridPosition.X && x.Row == gridPosition.Y);

            if (targetTemplateCell.TileEntities[0].Classification != TileType.GasElement && item.EntityType != null)
            {
                MessageBox.Show("Base gas element required before placing creature or plant");
                return;
            }

            // update the template cell with the selected values
            if (item.EntityType == null)
            {
                targetTemplateCell.TileEntities[0].ElementType    = item.ElementType;
                targetTemplateCell.TileEntities[0].Classification = item.Classification;
                targetTemplateCell.TileEntities[0].DisplayName    = item.DisplayName;
                targetTemplateCell.TileEntities[0].EntityType     = item.EntityType;
                targetTemplateCell.TileEntities[0].ImageUri       = item.ImageUri;
                targetTemplateCell.TileEntities[0].TileProperty   = item.TileProperty.Copy();
            }
            else
            {
                targetTemplateCell.TileEntities[1].ElementType    = item.ElementType;
                targetTemplateCell.TileEntities[1].Classification = item.Classification;
                targetTemplateCell.TileEntities[1].DisplayName    = item.DisplayName;
                targetTemplateCell.TileEntities[1].EntityType     = item.EntityType;
                targetTemplateCell.TileEntities[1].ImageUri       = item.ImageUri;
                targetTemplateCell.TileEntities[1].TileProperty   = item.TileProperty.Copy();
            }

            // get the current container in the grid
            var stackPanel = mainGrid.Children.Cast <UIElement>().First(g => Grid.GetRow(g) == gridPosition.Y && Grid.GetColumn(g) == gridPosition.X) as StackPanel;

            // update the render images
            var baseImage   = stackPanel.Children[0] as Image;
            var baseContext = baseImage.DataContext as TileEntity;

            var entityImage   = stackPanel.Children[1] as Image;
            var entityContext = entityImage.DataContext as TileEntity;

            BitmapFrame baseFrame   = BitmapDecoder.Create(new Uri("pack://application:,,,/OniTemplate;component/Images/" + baseContext.ImageUri), BitmapCreateOptions.None, BitmapCacheOption.OnLoad).Frames.First();
            BitmapFrame entityFrame = BitmapDecoder.Create(new Uri("pack://application:,,,/OniTemplate;component/Images/" + entityContext.ImageUri), BitmapCreateOptions.None, BitmapCacheOption.OnLoad).Frames.First();

            // Gets the size of the images
            int imageWidth  = 50;
            int imageHeight = 50;

            // Draws the images into a DrawingVisual component
            DrawingVisual drawingVisual = new DrawingVisual();

            using (DrawingContext drawingContext = drawingVisual.RenderOpen())
            {
                if (item.EntityType != null)
                {
                    drawingContext.DrawImage(baseFrame, new Rect(0, 0, imageWidth, imageHeight));
                    drawingContext.DrawImage(entityFrame, new Rect(imageWidth, 0, imageWidth, imageHeight));
                }
                else
                {
                    drawingContext.DrawImage(baseFrame, new Rect(0, 0, imageWidth, imageHeight));
                }
            }

            // Converts the Visual (DrawingVisual) into a BitmapSource
            RenderTargetBitmap bmp = null;

            if (item.EntityType != null)
            {
                bmp = new RenderTargetBitmap(imageWidth * 2, imageHeight * 2, 96, 96, PixelFormats.Pbgra32);
            }
            else
            {
                bmp = new RenderTargetBitmap(imageWidth, imageHeight, 96, 96, PixelFormats.Pbgra32);
            }
            bmp.Render(drawingVisual);

            // Creates a PngBitmapEncoder and adds the BitmapSource to the frames of the encoder
            PngBitmapEncoder encoder = new PngBitmapEncoder();

            encoder.Frames.Add(BitmapFrame.Create(bmp));
            var blended = new MemoryStream();

            encoder.Save(blended);

            var renderImage = new BitmapImage();

            renderImage.BeginInit();
            renderImage.StreamSource = blended;
            renderImage.EndInit();
            baseImage.Source = renderImage;
        }
Exemple #28
0
        protected void DrawHsvDial(DrawingContext drawingContext)
        {
            float cx = (float)(Bounds.Width) / 2.0f;
            float cy = (float)(Bounds.Height) / 2.0f;

            float outer_radius = (float)Math.Min(cx, cy);

            ActualOuterRadius = outer_radius;

            int bmp_width  = (int)Bounds.Width;
            int bmp_height = (int)Bounds.Height;

            if (bmp_width <= 0 || bmp_height <= 0)
            {
                return;
            }


            var stopwatch = new Stopwatch();

            stopwatch.Start();

            //This probably wants to move somewhere else....
            if (border == null)
            {
                border                  = new Ellipse();
                border.Fill             = new SolidColorBrush(Colors.Transparent);
                border.Stroke           = new SolidColorBrush(Colors.Black);
                border.StrokeThickness  = 3;
                border.IsHitTestVisible = false;
                border.Opacity          = 50;
                this.Children.Add(border);
                border.HorizontalAlignment = HA.Center;
                border.VerticalAlignment   = VA.Center;
            }

            border.Width  = Math.Min(bmp_width, bmp_height) + (border.StrokeThickness / 2);
            border.Height = Math.Min(bmp_width, bmp_height) + (border.StrokeThickness / 2);

            var writeableBitmap = new WriteableBitmap(new PixelSize(bmp_width, bmp_height), new Vector(96, 96), PixelFormat.Bgra8888);

            using (var lockedFrameBuffer = writeableBitmap.Lock())
            {
                unsafe
                {
                    IntPtr bufferPtr = new IntPtr(lockedFrameBuffer.Address.ToInt64());

                    for (int y = 0; y < bmp_height; y++)
                    {
                        for (int x = 0; x < bmp_width; x++)
                        {
                            int color_data = 0;

                            // Convert xy to normalized polar co-ordinates
                            double dx = x - cx;
                            double dy = y - cy;
                            double pr = Math.Sqrt(dx * dx + dy * dy);

                            // Only draw stuff within the circle
                            if (pr <= outer_radius)
                            {
                                // Compute the color for the given pixel using polar co-ordinates
                                double    pa = Math.Atan2(dx, dy);
                                RGBStruct c  = ColorFunction(pr / outer_radius, ((pa + Math.PI) * 180.0 / Math.PI));

                                // Anti-aliasing
                                // This works by adjusting the alpha to the alias error between the outer radius (which is integer)
                                // and the computed radius, pr (which is float).
                                double aadelta = pr - (outer_radius - 1.0);
                                if (aadelta >= 0.0)
                                {
                                    c.a = (byte)(255 - aadelta * 255);
                                }

                                color_data = c.ToARGB32();
                            }

                            *((int *)bufferPtr) = color_data;
                            bufferPtr          += 4;
                        }
                    }
                }
            }

            drawingContext.DrawImage(writeableBitmap, Bounds);

            stopwatch.Stop();
            Debug.WriteLine($"YO! This puppy took {stopwatch.ElapsedMilliseconds} MS to complete");
        }
Exemple #29
0
        protected override void OnRender(DrawingContext drawingContext)
        {
            Size renderSize = this.RenderSize;
            var  theme      = Themes.Theme;
            var  bgColor    = theme.GetColor(ColorType.IconBar).InheritedColor.Background.GetColor(null).Value;

            drawingContext.DrawRectangle(theme.GetColor(ColorType.IconBar).InheritedColor.Background.GetBrush(null), null,
                                         new Rect(0, 0, renderSize.Width, renderSize.Height));
            drawingContext.DrawLine(new Pen(theme.GetColor(ColorType.IconBarBorder).InheritedColor.Background.GetBrush(null), 1),
                                    new Point(renderSize.Width - 0.5, 0),
                                    new Point(renderSize.Width - 0.5, renderSize.Height));

            ICSharpCode.AvalonEdit.Rendering.TextView textView = this.TextView;
            if (textView != null && textView.VisualLinesValid)
            {
                // create a dictionary line number => first bookmark
                Dictionary <int, List <IBookmark> > bookmarkDict = new Dictionary <int, List <IBookmark> >();
                var cm = decompilerTextView.CodeMappings;
                foreach (var bm in BookmarkManager.Bookmarks)
                {
                    if (bm is BreakpointBookmark)
                    {
                        if (cm == null || cm.Count == 0 || !cm.ContainsKey(((BreakpointBookmark)bm).MethodKey))
                        {
                            continue;
                        }
                    }
                    int line = bm.GetLineNumber(decompilerTextView);
                    List <IBookmark> list;
                    if (!bookmarkDict.TryGetValue(line, out list))
                    {
                        bookmarkDict[line] = list = new List <IBookmark>();
                    }
                    list.Add(bm);
                }

                foreach (var bm in manager.Bookmarks)
                {
                    int line = BookmarkBase.GetLineNumber(bm, decompilerTextView);
                    List <IBookmark> list;
                    if (!bookmarkDict.TryGetValue(line, out list))
                    {
                        bookmarkDict[line] = list = new List <IBookmark>();
                    }
                    list.Add(bm);
                }

                const double imagePadding = 1.0;
                Size         pixelSize    = PixelSnapHelpers.GetPixelSize(this);
                foreach (VisualLine line in textView.VisualLines)
                {
                    int lineNumber = line.FirstDocumentLine.LineNumber;
                    List <IBookmark> list;
                    if (!bookmarkDict.TryGetValue(lineNumber, out list))
                    {
                        continue;
                    }
                    list.Sort((a, b) => a.ZOrder.CompareTo(b.ZOrder));
                    foreach (var bm in list)
                    {
                        Rect rect = new Rect(imagePadding, PixelSnapHelpers.Round(line.VisualTop - textView.VerticalOffset, pixelSize.Height), 16, 16);
                        drawingContext.DrawImage(bm.GetImage(bgColor), rect);
                    }
                }
            }
        }
Exemple #30
0
        /// <summary>
        /// Renders the visual content of the <see cref="MapViewRenderer"/>.</summary>
        /// <param name="context">
        /// The <see cref="DrawingContext"/> for the rendering.</param>
        /// <remarks><para>
        /// <b>OnRender</b> calls the base class implementation of <see cref="UIElement.OnRender"/>,
        /// and then immediately returns if the associated <see cref="MapView"/> has not been fully
        /// initialized yet, or already been disposed of.
        /// </para><para>
        /// Otherwise, <b>OnRender</b> redraws the current <see cref="MapViewControl.Viewport"/>.
        /// The <see cref="Graphics.MapView.Extent"/> of the associated <see cref="MapView"/>
        /// outside the current <see cref="MapViewControl.Viewport"/> remains empty.
        /// </para></remarks>

        protected override void OnRender(DrawingContext context)
        {
            base.OnRender(context);
            if (MapView.Catalog == null || MapView.IsDisposed)
            {
                return;
            }

            // check if there is anything to render
            Rect viewRegion = Control.Viewport;

            if (viewRegion.Width == 0 || viewRegion.Height == 0)
            {
                return;
            }

            // distance from center point to upper-left corner
            double centerX = MapView.TileWidth / 2.0;
            double centerY = MapView.TileHeight / 2.0;

            // compute sites covered by viewport
            RectD region     = viewRegion.ToRectD();
            RectI intRegion  = region.Circumscribe();
            RectI siteRegion = MapView.ViewToSite(region);

            // resize & clear paint buffer
            bool mustClear = EnsureBufferSize(intRegion.Size);

            PaintBuffer.Lock();
            if (mustClear)
            {
                PaintBuffer.Clear();
            }

            // cache performance options
            this._bitmapGrid   = ApplicationOptions.Instance.View.BitmapGrid;
            this._opaqueImages = ApplicationOptions.Instance.View.OpaqueImages;

            // draw entities of all sites within region
            for (int x = siteRegion.Left; x < siteRegion.Right; x++)
            {
                for (int y = siteRegion.Top; y < siteRegion.Bottom; y++)
                {
                    Site site = MapView.WorldState.Sites[x, y];

                    // compute upper-left corner of bitmap tile
                    PointD display = MapView.SiteToView(site.Location);
                    PointI pixel   = new PointI(
                        Fortran.NInt(display.X - centerX),
                        Fortran.NInt(display.Y - centerY));

                    // draw entities in current site
                    DrawEntities(pixel, intRegion, site);
                }
            }

            // copy paint buffer to viewport
            PaintBuffer.Unlock();
            context.DrawImage(PaintBuffer,
                              new Rect(region.Left, region.Top, PaintBuffer.Width, PaintBuffer.Height));

            // draw optional decoration on all sites
            DrawDecoration(context, siteRegion);
        }
Exemple #31
0
		/// <summary>
		/// Renders the contents of the image
		/// </summary>
		/// <param name="dc">An instance of <see cref="T:Windows.UI.Xaml.Media.DrawingContext"/> used to render the control.</param>
		protected override void OnRender (DrawingContext dc)
		{
			if (background != null)
				dc.DrawRectangle (background, null, new Rect (0, 0, RenderSize.Width, RenderSize.Height));

			if (Source == null)
				return;

			ImageSource src = Source;
			var ourSize = RenderSize.Width * RenderSize.Height;
			foreach (var frame in _availableFrames)
			{
				src = frame;
				if (frame.PixelWidth * frame.PixelHeight >= ourSize)
					break;
			}
			dc.DrawImage (src, new Rect (new Point (0, 0), RenderSize));
		}