/// <summary>
        ///   Renders the ui element into a bitmap frame using the specified scale.
        /// </summary>
        /// <param name = "element">The UI element.</param>
        /// <param name = "scale">The scale (default: 1).</param>
        /// <returns>The created bitmap frame</returns>
        public static BitmapSource RenderToBitmap(this UIElement element, double scale)
        {
            var renderWidth = (int) (element.RenderSize.Width * scale);
            var renderHeight = (int) (element.RenderSize.Height * scale);

            var renderTarget = new RenderTargetBitmap(renderWidth, renderHeight, 96, 96, PixelFormats.Pbgra32);
            var sourceBrush = new VisualBrush(element);

            var drawingVisual = new DrawingVisual();

            using (var drawingContext = drawingVisual.RenderOpen())
            {
                drawingContext.PushTransform(new ScaleTransform(scale, scale));
                drawingContext.DrawRectangle(sourceBrush, null, new Rect(new Point(0, 0), new Point(element.RenderSize.Width, element.RenderSize.Height)));
            }
            renderTarget.Render(drawingVisual);

            return renderTarget;
        }
Beispiel #2
0
        PdfTilingPattern BuildPattern(VisualBrush brush, XMatrix transform)
        {
            // Bounding box lays always at (0,0)
            XRect bbox = new XRect(0, 0, brush.Viewport.Width, brush.Viewport.Height);

            XMatrix matrix = transform;

            matrix.Prepend(new XMatrix(1, 0, 0, 1, brush.Viewport.X, brush.Viewport.Y));
            if (brush.Transform != null)
            {
                matrix.Prepend(new XMatrix(brush.Transform.Matrix.m11, brush.Transform.Matrix.m12, brush.Transform.Matrix.m21,
                                           brush.Transform.Matrix.m22, brush.Transform.Matrix.offsetX, brush.Transform.Matrix.offsetY));
            }

            // Set X Step beyond the viewport if tilemode is set to none since
            // there is no other easy way to turn off tiling - NPJ
            double xStep = brush.Viewport.Width * (brush.TileMode == TileMode.None ? 2 : 1);
            double yStep = brush.Viewport.Height * (brush.TileMode == TileMode.None ? 2 : 1);

            // PdfTilingPattern
            //<<
            //  /BBox [0 0 240 120]
            //  /Length 74
            //  /Matrix [0.75 0 0 -0.75 0 480]
            //  /PaintType 1
            //  /PatternType 1
            //  /Resources
            //  <<
            //    /ExtGState
            //    <<
            //      /GS0 10 0 R
            //    >>
            //    /XObject
            //    <<
            //      /Fm0 17 0 R
            //    >>
            //  >>
            //  /TilingType 3
            //  /Type /Pattern
            //  /XStep 480
            //  /YStep 640
            //>>
            //stream
            //  q
            //  0 0 240 120 re
            //  W n
            //  q
            //    2.3999939 0 0 1.1999969 0 0 cm
            //    /GS0 gs
            //    /Fm0 Do
            //  Q
            //Q
            //endstream
            PdfTilingPattern pattern = new PdfTilingPattern(Context.PdfDocument);

            Context.PdfDocument.Internals.AddObject(pattern);
            pattern.Elements.SetInteger(PdfTilingPattern.Keys.PatternType, 1); // Tiling
            pattern.Elements.SetInteger(PdfTilingPattern.Keys.PaintType, 1);   // Color
            pattern.Elements.SetInteger(PdfTilingPattern.Keys.TilingType, 3);  // Constant spacing and faster tiling
            pattern.Elements.SetMatrix(PdfTilingPattern.Keys.Matrix, matrix);
            pattern.Elements.SetRectangle(PdfTilingPattern.Keys.BBox, new PdfRectangle(bbox));
            pattern.Elements.SetReal(PdfTilingPattern.Keys.XStep, xStep);
            pattern.Elements.SetReal(PdfTilingPattern.Keys.YStep, yStep);

            // Set extended graphic state like Acrobat do
            PdfExtGState pdfExtGState = Context.PdfDocument.Internals.CreateIndirectObject <PdfExtGState>();

            pdfExtGState.SetDefault1();

            PdfFormXObject pdfForm = BuildForm(brush);

            PdfContentWriter writer = new PdfContentWriter(Context, pattern);

            writer.BeginContentRaw();

            // Acrobat 8 clips to bounding box, so do we
            //writer.WriteClip(bbox);

            XMatrix transformation = new XMatrix();
            double  dx             = brush.Viewport.Width / brush.Viewbox.Width * 96 / pdfForm.DpiX;
            double  dy             = brush.Viewport.Height / brush.Viewbox.Height * 96 / pdfForm.DpiY;

            transformation = new XMatrix(dx, 0, 0, dy, 0, 0);
            writer.WriteMatrix(transformation);
            writer.WriteGraphicsState(pdfExtGState);

            string name = writer.Resources.AddForm(pdfForm);

            writer.WriteLiteral(name + " Do\n");

            writer.EndContent();

            return(pattern);
        }
        private void CaptureLayer()
        {
            SetFlashFill(captureIndex);
            flashStoryboard.Begin(this);

            switch (captureIndex)
            {
            case 0:
                capture1Storyboard.Begin(this);
                break;

            case 1:
                capture2Storyboard.Begin(this);
                break;

            case 2:
                capture3Storyboard.Begin(this);
                break;

            default:
                break;
            }

            RenderTargetBitmap renderBitmap = new RenderTargetBitmap((int)CompositeImage.ActualWidth, (int)CompositeImage.ActualHeight, 96.0, 96.0, PixelFormats.Pbgra32);
            DrawingVisual      dv           = new DrawingVisual();

            using (DrawingContext dc = dv.RenderOpen())
            {
                VisualBrush brush = new VisualBrush(CompositeImage);
                dc.DrawRectangle(brush, null, new Rect(new System.Windows.Point(), new System.Windows.Size(CompositeImage.ActualWidth, CompositeImage.ActualHeight)));
            }
            renderBitmap.Render(dv);

            byte[] encoded;

            using (MemoryStream stream = new MemoryStream())
            {
                var encoder = new PngBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(renderBitmap));
                encoder.Save(stream);
                encoded = stream.ToArray();
            }

            BitmapImage processed = new BitmapImage();
            double      opacity   = 1;

            using (MemoryStream stream = new MemoryStream())
            {
                using (ImageProcessor.ImageFactory imageFactory = new ImageProcessor.ImageFactory(false))
                {
                    imageFactory.Load(encoded);
                    imageFactory.Filter(ImageProcessor.Imaging.Filters.Photo.MatrixFilters.BlackWhite);
                    switch (captureIndex)
                    {
                    case 0:
                        break;

                    case 1:
                        imageFactory.Tint(System.Drawing.Color.Magenta);
                        opacity = .4;
                        break;

                    case 2:
                        imageFactory.Tint(System.Drawing.Color.Cyan);
                        opacity = .3;
                        break;

                    case 3:
                        imageFactory.Tint(System.Drawing.Color.Yellow);
                        opacity = .2;
                        break;

                    default:
                        break;
                    }
                    imageFactory.Save(stream);
                }

                processed.BeginInit();
                processed.CacheOption  = BitmapCacheOption.OnLoad;
                processed.StreamSource = stream;
                processed.EndInit();
            }

            System.Windows.Controls.Image image = new System.Windows.Controls.Image()
            {
                Source  = processed,
                Stretch = Stretch.None,
                Opacity = opacity
            };
            CompositeLayers.Children.Add(image);
        }
Beispiel #4
0
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is IControlTemplate ctrlTemplate)
            {
                return(ctrlTemplate);
            }
            else if (value is IControl ctrl)
            {
                ctrl.Measure(Size.Infinity);
                Thickness ctrlMargin = ctrl.Margin;
                double    ctrlWidth  = ctrl.DesiredSize.Width + ctrlMargin.Left + ctrlMargin.Right;
                double    ctrlHeight = ctrl.DesiredSize.Height + ctrlMargin.Top + ctrlMargin.Bottom;

                VisualBrush visBrush = new VisualBrush(ctrl);
                return(new FuncControlTemplate((tctrl, namescope) => new Rectangle()
                {
                    Width = ctrlWidth,
                    Height = ctrlHeight,
                    Fill = visBrush
                }));
            }
            else if (value is Geometry geom)
            {
                return(new FuncControlTemplate((tctrl, namescope) =>
                {
                    var path = new Path()
                    {
                        Data = geom
                    };
                    path[!Path.FillProperty] = new TemplateBinding(TextBlock.ForegroundProperty);
                    return path;
                }));
            }
            else if (value is Drawing draw)
            {
                DrawingImage drImage = new DrawingImage()
                {
                    Drawing = draw
                };
                return(new FuncControlTemplate((tctrl, namescope) => new Image()
                {
                    Source = drImage,
                    Width = drImage.Size.Width,
                    Height = drImage.Size.Height
                }));
            }
            else if (value is string str)
            {
                string inStr          = str;
                bool   explicitSize   = inStr.StartsWith(EXPLICIT_SIZE_PREFIX);
                double explicitWidth  = 0;
                double explicitHeight = 0;
                if (explicitSize)
                {
                    inStr = str.Substring(EXPLICIT_SIZE_PREFIX.Length);
                    int    splitIndex = inStr.IndexOf(EXPLICIT_SIZE_SUFFIX);
                    string before     = inStr.Substring(0, splitIndex).Replace(" ", string.Empty);
                    inStr = inStr.Substring(splitIndex + EXPLICIT_SIZE_SUFFIX.Length);

                    if (before.Contains(EXPLICIT_SIZE_SEPARATOR.ToString()))
                    {
                        string[] b4 = before.Split(EXPLICIT_SIZE_SEPARATOR);
                        explicitWidth  = double.Parse(b4[0]);
                        explicitHeight = double.Parse(b4[1]);
                    }
                    else
                    {
                        explicitWidth  = double.Parse(before);
                        explicitHeight = explicitWidth;
                    }

                    while (inStr.StartsWith(" "))
                    {
                        inStr = inStr.Substring(1);
                    }
                }


                try
                {
                    var stUri = new Uri(inStr, UriKind.Absolute);

                    var    assetLoader = AvaloniaLocator.Current.GetService <IAssetLoader>();
                    Bitmap bmp         = null;
                    using (var stream = assetLoader.Open(stUri))
                    {
                        bmp = new Bitmap(stream);
                    }
                    if (!explicitSize)
                    {
                        explicitWidth  = bmp.Size.Width;
                        explicitHeight = bmp.Size.Height;
                    }

                    return(new FuncControlTemplate((tctrl, namescope) => new Image()
                    {
                        Source = bmp,
                        Width = explicitWidth,
                        Height = explicitHeight
                    }));
                }
                catch
                {
                    try
                    {
                        var geome = PathGeometry.Parse(inStr);
                        return(new FuncControlTemplate((tctrl, namescope) =>
                        {
                            var path = new Path()
                            {
                                Data = geome
                            };
                            if (explicitSize)
                            {
                                path.Width = explicitWidth;
                                path.Height = explicitHeight;
                                path.Stretch = Stretch.Fill;
                            }
                            path[!Path.FillProperty] = new TemplateBinding(TextBlock.ForegroundProperty);
                            return path;
                        }));
                    }
                    catch { }
                }
            }
            else if (value is IImage img)
            {
                return(new FuncControlTemplate((tctrl, namescope) => new Image()
                {
                    Source = img
                }));
            }
            else if (value is Uri uri)
            {
                return(new FuncControlTemplate((tctrl, namescope) => new Image()
                {
                    Source = new Bitmap(uri.ToString())
                }));
            }
            else if (value is PathFigures fig)
            {
                return(new FuncControlTemplate((tctrl, namescope) =>
                {
                    var path = new Path()
                    {
                        Data = new PathGeometry()

                        {
                            Figures = fig
                        }
                    };
                    path[!Path.FillProperty] = new TemplateBinding(TextBlock.ForegroundProperty);
                    return path;
                }));
            }
            else if (value is PathFigure figure)
            {
                return(new FuncControlTemplate((tctrl, namescope) =>
                {
                    var path = new Path()
                    {
                        Data = new PathGeometry()

                        {
                            Figures = { figure }
                        }
                    };
                    path[!Path.FillProperty] = new TemplateBinding(TextBlock.ForegroundProperty);
                    return path;
                }));
            }

            return(null);
        }
Beispiel #5
0
        public bool RotateFrameKeepSize(double rotationDegrees, BitmapScalingMode scalingMode = BitmapScalingMode.NearestNeighbor)
        {
            var clipped = false;

            var rotationRad = rotationDegrees / 180.0 * Math.PI;
            var frame       = this.BitmapFrame;
            var w           = frame.PixelWidth;
            var h           = frame.PixelHeight;

            var imageRect = FindNonTransparentRect(frame);

            var newW = (int)(Math.Abs(imageRect.Width * Math.Sin(rotationRad)) + Math.Abs(imageRect.Height * Math.Cos(rotationRad)));
            var newH = (int)(Math.Abs(imageRect.Width * Math.Cos(rotationRad)) + Math.Abs(imageRect.Height * Math.Sin(rotationRad)));

            if (newW > w || newH > h)
            {
                clipped = true;
            }

            var transformGroup = new TransformGroup();
            var rotation       = new RotateTransform(rotationDegrees);

            rotation.CenterX = w / 2.0;
            rotation.CenterY = h / 2.0;
            var translate = new TranslateTransform((w - imageRect.Width) / 2.0 - imageRect.X, (h - imageRect.Height) / 2.0 - imageRect.Y);

            transformGroup.Children.Add(translate);
            transformGroup.Children.Add(rotation);

            var origHotspot        = new Point(this.HLeft, this.HTop);
            var transformedHotspot = transformGroup.Transform(origHotspot);

            var image = new Image()
            {
                Source              = frame,
                RenderTransform     = transformGroup,
                Width               = w,
                Height              = h,
                Stretch             = Stretch.None,
                UseLayoutRounding   = false,
                SnapsToDevicePixels = false,
            };

            RenderOptions.SetBitmapScalingMode(image, scalingMode);
            image.Arrange(new Rect(0, 0, w, h));
            var newRect = new Rect(0, 0, w, h);

            var dv = new DrawingVisual();

            using (var ctx = dv.RenderOpen())
            {
                var vb = new VisualBrush(image);
                vb.TileMode     = TileMode.None;
                vb.ViewboxUnits = BrushMappingMode.Absolute;
                vb.Viewbox      = newRect;
                ctx.DrawRectangle(vb, null, newRect);
            }

            var resultSource = new RenderTargetBitmap(w, h, 96, 96, PixelFormats.Pbgra32);

            resultSource.Render(dv);

            this.HLeft  = (ushort)transformedHotspot.X;
            this.HTop   = (ushort)transformedHotspot.Y;
            this.Width  = (byte)newW;
            this.Height = (byte)newH;

            this._BitmapFrame = BitmapFrame.Create(resultSource);
            this._PngFile     = null;

            return(clipped);
        }
Beispiel #6
0
        protected override Rectangle InitializeAdornedElementImage()
        {
            Rect adornedBounds = VisualTreeHelper.GetDescendantBounds(this.AdornedElement);

            // Round the height and width of the bounds to reduce the
            // blur effect caused by the RenderTargetBitmap.
            // When drawing Text into RenderTargetBitmap, the ClearType
            // reverts to grayscale causing a blur effect. If there is
            // also an extrapolation, the blur effect will be worst.
            int roundedHeight = ( int )Math.Round(adornedBounds.Height, MidpointRounding.ToEven);
            int roundedWidth  = ( int )Math.Round(adornedBounds.Width, MidpointRounding.ToEven);

            VisualBrush brush = new VisualBrush(this.AdornedElement);

            Rectangle rectangle = new Rectangle();

            // Only if we have something to adorn
            if (this.DeepCopy &&
                ((roundedWidth > 0) && (roundedHeight > 0)))
            {
                try
                {
                    RenderTargetBitmap bitmap = new RenderTargetBitmap(roundedWidth,
                                                                       roundedHeight,
                                                                       96,
                                                                       96,
                                                                       PixelFormats.Pbgra32);

                    DrawingVisual drawingVisual = new DrawingVisual();

                    using (DrawingContext context = drawingVisual.RenderOpen())
                    {
                        Rect finalRect = new Rect(0,
                                                  0,
                                                  roundedWidth,
                                                  roundedHeight);

                        context.DrawRectangle(brush, null, finalRect);
                    }

                    bitmap.Render(drawingVisual);

                    // Ensure to set the Height and Width
                    // values for the Fill does not resize the
                    // rectangle if it is larger. This also
                    // reduce the blur effect.
                    rectangle.Height = roundedHeight;
                    rectangle.Width  = roundedWidth;
                    rectangle.UpdateLayout();

                    // Adding BitmapScallingMode using any other BitmapScalingMode cause some
                    // blur in the resulting Bitmap
                    RenderOptions.SetBitmapScalingMode(rectangle, BitmapScalingMode.NearestNeighbor);
                    rectangle.Fill = new ImageBrush(bitmap);

                    // Translate the Top Left corner of the rectangle that
                    // contains the AdornedElement
                    if (!adornedBounds.Size.IsEmpty)
                    {
                        rectangle.RenderTransform = new TranslateTransform(adornedBounds.X, adornedBounds.Y);
                    }
                }
                catch (Exception)
                {
                    // Avoid any exception and use the brush itself
                    rectangle.Fill = brush;
                }
            }
            else
            {
                rectangle.Fill = brush;
            }

            return(rectangle);
        }
Beispiel #7
0
 private void PageMediaElement_MediaOpened(object sender, RoutedEventArgs e)
 {
     Background = new VisualBrush(PageMediaElement);
     App.CastedMainWindow.MusicPlayer.Play();
     PageFrame.ShowUsingLinearAnimation();
 }
Beispiel #8
0
        /// <summary>
        /// Exporting png pictures
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TakeScreenShotButton_Click(object sender, RoutedEventArgs e)
        {
            string path              = (DataContext as ColorbarViewModel).AppConfiguration.ScreenshotDirectory;
            var    filename          = string.Empty;
            var    currentPageName   = (DataContext as ColorbarViewModel).CurrentPageName;
            var    currentRecordInfo = (DataContext as ColorbarViewModel).RecordInfo;

            try
            {
                if (path.Contains(@"MyDocuments\CapFrameX\Screenshots"))
                {
                    var documentFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                    path = Path.Combine(documentFolder, @"CapFrameX\Screenshots");
                }

                if (currentPageName == "Analysis")
                {
                    var name = "CX" + "_" +
                               DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss") + "_" + $"{currentRecordInfo.GameName}" + "_" + $"{ currentRecordInfo.Comment}.png";

                    Regex r            = new Regex(string.Format("[{0}]", Regex.Escape(REGEX_SEARCH)));
                    var   adjustedName = r.Replace(name, " ");
                    filename = Path.Combine(path, adjustedName);
                }
                else
                {
                    filename = Path.Combine(path, "CX" + "_" +
                                            DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss") + "_" + $"{currentPageName}.png");
                }

                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }

                var screenShotArea = (DataContext as ColorbarViewModel).Shell.GlobalScreenshotArea;

                if (screenShotArea == null)
                {
                    return;
                }

                VisualBrush visualBrush = new VisualBrush(screenShotArea);

                // Gets the size of the images (I assume each image has the same size)
                int imageWidth  = (int)screenShotArea.ActualWidth;
                int imageHeight = (int)screenShotArea.ActualHeight;

                // Draws the images into a DrawingVisual component
                DrawingVisual drawingVisual = new DrawingVisual();
                using (DrawingContext drawingContext = drawingVisual.RenderOpen())
                {
                    drawingContext.DrawRectangle(visualBrush, null, new Rect(new System.Windows.Point(0, 0), new System.Windows.Point(imageWidth, imageHeight)));
                }

                // Converts the Visual (DrawingVisual) into a BitmapSource
                RenderTargetBitmap rtb = new RenderTargetBitmap(
                    imageWidth, imageHeight, 96, 96, PixelFormats.Pbgra32);
                rtb.Render(drawingVisual);

                using (MemoryStream stream = new MemoryStream())
                {
                    BitmapEncoder encoder = new PngBitmapEncoder();
                    encoder.Frames.Add(BitmapFrame.Create(rtb));
                    encoder.Save(stream);

                    Bitmap bitmap = new Bitmap(stream);
                    System.Drawing.Image logoName        = (System.Drawing.Image)Properties.Resources.ResourceManager.GetObject("CX_Screen_Logo_Name");
                    System.Drawing.Image logoDescription = (System.Drawing.Image)Properties.Resources.ResourceManager.GetObject("CX_Screen_Logo_Description");


                    // Add fill rectangle
                    AddFillRectangle(bitmap, new System.Drawing.Point(0, imageHeight - logoDescription.Height),
                                     new System.Drawing.Size(imageWidth, logoDescription.Height), new SolidBrush(System.Drawing.Color.FromArgb(255, 32, 141, 228)));

                    // Add frame
                    AddRectangle(bitmap, new System.Drawing.Point(1, 1),
                                 new System.Drawing.Size(imageWidth - 2, imageHeight), new SolidBrush(System.Drawing.Color.FromArgb(255, 32, 141, 228)));

                    // Add CX logos
                    AddLogo(bitmap, logoName, new System.Drawing.Point(0, imageHeight - logoName.Height));
                    AddLogo(bitmap, logoDescription, new System.Drawing.Point(imageWidth - logoDescription.Width, imageHeight - logoDescription.Height));

                    bitmap.Save(filename);
                }
            }
            catch (Exception ex)
            {
                var logger = (DataContext as ColorbarViewModel).Logger;
                logger.LogError(ex, "Screenshot {filename} could not be created", filename);
            }
        }
Beispiel #9
0
        /// <summary>
        /// 获取合并后的图片
        /// </summary>
        /// <param name="dictionary"></param>
        /// <param name="rect"></param>
        /// <returns></returns>
        public static BitmapImage GetCombinedBitmap(this IDictionary <FrameworkElement, FrameworkElement> dictionary, Rect rect)
        {
            var animatedGifs = dictionary.Values.Select((item, index) => new { item, index }).Where(m => ((AnimatedGif)m.item).Animatable).ToArray();

            if (animatedGifs.Length == 1)
            {
                var imageWidth    = (int)rect.Width;
                var imageHeight   = (int)rect.Height;
                var relationPoint = new Point(rect.X, rect.Y);

                //动态图信息
                var animatedGif    = (AnimatedGif)animatedGifs[0].item;
                var index          = animatedGifs[0].index;
                var element        = dictionary.Keys.ElementAt(index);
                var width          = (int)Math.Round(element.Width);
                var height         = (int)Math.Round(element.Height);
                var angle          = element.GetTransform <RotateTransform>().Angle;
                var scaleTransform = element.GetTransform <ScaleTransform>();
                var scaleX         = scaleTransform.ScaleX;
                var scaleY         = scaleTransform.ScaleY;
                var gifRect        = animatedGif.GetRelationRect(relationPoint);
                var visualWidth    = (int)Math.Round(gifRect.Width);
                var visualHeight   = (int)Math.Round(gifRect.Height);


                var stream = new MemoryStream();
                using (var encoder = new GifEncoder(stream, imageWidth, imageHeight, animatedGif.RepeatCount))
                {
                    var          bitmapFrames = animatedGif.BitmapFrames;
                    var          delays = animatedGif.Delays;
                    BitmapSource cacheBottomBitmapSource = null, cacheTopBitmapSource = null;
                    if (index > 0)
                    {
                        var drawingVisual = new DrawingVisual();
                        using (var context = drawingVisual.RenderOpen())
                        {
                            for (var j = 0; j < index; j++)
                            {
                                var item    = dictionary.ElementAt(j);
                                var viewbox = item.Key.GetChildViewbox(item.Value);
                                var brush   = new VisualBrush(item.Key)
                                {
                                    ViewboxUnits = BrushMappingMode.RelativeToBoundingBox,
                                    Viewbox      = viewbox,
                                };
                                context.DrawRectangle(brush, null, item.Value.GetRelationRect(relationPoint));
                            }
                        }
                        var renderBitmap = new RenderTargetBitmap(imageWidth, imageHeight, 96, 96, PixelFormats.Pbgra32);
                        renderBitmap.Render(drawingVisual);
                        cacheBottomBitmapSource = renderBitmap;
                    }
                    if (index + 1 < dictionary.Count)
                    {
                        var drawingVisual = new DrawingVisual();
                        using (var context = drawingVisual.RenderOpen())
                        {
                            for (var j = index + 1; j < dictionary.Count; j++)
                            {
                                var item    = dictionary.ElementAt(j);
                                var viewbox = item.Key.GetChildViewbox(item.Value);
                                var brush   = new VisualBrush(item.Key)
                                {
                                    ViewboxUnits = BrushMappingMode.RelativeToBoundingBox,
                                    Viewbox      = viewbox,
                                };
                                context.DrawRectangle(brush, null, item.Value.GetRelationRect(relationPoint));
                            }
                        }
                        var renderBitmap = new RenderTargetBitmap(imageWidth, imageHeight, 96, 96, PixelFormats.Pbgra32);
                        renderBitmap.Render(drawingVisual);
                        cacheTopBitmapSource = renderBitmap;
                    }
                    var cacheRect = new Rect(0, 0, imageWidth, imageHeight);

                    for (var i = 0; i < bitmapFrames.Count; i++)
                    {
                        var drawingVisual = new DrawingVisual();
                        using (var context = drawingVisual.RenderOpen())
                        {
                            if (cacheBottomBitmapSource != null)
                            {
                                context.DrawImage(cacheBottomBitmapSource, cacheRect);
                            }
                            context.DrawRectangle(new ImageBrush(bitmapFrames[i].GetMinContainBitmap(width, height, angle, scaleX, scaleY, visualWidth, visualHeight)), null, gifRect);
                            if (cacheTopBitmapSource != null)
                            {
                                context.DrawImage(cacheTopBitmapSource, cacheRect);
                            }
                        }
                        var renderBitmap = new RenderTargetBitmap(imageWidth, imageHeight, 96, 96, PixelFormats.Pbgra32);
                        renderBitmap.Render(drawingVisual);
                        using (var frame = renderBitmap.GetBitmap())
                        {
                            encoder.AppendFrame(frame, (int)delays[i].TotalMilliseconds);
                        }
                    }
                }
                stream.Position = 0;
                var bitmapImage = new BitmapImage();
                bitmapImage.BeginInit();
                bitmapImage.StreamSource = stream;
                bitmapImage.EndInit();
                return(bitmapImage);
            }
            else
            {
                return(dictionary.GetMinContainBitmap().GetBitmapImage());
            }
        }
Beispiel #10
0
        private FrameworkElement CreateVisualChild()
        {
            MeshGeometry3D meshGeometry3D = new MeshGeometry3D()
            {
                Positions          = new Point3DCollection(Planerator.Mesh),
                TextureCoordinates = new PointCollection(Planerator.TexCoords),
                TriangleIndices    = new Int32Collection(Planerator.Indices)
            };
            Material diffuseMaterial = new DiffuseMaterial(Brushes.White);

            diffuseMaterial.SetValue(Viewport2DVisual3D.IsVisualHostMaterialProperty, (object)true);
            VisualBrush visualBrush = new VisualBrush(this._logicalChild);

            this.SetCachingForObject(visualBrush);
            Material material = new DiffuseMaterial(visualBrush);

            this._rotationTransform.Rotation = this._quaternionRotation;
            Transform3DGroup transform3DGroup = new Transform3DGroup();

            transform3DGroup.Children.Add(this._scaleTransform);
            transform3DGroup.Children.Add(this._rotationTransform);
            Transform3DGroup transform3DGroup1 = transform3DGroup;
            GeometryModel3D  geometryModel3D   = new GeometryModel3D()
            {
                Geometry     = meshGeometry3D,
                Transform    = transform3DGroup1,
                BackMaterial = material
            };
            Model3DGroup model3DGroup = new Model3DGroup();

            model3DGroup.Children.Add(new DirectionalLight(Colors.White, new Vector3D(0, 0, -1)));
            model3DGroup.Children.Add(new DirectionalLight(Colors.White, new Vector3D(0.1, -0.1, 1)));
            model3DGroup.Children.Add(geometryModel3D);
            ModelVisual3D modelVisual3D = new ModelVisual3D()
            {
                Content = model3DGroup
            };

            if (this._frontModel != null)
            {
                this._frontModel.Visual = null;
            }
            this._frontModel = new Viewport2DVisual3D()
            {
                Geometry  = meshGeometry3D,
                Visual    = this._logicalChild,
                Material  = diffuseMaterial,
                Transform = transform3DGroup1
            };
            this.SetCachingForObject(this._frontModel);
            Viewport3D viewport3D = new Viewport3D()
            {
                ClipToBounds = false
            };

            viewport3D.Children.Add(modelVisual3D);
            viewport3D.Children.Add(this._frontModel);
            this._viewport3D = viewport3D;
            this.UpdateRotation();
            return(this._viewport3D);
        }
        public static ToolTip CreateToolTip(string header, string subHeader, Control content,
                                            string decorator, bool isSymbolicDecorator = true, double hueValue = -1, bool overrideContentForeground = false,
                                            int maxWidth = 200, int padding = 3, double headerFontSize = 14)
        {
            ToolTip toolTip = new ToolTip
            {
                MaxWidth   = maxWidth,
                Padding    = new Thickness(padding),
                FontFamily = FontManager.Body,
            };

            StackPanel stackPanel = new StackPanel();

            if (!string.IsNullOrEmpty(header))
            {
                TextBlock headerTextBlock = new TextBlock
                {
                    Text          = header,
                    TextAlignment = TextAlignment.Center,
                    TextWrapping  = TextWrapping.Wrap,
                    FontFamily    = FontManager.Heading,
                    FontWeight    = FontWeights.SemiBold,
                    FontSize      = headerFontSize,
                };
                stackPanel.Children.Add(headerTextBlock);
            }

            if (!string.IsNullOrEmpty(subHeader))
            {
                TextBlock subHeaderTextBlock = new TextBlock
                {
                    Text         = subHeader,
                    TextWrapping = TextWrapping.Wrap,
                };
                stackPanel.Children.Add(subHeaderTextBlock);
            }

            if (!(string.IsNullOrEmpty(header) && string.IsNullOrEmpty(subHeader)) &&
                content != null)
            {
                stackPanel.Children.Add(new Separator());
            }

            if (content != null)
            {
                stackPanel.Children.Add(content);
            }

            if (hueValue >= 0)
            {
                Color background = Helper.GetBackgroundFromHue(hueValue);
                Color foreground = Helper.GetForegroundFromHue(hueValue);
                toolTip.Background = new SolidColorBrush(background);
                toolTip.Foreground = new SolidColorBrush(foreground);
                if (overrideContentForeground && content != null)
                {
                    content.Foreground = new SolidColorBrush(foreground);
                }
            }

            if (!string.IsNullOrEmpty(decorator))
            {
                TextBlock decoratorTextBlock = new TextBlock
                {
                    Opacity    = 0.2,
                    Text       = decorator,
                    FontFamily = isSymbolicDecorator ? FontManager.Symbol : FontManager.Body,
                };

                VisualBrush decoratorVisualBrush = new VisualBrush
                {
                    Stretch    = Stretch.Uniform,
                    AlignmentX = AlignmentX.Right,
                    AlignmentY = AlignmentY.Bottom,
                    Visual     = decoratorTextBlock
                };

                Grid decoratorGrid = new Grid
                {
                    Background = decoratorVisualBrush,
                    Margin     = new Thickness(0, 0, -15, -15),
                };

                Grid mainGrid = new Grid();
                mainGrid.Children.Add(decoratorGrid);
                mainGrid.Children.Add(stackPanel);

                toolTip.Content = mainGrid;
            }
            else
            {
                toolTip.Content = stackPanel;
            }

            return(toolTip);
        }
Beispiel #12
0
        private void shrinkListBox()
        {
            DoubleAnimation fadeOut = new DoubleAnimation()
            {
                To       = 0,
                Duration = TimeSpan.FromMilliseconds(400)
            };

            Storyboard.SetTarget(fadeOut, DevicesLB);
            Storyboard.SetTargetProperty(fadeOut, new PropertyPath(Control.OpacityProperty));
            DoubleAnimation shrinkBorder = new DoubleAnimation()
            {
                To       = 77.5,
                Duration = TimeSpan.FromMilliseconds(400)
            };

            Storyboard.SetTarget(shrinkBorder, Border1);
            Storyboard.SetTargetProperty(shrinkBorder, new PropertyPath(Control.HeightProperty));
            DoubleAnimation shrinkList = new DoubleAnimation()
            {
                To       = 77.5,
                Duration = TimeSpan.FromMilliseconds(400)
            };

            Storyboard.SetTarget(shrinkList, DevicesLB);
            Storyboard.SetTargetProperty(shrinkList, new PropertyPath(Control.HeightProperty));
            DoubleAnimation fadeIn = new DoubleAnimation()
            {
                BeginTime = TimeSpan.FromMilliseconds(400),
                To        = 1,
                Duration  = TimeSpan.FromMilliseconds(400)
            };

            Storyboard.SetTarget(fadeIn, DevicesLB);
            Storyboard.SetTargetProperty(fadeIn, new PropertyPath(Control.OpacityProperty));

            Storyboard fadeChange    = new Storyboard();
            Storyboard changed       = new Storyboard();
            Storyboard secondChanged = new Storyboard();

            fadeChange.Children.Add(fadeOut);
            changed.Children.Add(shrinkBorder);
            changed.Children.Add(shrinkList);
            secondChanged.Children.Add(fadeIn);

            fadeChange.Completed += (s, a) => {
                //Here place the data inside
                DevicesLB.ItemsSource = deviceSearched;
                for (int i = 0; i < 10; i++)
                {
                    for (int j = 0; j < 10; j++)
                    {
                        devicesMatrix[i][j].deviceCheckbox.IsChecked = false;
                    }
                }

                devicesMatrix[deviceSearched[0].xInt][deviceSearched[0].yInt].deviceCheckbox.IsChecked = true;
                changed.Begin();
            };

            changed.Completed += (s, a) =>
            {
                VisualBrush vb = new VisualBrush()
                {
                    Visual = Border2
                };
                gridListBox.OpacityMask = vb;

                secondChanged.Begin();
            };

            secondChanged.Completed += (s, a) =>
            {
                searching = false;
            };

            fadeChange.Begin();
        }
        public MyCanvas()
        {
            #region 点

            //DoubleCollection doubleCollection = new DoubleCollection();
            //doubleCollection.Add(5);
            //DashStyle dashstyle = new DashStyle();
            //dashstyle.Dashes = doubleCollection;
            //dashstyle.Offset = 2;

            //DrawingBrush drawingBrush = new DrawingBrush(
            //	new GeometryDrawing(
            //		new SolidColorBrush(Colors.Transparent),
            //		new Pen(new SolidColorBrush(Colors.Black),1)
            //		{
            //			DashStyle = dashstyle
            //		},
            //		new RectangleGeometry(
            //			new Rect(0,0,HORIZONTAL_OFFSET,VERTICAL_OFFSET)
            //			)
            //		)
            //	);

            //drawingBrush.Stretch = Stretch.None;
            //drawingBrush.TileMode = TileMode.Tile;
            //drawingBrush.Viewport = new Rect(0.0,0.0,HORIZONTAL_OFFSET,VERTICAL_OFFSET);
            //drawingBrush.ViewportUnits = BrushMappingMode.Absolute;
            //this.Background = drawingBrush;

            #endregion

            #region 线

            //LinearGradientBrush linearBrush = new LinearGradientBrush();

            //linearBrush.SpreadMethod = GradientSpreadMethod.Repeat;
            //linearBrush.StartPoint = new Point(0,0);
            //linearBrush.EndPoint = new Point(1,0);
            //linearBrush.GradientStops.Add(new GradientStop(Colors.LightGray,0.0));
            //linearBrush.GradientStops.Add(new GradientStop(Colors.LightGray,0.5));
            //linearBrush.GradientStops.Add(new GradientStop(Colors.White,0.5));
            //linearBrush.GradientStops.Add(new GradientStop(Colors.White,1.0));


            //DrawingBrush drawingBrush = new DrawingBrush(
            //	new GeometryDrawing(
            //		linearBrush,
            //		new Pen(new SolidColorBrush(Colors.Gray),1)
            //		{
            //			//DashStyle = dashstyle
            //		},
            //		new RectangleGeometry(
            //			new Rect(0,0,20,10)
            //			)
            //		)
            //	);
            //drawingBrush.Stretch = Stretch.Fill;
            //drawingBrush.TileMode = TileMode.FlipX;
            //drawingBrush.Viewbox = new Rect(0,0,20,10);
            //drawingBrush.ViewboxUnits = BrushMappingMode.Absolute;
            //drawingBrush.Viewport = new Rect(0,0,40,10);
            //drawingBrush.ViewportUnits = BrushMappingMode.Absolute;
            //this.Background = drawingBrush;

            #endregion

            #region 格子
            //this.Width = 40;
            //this.Height = 40;

            //double width = this.Width;
            //double height = this.Height;
            //bool colors = false;//false是白色,true是黑色

            //int widthCount = (int)(width / HORIZONTAL_OFFSET);
            //int heightCount = (int)(height / VERTICAL_OFFSET);

            ////长和宽双数
            //if(heightCount % 2 == 0 && widthCount % 2 == 0)
            //{
            //	for(var i = 0;i <= heightCount;i++)//行循环添加label
            //	{
            //		for(var j = 0;j <= widthCount;j++)//列循环添加label
            //		{
            //			#region 涂色
            //			if(colors == false)
            //			{
            //				Point startpoint = new Point();
            //				startpoint.X = j * 10;
            //				startpoint.Y = i * 10;

            //				Point secondpoint = new Point();
            //				secondpoint.X = j * 10 + 10;
            //				secondpoint.Y = i * 10;

            //				Point thirdpoint = new Point();
            //				thirdpoint.X = j * 10 + 10;
            //				thirdpoint.Y = i * 10 + 10;

            //				Point endpoint = new Point();
            //				endpoint.X = j * 10;
            //				endpoint.Y = i * 10 + 10;

            //				Path path = new Path();
            //				StreamGeometry streamGeomety = new StreamGeometry();
            //				StreamGeometryContext sgc = streamGeomety.Open();
            //				sgc.BeginFigure(startpoint,true,true);
            //				sgc.LineTo(secondpoint,true,true);
            //				sgc.LineTo(thirdpoint,true,true);
            //				sgc.LineTo(endpoint,true,true);
            //				sgc.Close();
            //				path.Data = streamGeomety;
            //				path.Fill = new SolidColorBrush(Colors.White);
            //				path.Stroke = new SolidColorBrush(Colors.White);
            //				path.StrokeThickness = 1;
            //				this.Children.Add(path);
            //				SetLeft(path,0);
            //				SetTop(path,0);
            //				colors = true;
            //			}
            //			else if(colors == true)
            //			{
            //				Point startpoint = new Point();
            //				startpoint.X = j * 10;
            //				startpoint.Y = i * 10;

            //				Point secondpoint = new Point();
            //				secondpoint.X = j * 10 + 10;
            //				secondpoint.Y = i * 10;

            //				Point thirdpoint = new Point();
            //				thirdpoint.X = j * 10 + 10;
            //				thirdpoint.Y = i * 10 + 10;

            //				Point endpoint = new Point();
            //				endpoint.X = j * 10;
            //				endpoint.Y = i * 10 + 10;

            //				Path path = new Path();
            //				StreamGeometry streamGeomety = new StreamGeometry();
            //				StreamGeometryContext sgc = streamGeomety.Open();
            //				sgc.BeginFigure(startpoint,true,true);
            //				sgc.LineTo(secondpoint,true,true);
            //				sgc.LineTo(thirdpoint,true,true);
            //				sgc.LineTo(endpoint,true,true);
            //				sgc.Close();
            //				path.Data = streamGeomety;
            //				path.Fill = new SolidColorBrush(Colors.Gray);
            //				path.Stroke = new SolidColorBrush(Colors.Gray);
            //				path.StrokeThickness = 1;
            //				this.Children.Add(path);
            //				SetLeft(path,0);
            //				SetTop(path,0);
            //				colors = false;
            //			}
            //			#endregion
            //		}
            //	}
            //}


            #endregion

            #region 新格子

            //Grid grid = new Grid();

            //grid.Width = 20;
            //grid.Height = 20;

            //RowDefinition rd1 = new RowDefinition();
            //rd1.Height = new GridLength(1,GridUnitType.Star);

            //RowDefinition rd2 = new RowDefinition();
            //rd2.Height = new GridLength(1,GridUnitType.Star);

            //ColumnDefinition cd1 = new ColumnDefinition();
            //cd1.Width = new GridLength(1,GridUnitType.Star);

            //ColumnDefinition cd2 = new ColumnDefinition();
            //cd2.Width = new GridLength(1,GridUnitType.Star);

            //grid.RowDefinitions.Add(rd1);
            //grid.RowDefinitions.Add(rd2);
            //grid.ColumnDefinitions.Add(cd1);
            //grid.ColumnDefinitions.Add(cd2);

            //for(int i = 0;i < grid.RowDefinitions.Count;i++)
            //{
            //	for(int j = 0;j < grid.ColumnDefinitions.Count;j++)
            //	{
            //		if((i == 0 && j ==0) ||(i == 1 && j == 1))
            //		{
            //			Rectangle rect = new Rectangle();
            //			rect.Fill = new SolidColorBrush(Colors.White);
            //			grid.Children.Add(rect);
            //			Grid.SetRow(rect,i);
            //			Grid.SetColumn(rect,j);
            //		}
            //		else
            //		{
            //			Rectangle rect = new Rectangle();
            //			rect.Fill = new SolidColorBrush(Colors.LightGray);
            //			grid.Children.Add(rect);
            //			Grid.SetRow(rect,i);
            //			Grid.SetColumn(rect,j);
            //		}
            //	}
            //}

            //VisualBrush visualbrush = new VisualBrush(grid);

            //DrawingBrush drawingBrush = new DrawingBrush(
            //	new GeometryDrawing(
            //		visualbrush,
            //		new Pen(new SolidColorBrush(Colors.Gray),double.NaN)
            //		{
            //						//DashStyle = dashstyle
            //					},
            //		new RectangleGeometry(
            //			new Rect(0,0,20,20)
            //			)
            //		)
            //	);
            //drawingBrush.Stretch = Stretch.Fill;
            //drawingBrush.TileMode = TileMode.Tile;
            //drawingBrush.Viewbox = new Rect(0,0,20,20);
            //drawingBrush.ViewboxUnits = BrushMappingMode.Absolute;
            //drawingBrush.Viewport = new Rect(0,0,20,20);
            //drawingBrush.ViewportUnits = BrushMappingMode.Absolute;
            //this.Background = drawingBrush;

            #endregion

            #region 飞镖

            //Grid grid = NewDart.GetNewDart();

            //VisualBrush visualbrush = new VisualBrush(grid);

            //DrawingBrush drawingBrushAll = new DrawingBrush(
            //	new GeometryDrawing(
            //		visualbrush,
            //		new Pen(new SolidColorBrush(Colors.Gray),double.NaN)
            //		{
            //			//DashStyle = dashstyle
            //		},
            //		new RectangleGeometry(
            //			new Rect(0,0,10,10)
            //			)
            //		)
            //	);
            //drawingBrushAll.Stretch = Stretch.Fill;
            //drawingBrushAll.TileMode = TileMode.Tile;
            //drawingBrushAll.Viewbox = new Rect(0,0,10,10);
            //drawingBrushAll.ViewboxUnits = BrushMappingMode.Absolute;
            //drawingBrushAll.Viewport = new Rect(0,0,10,10);
            //drawingBrushAll.ViewportUnits = BrushMappingMode.Absolute;
            //this.Background = drawingBrushAll;

            #endregion

            #region 真正的点

            Grid grid = NewPoint.GetNewPoint();

            VisualBrush visualbrush = new VisualBrush(grid);

            DrawingBrush drawingBrushAll = new DrawingBrush(
                new GeometryDrawing(
                    visualbrush,
                    new Pen(new SolidColorBrush(Colors.Gray), double.NaN)
            {
                //DashStyle = dashstyle
            },
                    new RectangleGeometry(
                        new Rect(0, 0, 10, 10)
                        )
                    )
                );
            drawingBrushAll.Stretch       = Stretch.Fill;
            drawingBrushAll.TileMode      = TileMode.Tile;
            drawingBrushAll.Viewbox       = new Rect(0, 0, 10, 10);
            drawingBrushAll.ViewboxUnits  = BrushMappingMode.Absolute;
            drawingBrushAll.Viewport      = new Rect(0, 0, 10, 10);
            drawingBrushAll.ViewportUnits = BrushMappingMode.Absolute;
            this.Background = drawingBrushAll;

            #endregion
        }
Beispiel #14
0
 public PageItem(PageItem pageItem)
 {
     _pageContent = pageItem.PageContent;
     _fixedPage   = pageItem.FixedPage;
     _pageBrush   = new VisualBrush(_fixedPage);
 }
Beispiel #15
0
 public PageItem(PageContent pageContent)
 {
     _pageContent = pageContent;
     _fixedPage   = _pageContent.GetPageRoot(false);
     _pageBrush   = new VisualBrush(_fixedPage);
 }
Beispiel #16
0
        private void AdjustViewport(FrameworkElement container, VisualBrush prevBrush, VisualBrush nextBrush)
        {
            // Adjusting the positions according to the Container's Width/Height
            double aspect = container.ActualWidth / container.ActualHeight;

            _flipModelContainer.Children.Add(PrepareFace(prevBrush, nextBrush, aspect));

            // Camera
            AdjustCamera(aspect);

            //adjust the transforms and the visual to move
            AdjustTransformsAndVisual(aspect, nextBrush);
        }
        private UIElement GenerateItem(int row, int column, Color color, int index)
        {
            var rectangle = new Rectangle();

            rectangle.Fill = new SolidColorBrush(color);

            if (Size.GridUnitType == GridUnitType.Pixel)
            {
                rectangle.Height = Size.Value;
                rectangle.Width  = Size.Value;
            }
            else
            {
                rectangle.Height = 16;
                rectangle.Width  = 16;
            }

            var border = new Border();

            border.Margin          = ColorPadding;
            border.BorderThickness = new Thickness(1);
            border.BorderBrush     = new SolidColorBrush(SWM.Colors.Black);
            border.Width           = rectangle.Width;
            border.Height          = rectangle.Height;

            border.Child = rectangle;

            var focusBorder = new FocusableBorder();

            focusBorder.Child     = border;
            focusBorder.Focusable = true;
            focusBorder.Padding   = new Thickness(1);

            var dashBorderBrush = new VisualBrush();
            var dashVisual      = new Rectangle();

            dashVisual.StrokeDashArray = new DoubleCollection(new double[] { 4, 2 });
            dashVisual.Stroke          = new SolidColorBrush(SWM.Colors.Gray);
            dashVisual.StrokeThickness = 1;

            dashBorderBrush.Visual = dashVisual;

            focusBorder.GotFocus  += (s, a) => focusBorder.BorderBrush = dashBorderBrush;
            focusBorder.LostFocus += (s, a) => focusBorder.BorderBrush = new SolidColorBrush(SWM.Colors.Transparent);

            focusBorder.BorderBrush = new SolidColorBrush(SWM.Colors.Transparent);

            AutomationProperties.SetHelpText(focusBorder, GetColorHelpText(color));

            focusBorder.MouseDown += (s, a) => ColorSelected?.Invoke(this, new ColorPalleteSelectedArgs(color, index));
            focusBorder.KeyDown   += (s, a) =>
            {
                if (a.Key == System.Windows.Input.Key.Enter)
                {
                    ColorSelected?.Invoke(this, new ColorPalleteSelectedArgs(color, index));
                }
            };

            Grid.SetColumn(focusBorder, column);
            Grid.SetRow(focusBorder, row);

            return(focusBorder);
        }
Beispiel #18
0
        /*
         *      FUNCTION SAVES CANVAS TO PNG
         *          the following function will save a png from a selected path from the user
         *          used libraries:
         *              -Rect
         *              -RenderTargetBitmap
         *              -DrawingVisual
         *              -VisualBrush
         *              -DialogResult
         */
        private void SaveMazeToPNG(object sender, RoutedEventArgs e)
        {
            if (this.createdMaze)
            {
                //rendering the canvas to png file
                Rect bounds            = VisualTreeHelper.GetDescendantBounds(canvas);
                RenderTargetBitmap rtb = new RenderTargetBitmap((Int32)bounds.Width, (Int32)bounds.Height, 96, 96, PixelFormats.Pbgra32);
                DrawingVisual      dv  = new DrawingVisual();
                using (DrawingContext dc = dv.RenderOpen())
                {
                    VisualBrush vb = new VisualBrush(canvas);
                    dc.DrawRectangle(vb, null, new Rect(new Point(), bounds.Size));
                }
                rtb.Render(dv);

                // PNG encoder
                PngBitmapEncoder png = new PngBitmapEncoder();
                png.Frames.Add(BitmapFrame.Create(rtb));

                //asking the user for directory path
                using (var fbd = new FolderBrowserDialog())
                {
                    DialogResult result = fbd.ShowDialog();
                    if (result == DialogResult.OK && !string.IsNullOrWhiteSpace(fbd.SelectedPath))
                    {
                        try
                        {
                            //fdb is the folder selected by the user
                            string directory = fbd.SelectedPath + "\\maze.png";

                            //if file exists change name by adding a number
                            if (File.Exists(directory))
                            {
                                int i = 1;
                                do
                                {
                                    directory = fbd.SelectedPath + "\\maze" + i + ".png";
                                    i++;
                                } while (File.Exists(directory));
                            }

                            //finally saving the file
                            using (var save = File.OpenWrite(directory))
                            {
                                png.Save(save);
                                save.Close();
                            }
                            //confirmation of file exported
                            System.Windows.MessageBox.Show("Exported @ " + fbd.SelectedPath, "Done");
                        }
                        catch //file has not been saved?
                        {
                            System.Windows.MessageBox.Show("Not allowed to export\n" + fbd.SelectedPath, "Not Allow");
                        }
                    }
                }
            }
            else //if there is not a maze in the canvas
            {
                System.Windows.MessageBox.Show("You are not allow to store a maze if have not generated one yet.", "Not Allow");
            }
        }
Beispiel #19
0
        /// <summary>
        /// Gets a render of the current UIElement
        /// </summary>
        /// <param name="source">UIElement to screenshot</param>
        /// <param name="scale">The scale of the screen.</param>
        /// <param name="dpi">The DPI of the output.</param>
        /// <param name="size">The size of the destination image.</param>
        /// <returns>An ImageSource</returns>
        public static RenderTargetBitmap GetScaledRender(this UIElement source, double scale, double dpi, System.Windows.Size size)
        {
            var bounds = VisualTreeHelper.GetDescendantBounds(source);

            //var width = (bounds.Width + bounds.X) * scale;
            //var height = (bounds.Height + bounds.Y) * scale;

            #region If no bounds

            if (bounds.IsEmpty)
            {
                var control = source as FrameworkElement;

                if (control != null)
                {
                    bounds = new Rect(new System.Windows.Point(0d, 0d), new System.Windows.Point(control.ActualWidth * scale, control.ActualHeight * scale));
                }
            }

            #endregion

            var rtb = new RenderTargetBitmap((int)Math.Round(size.Width), (int)Math.Round(size.Height), dpi, dpi, PixelFormats.Pbgra32);

            //source.Clip = new RectangleGeometry(new Rect(0, 0, rtb.Width, rtb.Height));
            //source.ClipToBounds = true;

            var dv = new DrawingVisual();

            using (var ctx = dv.RenderOpen())
            {
                var vb = new VisualBrush(source)
                {
                    AutoLayoutContent = false,
                    Stretch           = Stretch.Fill
                };

                //Test with high dpi.
                //For some reason, an InkCanvas with Strokes going beyond the bounds will report a strange bound even if clipped.
                if (bounds.Width > size.Width)
                {
                    bounds.Width = size.Width;
                }

                if (bounds.Height > size.Height)
                {
                    bounds.Height = size.Height;
                }

                if (bounds.X < 0)
                {
                    bounds.X = 0;
                }

                if (bounds.Y < 0)
                {
                    bounds.Y = 0;
                }

                var locationRect = new System.Windows.Point(bounds.X * scale, bounds.Y * scale);
                var sizeRect     = new System.Windows.Size(bounds.Width * scale, bounds.Height * scale);

                ctx.DrawRectangle(vb, null, new Rect(locationRect, sizeRect));
            }

            rtb.Render(dv);

            //source.Clip = null;

            return((RenderTargetBitmap)rtb.GetAsFrozen());
        }
Beispiel #20
0
        private void loadTheme(string themeName)
        {
            updateMs = (int)Math.Round(1000 / (double)SharedData.settings.UpdateFPS);
            overlayUpdateTimer.Interval = new TimeSpan(0, 0, 0, 0, updateMs);

            // web timing
            SharedData.webError = "";
            SharedData.web      = new webTiming(SharedData.settings.WebTimingUrl);

            /*
             * for (int i = 0; i < SharedData.webUpdateWait.Length; i++)
             * {
             *  SharedData.webUpdateWait[i] = true;
             * }
             */
            // disable overlay update
            SharedData.runOverlay = false;

            SharedData.theme = new Theme(themeName);

            SharedData.theme.readExternalData();

            canvas.Children.Clear();

            objects           = new Canvas[SharedData.theme.objects.Length];
            labels            = new Label[SharedData.theme.objects.Length][];
            images            = new Image[SharedData.theme.images.Length];
            tickers           = new Canvas[SharedData.theme.tickers.Length];
            tickerLabels      = new Label[SharedData.theme.tickers.Length][];
            tickerHeaders     = new Label[SharedData.theme.tickers.Length];
            tickerFooters     = new Label[SharedData.theme.tickers.Length];
            tickerStackpanels = new StackPanel[SharedData.theme.tickers.Length];
            tickerRowpanels   = new StackPanel[SharedData.theme.tickers.Length][];
            videos            = new MediaElement[SharedData.theme.videos.Length];
            videoBoxes        = new Rectangle[SharedData.theme.videos.Length];
            videoBrushes      = new VisualBrush[SharedData.theme.videos.Length];
            sounds            = new MediaPlayer[SharedData.theme.sounds.Length];

            tickerAnimations       = new ThicknessAnimation[SharedData.theme.tickers.Length];
            tickerStoryboards      = new Storyboard[SharedData.theme.tickers.Length];
            tickerScrolls          = new Canvas[SharedData.theme.tickers.Length];
            SharedData.tickerReady = new Boolean[SharedData.theme.tickers.Length];

            SharedData.lastPage = new Boolean[SharedData.theme.objects.Length];

            // create images
            for (int i = 0; i < SharedData.theme.images.Length; i++)
            {
                images[i] = new Image();
                loadImage(images[i], SharedData.theme.images[i]);

                /*
                 * images[i].Width = SharedData.theme.width;
                 * images[i].Height = SharedData.theme.height;
                 */
                images[i].Visibility = System.Windows.Visibility.Hidden;
                canvas.Children.Add(images[i]);
                Canvas.SetZIndex(images[i], SharedData.theme.images[i].zIndex);
            }

            // create videos
            for (int i = 0; i < SharedData.theme.videos.Length; i++)
            {
                videos[i] = new MediaElement();
                videos[i].LoadedBehavior = MediaState.Manual;
                if (File.Exists(Directory.GetCurrentDirectory() + "\\" + SharedData.theme.path + "\\" + SharedData.theme.videos[i].filename))
                {
                    videos[i].Source = new Uri(Directory.GetCurrentDirectory() + "\\" + SharedData.theme.path + "\\" + SharedData.theme.videos[i].filename);
                }
                else
                {
                    MessageBox.Show("Could not load video \"" + Directory.GetCurrentDirectory() + "\\" + SharedData.theme.path + "\\" + SharedData.theme.videos[i].filename + "\"");
                }

                videoBrushes[i]        = new VisualBrush();
                videoBrushes[i].Visual = videos[i];

                videoBoxes[i]      = new Rectangle();
                videoBoxes[i]      = new System.Windows.Shapes.Rectangle();
                videoBoxes[i].Fill = videoBrushes[i];

                // width
                if (SharedData.theme.videos[i].width == 0)
                {
                    videoBoxes[i].Width = SharedData.theme.width;
                }
                else
                {
                    videoBoxes[i].Width = SharedData.theme.videos[i].width;
                }

                // height
                if (SharedData.theme.videos[i].height == 0)
                {
                    videoBoxes[i].Height = SharedData.theme.height;
                }
                else
                {
                    videoBoxes[i].Height = SharedData.theme.videos[i].height;
                }

                Thickness videoMargin = new Thickness();

                // left
                if (SharedData.theme.videos[i].left != 0)
                {
                    videoMargin.Left = SharedData.theme.videos[i].left;
                }

                // top
                if (SharedData.theme.videos[i].top != 0)
                {
                    videoMargin.Top = SharedData.theme.videos[i].top;
                }

                videoBoxes[i].Margin     = videoMargin;
                videoBoxes[i].Visibility = System.Windows.Visibility.Hidden;

                canvas.Children.Add(videoBoxes[i]);
                Canvas.SetZIndex(videoBoxes[i], SharedData.theme.videos[i].zIndex);
            }

            // create sounds
            for (int i = 0; i < SharedData.theme.sounds.Length; i++)
            {
                sounds[i] = new MediaPlayer();
                //sounds[i].LoadedBehavior = MediaState.Manual;
                if (File.Exists(Directory.GetCurrentDirectory() + "\\" + SharedData.theme.path + "\\" + SharedData.theme.sounds[i].filename))
                {
                    sounds[i].Open(new Uri(Directory.GetCurrentDirectory() + "\\" + SharedData.theme.path + "\\" + SharedData.theme.sounds[i].filename));
                }
                else
                {
                    MessageBox.Show("Could not load sound \"" + Directory.GetCurrentDirectory() + "\\" + SharedData.theme.path + "\\" + SharedData.theme.sounds[i].filename + "\"");
                }
            }

            // create objects
            for (int i = 0; i < SharedData.theme.objects.Length; i++)
            {
                // init canvas
                objects[i]              = new Canvas();
                objects[i].Margin       = new Thickness(SharedData.theme.objects[i].left, SharedData.theme.objects[i].top, 0, 0);
                objects[i].Width        = SharedData.theme.objects[i].width;
                objects[i].Height       = SharedData.theme.objects[i].height;
                objects[i].ClipToBounds = true;

                // create labels
                if (SharedData.theme.objects[i].dataset == Theme.dataset.standing ||
                    SharedData.theme.objects[i].dataset == Theme.dataset.points)
                {
                    labels[i] = new Label[SharedData.theme.objects[i].labels.Length * SharedData.theme.objects[i].itemCount];

                    for (int j = 0; j < SharedData.theme.objects[i].labels.Length; j++) // items
                    {
                        // fix top preaddition
                        //SharedData.theme.objects[i].labels[j].top -= SharedData.theme.objects[i].itemSize;
                        for (int k = 0; k < SharedData.theme.objects[i].itemCount; k++) // subitems
                        {
                            Theme.LabelProperties label = Theme.setLabelPosition(SharedData.theme.objects[i], SharedData.theme.objects[i].labels[j], k);
                            //SharedData.theme.objects[i].labels[j].top += SharedData.theme.objects[i].itemSize;
                            labels[i][(j * SharedData.theme.objects[i].itemCount) + k] = DrawLabel(label);
                            objects[i].Children.Add(labels[i][(j * SharedData.theme.objects[i].itemCount) + k]);
                        }
                    }
                }
                else
                {
                    labels[i] = new Label[SharedData.theme.objects[i].labels.Length];

                    for (int j = 0; j < SharedData.theme.objects[i].labels.Length; j++)
                    {
                        labels[i][j] = DrawLabel(SharedData.theme.objects[i].labels[j]);
                        objects[i].Children.Add(labels[i][j]);
                    }
                }

                objects[i].Visibility = System.Windows.Visibility.Hidden;
                canvas.Children.Add(objects[i]);
                Canvas.SetZIndex(objects[i], SharedData.theme.objects[i].zIndex);

                /*
                 *
                 * if (Properties.Settings.Default.ShowBorders)
                 * {
                 *  objects[i].BorderBrush = System.Windows.Media.Brushes.LightGreen;
                 *  objects[i].BorderThickness = new Thickness(1);
                 * }*/
            }

            // create tickers
            for (int i = 0; i < SharedData.theme.tickers.Length; i++)
            {
                // init canvas
                tickers[i]              = new Canvas();
                tickers[i].Margin       = new Thickness(SharedData.theme.tickers[i].left, SharedData.theme.tickers[i].top, 0, 0);
                tickers[i].Width        = SharedData.theme.tickers[i].width;
                tickers[i].Height       = SharedData.theme.tickers[i].height;
                tickers[i].ClipToBounds = true;

                tickerScrolls[i] = new Canvas();

                tickerStackpanels[i] = new StackPanel();

                tickerAnimations[i] = new ThicknessAnimation();
                Timeline.SetDesiredFrameRate(tickerAnimations[i], SharedData.settings.UpdateFPS);

                tickerStoryboards[i] = new Storyboard();

                tickers[i].Visibility = System.Windows.Visibility.Hidden;
                canvas.Children.Add(tickers[i]);
                Canvas.SetZIndex(tickers[i], SharedData.theme.tickers[i].zIndex);

                tickers[i].Children.Add(tickerScrolls[i]);

                tickerHeaders[i] = new Label();
                tickerFooters[i] = new Label();
            }

            // XSplit
            Type xsplitType = Type.GetType("XSplit.Wpf.TimedBroadcasterPlugin");

            if (xsplitType != null)
            {
                XSplit.Wpf.TimedBroadcasterPlugin xsplit = XSplit.Wpf.TimedBroadcasterPlugin.CreateInstance("415CD379-CD8A-4D88-A06C-D238FB38DF6A", canvas, SharedData.settings.OverlayW, SharedData.settings.OverlayH, (int)(1000 / SharedData.settings.UpdateFPS));

                if (xsplit != null)
                {
                    xsplit.StartTimer();
                }
            }
        }
        private void RecreateTargetModel()
        {
            MainViewport.Children.Clear();

            Visual3D targetModelVisual3D;

            // Setup VisualBrush as the material for the model
            var visualBrush = new VisualBrush(DrawingCanvas);
            var material    = new DiffuseMaterial(visualBrush);


            if (HeightMapModelTypeRadioButton.IsChecked ?? false)
            {
                var heightMapVisual3D = new Ab3d.Visuals.HeightMapVisual3D()
                {
                    Size                = new Size3D(100, 50, 100),
                    IsWireframeShown    = false,
                    IsSolidSurfaceShown = true,
                    Material            = material,
                    BackMaterial        = new DiffuseMaterial(Brushes.DimGray)
                };

                // Create height data from bitmap
                string      heightMapFileName = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Resources\\HeightMaps\\simpleHeightMap.png");
                BitmapImage heightImage       = new BitmapImage(new Uri(heightMapFileName, UriKind.RelativeOrAbsolute));

                double[,] heightData = Ab3d.PowerToys.Samples.Objects3D.HeightMapSample.OpenHeightMapDataFile(heightImage, invertData: false);

                if (heightData != null)
                {
                    heightMapVisual3D.HeightData = heightData;
                }

                targetModelVisual3D = heightMapVisual3D;
            }
            else if (BoxModelTypeRadioButton.IsChecked ?? false)
            {
                var boxVisual3D = new Ab3d.Visuals.BoxVisual3D()
                {
                    Size     = new Size3D(100, 50, 100),
                    Material = material
                };

                targetModelVisual3D = boxVisual3D;
            }
            else //if (SphereModelTypeRadioButton.IsChecked ?? false)
            {
                var sphereVisual3D = new Ab3d.Visuals.SphereVisual3D()
                {
                    Radius   = 40,
                    Material = material
                };

                targetModelVisual3D = sphereVisual3D;
            }

            MainViewport.Children.Add(targetModelVisual3D);

            // With clearing all childen we have also removed the camera's light.
            // Refresh the camera now to recreate the light
            Camera1.Refresh();

            SetupMouseEventHandlers(targetModelVisual3D);
        }
Beispiel #22
0
        /// <summary>
        /// Rotates this <see cref="PngFrame"/> with a given rotation angle.
        /// </summary>
        /// <param name="rotationDegrees">Rotation angle in degrees.</param>
        /// <param name="scalingMode"><see cref="BitmapScalingMode"/> used for rendering the rotated frame. Defaults to <see cref="BitmapScalingMode.NearestNeighbor"/>.</param>
        /// <exception cref="InvalidOperationException" />
        /// <exception cref="ArgumentException" />
        /// <exception cref="NotSupportedException" />
        public void RotateFrame(double rotationDegrees, BitmapScalingMode scalingMode = BitmapScalingMode.NearestNeighbor)
        {
            var rotationRad = rotationDegrees / 180.0 * Math.PI;

            var frame = this.BitmapFrame;

            var transform = new RotateTransform(rotationDegrees);
            var w         = frame.PixelWidth;
            var h         = frame.PixelHeight;

            var newW = (int)(Math.Abs(w * Math.Sin(rotationRad)) + Math.Abs(h * Math.Cos(rotationRad)));
            var newH = (int)(Math.Abs(w * Math.Cos(rotationRad)) + Math.Abs(h * Math.Sin(rotationRad)));

            if (newW > 256)
            {
                throw new InvalidOperationException(nameof(this.Width) + " is too big to be rotated.");
            }
            if (newH > 256)
            {
                throw new InvalidOperationException(nameof(this.Height) + " is too big to be rotated.");
            }

            transform.CenterX = w / 2;
            transform.CenterY = h / 2;

            var transformGroup = new TransformGroup();

            transformGroup.Children.Add(transform);
            transformGroup.Children.Add(new TranslateTransform((newW - w) / 2.0, (newH - h) / 2));

            var origHotspot        = new Point(this.HLeft, this.HTop);
            var transformedHotspot = transformGroup.Transform(origHotspot);

            var image = new Image()
            {
                Source              = frame,
                RenderTransform     = transformGroup,
                Width               = w,
                Height              = h,
                Stretch             = Stretch.None,
                UseLayoutRounding   = false,
                SnapsToDevicePixels = false,
            };

            RenderOptions.SetBitmapScalingMode(image, scalingMode);
            image.Arrange(new Rect(0, 0, w, h));
            var newRect = new Rect(0, 0, newW, newH);

            var dv = new DrawingVisual();

            using (var ctx = dv.RenderOpen())
            {
                var vb = new VisualBrush(image);
                vb.TileMode     = TileMode.None;
                vb.ViewboxUnits = BrushMappingMode.Absolute;
                vb.Viewbox      = newRect;
                ctx.DrawRectangle(vb, null, newRect);
            }

            var resultSource = new RenderTargetBitmap(newW, newH, 96, 96, PixelFormats.Pbgra32);

            resultSource.Render(dv);

            this.HLeft  = (ushort)transformedHotspot.X;
            this.HTop   = (ushort)transformedHotspot.Y;
            this.Width  = (byte)newW;
            this.Height = (byte)newH;

            this._BitmapFrame = BitmapFrame.Create(resultSource);
            this._PngFile     = null;
        }
Beispiel #23
0
        /// <summary>
        /// Plate変更時に呼び出される。板の初期化処理を行う
        /// </summary>
        /// <param name="oldValue"></param>
        private void OnPlateChanged(MassPlate oldValue = null)
        {
            if (oldValue != null)
            {
                oldValue.PositionUpdated -= this.Plate_PositionUpdated;
            }

            if (this.Plate == null)
            {
                return;
            }

            var dx = this.Plate.DivisionX - 1;
            var dy = this.Plate.DivisionY - 1;

            var points      = new Point3DCollection {
            };
            var indices     = new Int32Collection {
            };
            var coordinates = new PointCollection {
            };

            Brush brush = new VisualBrush
            {
                Visual = new Image
                {
                    Source = this.Plate.TextureImage,
                },
            };

            RenderOptions.SetCachingHint(brush, CachingHint.Cache);

            this.AssociatedObject.Geometry = new MeshGeometry3D
            {
                Positions          = points,
                TriangleIndices    = indices,
                TextureCoordinates = coordinates,
            };
            this.AssociatedObject.Material = new DiffuseMaterial
            {
                Brush = brush,
            };

            // Coordinateの配列を作成
            for (int y = 0; y < dy + 1; y++)
            {
                for (int x = 0; x < dx + 1; x++)
                {
                    coordinates.Add(new Point((double)x / dx, 1 - (double)y / dy));
                }
            }
            // 矩形の真ん中に置く頂点を作成
            for (int y = 0; y < dy; y++)
            {
                for (int x = 0; x < dx; x++)
                {
                    coordinates.Add(new Point((x + 0.5) / dx,
                                              1 - (y + 0.5) / dy));
                }
            }

            // Indicesの配列を作成
            for (int y = 0; y < dy; y++)
            {
                for (int x = 0; x < dx; x++)
                {
                    var leftTop     = y * (dx + 1) + x;
                    var rightTop    = leftTop + 1;
                    var leftBottom  = leftTop + (dx + 1);
                    var rightBottom = leftBottom + 1;
                    var center      = (dy + 1) * (dx + 1) + y * dx + x;
                    indices.Add(leftTop);
                    indices.Add(rightTop);
                    indices.Add(center);
                    indices.Add(rightTop);
                    indices.Add(rightBottom);
                    indices.Add(center);
                    indices.Add(rightBottom);
                    indices.Add(leftBottom);
                    indices.Add(center);
                    indices.Add(leftBottom);
                    indices.Add(leftTop);
                    indices.Add(center);
                }
            }
            // (頂点座標はアニメーションフレーム更新ごとに設定されるので今は設定不要)

            this.Plate.PositionUpdated += this.Plate_PositionUpdated;
        }
Beispiel #24
0
        /// <summary>
        /// Builds a PdfTilingPattern pattern from a visual brush.
        /// </summary>
        public static PdfTilingPattern BuildFromVisualBrush(DocumentRenderingContext context, VisualBrush brush, XMatrix transform)
        {
            TilingPatternBuilder builder    = new TilingPatternBuilder(context);
            PdfTilingPattern     pdfPattern = builder.BuildPattern(brush, transform);

            return(pdfPattern);
        }
Beispiel #25
0
 protected override void OnUpdateStepRepeaterControl(Rectangle control, VisualBrush brush, double stepSize)
 {
     brush.Viewport = new Rect(0, 0, stepSize, GetHeight());
     control.Margin = new Thickness(stepSize, 0, 0, 0);
 }
Beispiel #26
0
        public static bool ImageSave(FrameworkElement inkCanvas, string fileName = null)
        {
            if (fileName == null)
            {
                var ofd = new SaveFileDialog {
                    DefaultExt = ".jpg", Filter = "jpg file|*.jpg"
                };

                if (ofd.ShowDialog() == true)
                {
                    fileName = ofd.FileName;
                }
                if (fileName == null)
                {
                    return(false);
                }
            }

            try
            {
                int ratio = 1;

                var width  = (int)Math.Round(inkCanvas.ActualWidth * ratio);
                var height = (int)Math.Round(inkCanvas.ActualHeight * ratio);


                if (inkCanvas != null)
                {
                    if (!Double.IsNaN(inkCanvas.Width))
                    {
                        width = (int)inkCanvas.Width;
                    }
                    if (!Double.IsNaN(inkCanvas.Height))
                    {
                        height = (int)inkCanvas.Height;
                    }
                }

                Size size = new Size(width, height);
                inkCanvas.Measure(size);
                inkCanvas.Arrange(new Rect(size));


                var bmpCopied = new RenderTargetBitmap(width, height, 96, 96, PixelFormats.Default);
                var dv        = new DrawingVisual();
                using (DrawingContext dc = dv.RenderOpen())
                {
                    var vb = new VisualBrush(inkCanvas)
                    {
                        Stretch = Stretch.Fill
                    };
                    dc.DrawRectangle(vb, null, new Rect(new Point(), new Size(width, height)));
                }
                bmpCopied.Render(dv);
                using (var file = new FileStream(fileName, FileMode.Create, FileAccess.Write))
                {
                    var encoder = new JpegBitmapEncoder();
                    encoder.Frames.Add(BitmapFrame.Create(bmpCopied));
                    encoder.Save(file);
                    return(true);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                return(false);
            }
        }
Beispiel #27
0
        Visual CreateFillVisualBrush()
        {
            DrawingContext dc;
            DrawingVisual  dv = PrepareDrawingVisual(out dc);

            Rect  box    = new Rect(5, 5, BoxWidth - 10, BoxHeight - 10);
            Point center = new Point(110, 70);
            //double radiusX = BoxWidth / 2 - 5;
            //double radiusY = BoxHeight / 2 - 5;
            VisualBrush brush;

            DrawingVisual  visual = new DrawingVisual();
            DrawingContext vdc    = visual.RenderOpen();

            vdc.DrawRectangle(Brushes.GhostWhite, null, new Rect(0, 0, box.Width, box.Height));

            //vdc.DrawRectangle(Brushes.GhostWhite, null, new Rect(50, 50, 30, 30));
            vdc.DrawLine(new Pen(Brushes.Red, 3), new Point(20, 20), new Point(70, 70));
            vdc.DrawLine(new Pen(Brushes.DarkGreen, 1), new Point(0, 0), new Point(box.Width, box.Height));
            vdc.DrawLine(new Pen(Brushes.DarkGreen, 1), new Point(0, box.Height), new Point(box.Width, 0));

            //dc.DrawLine(new Pen(Brushes.Red, 3), new Point(WidthInPU, 0), new Point(0, HeightInPU));
            vdc.Close();

            //BeginBox(dc, 1, BoxOptions.Tile);
            //brush = new LinearGradientBrush(Colors.DarkBlue, Colors.Orange, 0);
            //dc.DrawEllipse(brush, null, center, radiusX, radiusY);
            //EndBox(dc);

            BeginBox(dc, 1, BoxOptions.Tile, "visual...");
            brush         = new VisualBrush(visual);
            brush.Opacity = 0.75;
            //dc.DrawEllipse(brush, null, center, radiusX, radiusY);
            dc.DrawRectangle(brush, null, box);

            //dc.DrawRectangle(brush, null, new Rect(5, 5, BoxWidth - 10, BoxHeight - 10));
            EndBox(dc);

            //BeginBox(dc, 2, BoxOptions.Box, "TileMode.Tile");
            //brush = new VisualBrush(visual);
            //brush.TileMode = TileMode.Tile;
            //dc.DrawRectangle(brush, null, new Rect(0, 0, BoxWidth, BoxHeight));
            //EndBox(dc);

            //BeginBox(dc, 3, BoxOptions.Tile);
            //brush = new LinearGradientBrush(Color.FromArgb(255, 255, 0, 0), Color.FromArgb(128, 0, 0, 255), 0);
            //dc.DrawEllipse(brush, null, center, radiusX, radiusY);
            //EndBox(dc);

            //BeginBox(dc, 4, BoxOptions.Tile);
            //brush = new LinearGradientBrush(Color.FromArgb(255, 255, 0, 0), Color.FromArgb(128, 0, 0, 255), -45);
            //dc.DrawEllipse(brush, null, center, radiusX, radiusY);
            //EndBox(dc);

            //BeginBox(dc, 5, BoxOptions.Tile);
            //brush = new LinearGradientBrush();
            //brush.GradientStops.Add(new GradientStop(Colors.DarkBlue, 0));
            //brush.GradientStops.Add(new GradientStop(Colors.Orange, 0.5));
            //brush.GradientStops.Add(new GradientStop(Colors.Red, 1));
            //dc.DrawEllipse(brush, null, center, radiusX, radiusY);
            //EndBox(dc);

            //BeginBox(dc, 6, BoxOptions.Tile);
            //EndBox(dc);

            //BeginBox(dc, 7, BoxOptions.Tile);
            //EndBox(dc);

            //BeginBox(dc, 8, BoxOptions.Tile);
            //EndBox(dc);

            dc.Close();
            return(dv);
        }
Beispiel #28
0
        protected override void BeginTransition3D(TransitionPresenter transitionElement, ContentPresenter oldContent, ContentPresenter newContent, Viewport3D viewport)
        {
            Size size = transitionElement.RenderSize;

            // Create a rectangle
            MeshGeometry3D mesh = CreateMesh(new Point3D(),
                                             new Vector3D(size.Width, 0, 0),
                                             new Vector3D(0, size.Height, 0),
                                             1,
                                             1,
                                             new Rect(0, 0, 1, 1));

            GeometryModel3D geometry = new GeometryModel3D();

            geometry.Geometry = mesh;
            VisualBrush clone = new VisualBrush(oldContent);

            geometry.Material = new DiffuseMaterial(clone);

            ModelVisual3D model = new ModelVisual3D();

            model.Content = geometry;

            viewport.Children.Add(model);

            Vector3D axis;
            Point3D  center = new Point3D();

            switch (Direction)
            {
            case RotateDirection.Left:
                axis = new Vector3D(0, 1, 0);
                break;

            case RotateDirection.Right:
                axis   = new Vector3D(0, -1, 0);
                center = new Point3D(size.Width, 0, 0);
                break;

            case RotateDirection.Up:
                axis = new Vector3D(-1, 0, 0);
                break;

            default:
                axis   = new Vector3D(1, 0, 0);
                center = new Point3D(0, size.Height, 0);
                break;
            }
            AxisAngleRotation3D rotation = new AxisAngleRotation3D(axis, 0);

            model.Transform = new RotateTransform3D(rotation, center);

            DoubleAnimation da = new DoubleAnimation(0, Duration);

            clone.BeginAnimation(Brush.OpacityProperty, da);

            da            = new DoubleAnimation(90, Duration);
            da.Completed += delegate
            {
                EndTransition(transitionElement, oldContent, newContent);
            };
            rotation.BeginAnimation(AxisAngleRotation3D.AngleProperty, da);
        }
Beispiel #29
0
        private FrameworkElement CreateVisualChild()
        {
            MeshGeometry3D simpleQuad = new MeshGeometry3D()
            {
                Positions          = new Point3DCollection(_mesh),
                TextureCoordinates = new PointCollection(_texCoords),
                TriangleIndices    = new Int32Collection(_indices)
            };

            // Front material is interactive, back material is not.
            Material frontMaterial = new DiffuseMaterial(Brushes.White);

            frontMaterial.SetValue(Viewport2DVisual3D.IsVisualHostMaterialProperty, true);

            VisualBrush vb = new VisualBrush(_logicalChild);

            SetCachingForObject(vb);  // big perf wins by caching!!
            Material backMaterial = new DiffuseMaterial(vb);

            _rotationTransform.Rotation = _quaternionRotation;
            var xfGroup = new Transform3DGroup()
            {
                Children = { _scaleTransform, _rotationTransform }
            };

            GeometryModel3D backModel = new GeometryModel3D()
            {
                Geometry = simpleQuad, Transform = xfGroup, BackMaterial = backMaterial
            };
            Model3DGroup m3dGroup = new Model3DGroup()
            {
                Children = { new DirectionalLight(Colors.White, new Vector3D(0,      0, -1)),
                             new DirectionalLight(Colors.White, new Vector3D(0.1, -0.1,  1)),
                             backModel }
            };

            // Non-interactive Visual3D consisting of the backside, and two lights.
            ModelVisual3D mv3d = new ModelVisual3D()
            {
                Content = m3dGroup
            };

            // Interactive frontside Visual3D
            Viewport2DVisual3D frontModel = new Viewport2DVisual3D()
            {
                Geometry = simpleQuad, Visual = _logicalChild, Material = frontMaterial, Transform = xfGroup
            };

            // Cache the brush in the VP2V3 by setting caching on it.  Big perf wins.
            SetCachingForObject(frontModel);

            // Scene consists of both the above Visual3D's.
            _viewport3d = new Viewport3D()
            {
                ClipToBounds = false, Children = { mv3d, frontModel }
            };

            UpdateRotation();

            return(_viewport3d);
        }
Beispiel #30
0
        /// <summary>
        /// Builds a PdfFormXObject from the specified brush.
        /// </summary>
        PdfFormXObject BuildForm(VisualBrush brush)
        {
            //<<
            //  /BBox [0 100 100 0]
            //  /Length 65
            //  /Matrix [1 0 0 1 0 0]
            //  /Resources
            //  <<
            //    /ColorSpace
            //    <<
            //      /CS0 15 0 R
            //    >>
            //    /ExtGState
            //    <<
            //      /GS0 10 0 R
            //    >>
            //    /ProcSet [/PDF /ImageC /ImageI]
            //    /XObject
            //    <<
            //      /Im0 16 0 R
            //    >>
            //  >>
            //  /Subtype /Form
            //>>
            //stream
            //  q
            //  0 0 100 100 re
            //  W n
            //  q
            //    /GS0 gs
            //    100 0 0 -100 0 100 cm
            //    /Im0 Do
            //  Q
            //Q
            //endstream
            PdfFormXObject pdfForm = Context.PdfDocument.Internals.CreateIndirectObject <PdfFormXObject>();

            pdfForm.DpiX = 96;
            pdfForm.DpiY = 96;

            // view box
            var box = new PdfRectangle(brush.Viewbox.X, brush.Viewbox.Y + brush.Viewbox.Height - 1, brush.Viewbox.X + brush.Viewbox.Width - 1, brush.Viewbox.Y);

            pdfForm.Elements.SetRectangle(PdfFormXObject.Keys.BBox, box);

            pdfForm.Elements.SetMatrix(PdfFormXObject.Keys.Matrix, new XMatrix());

            PdfContentWriter writer = new PdfContentWriter(Context, pdfForm);

            pdfForm.Elements.SetMatrix(PdfFormXObject.Keys.Matrix, new XMatrix());

            writer.BeginContentRaw();
            writer.WriteLiteral("-100 Tz\n");
            writer.WriteLiteral("q\n");
            writer.WriteVisual(brush.Visual);
            writer.WriteLiteral("Q\n");

#if DEBUG
            if (DevHelper.BorderPatterns)
            {
                writer.WriteLiteral("1 1 1 rg 0 0 m {0:0.###} 0 l {0:0.###} {1:0.###} l 0 {1:0.###} l h s\n",
                                    brush.Viewbox.Width, brush.Viewbox.Height);
            }
#endif

            writer.EndContent();

            return(pdfForm);
        }
Beispiel #31
0
        private void AdjustTransformsAndVisual(double aspect, VisualBrush nextBrush)
        {
            // Axis of rotation
            RotateTransform3D    rotateXForm    = (_rootModel.Transform as Transform3DGroup).Children[0] as RotateTransform3D;
            TranslateTransform3D translateXForm = (_rootModel.Transform as Transform3DGroup).Children[1] as TranslateTransform3D;

            Storyboard animator = _viewport.Resources["STORYBOARD_FlipAnimator"] as Storyboard;
            DoubleAnimationUsingKeyFrames rotateAnim    = animator.Children[0] as DoubleAnimationUsingKeyFrames;
            DoubleAnimationUsingKeyFrames translateAnim = animator.Children[1] as DoubleAnimationUsingKeyFrames;

            rotateAnim.Duration    = this.Duration;
            translateAnim.Duration = this.Duration;

            switch (Direction)
            {
            case Direction.LeftToRight:
                rotateAnim.KeyFrames[1].Value = 180;
                rotateXForm.CenterX           = -aspect / 2;
                (rotateXForm.Rotation as AxisAngleRotation3D).Axis = new Vector3D(0, 1, 0);

                translateXForm.OffsetY = 0;
                Storyboard.SetTargetProperty(translateAnim, new PropertyPath(TranslateTransform3D.OffsetXProperty));
                translateAnim.KeyFrames[1].Value = aspect;

                //apply a transform on the visual to move so that the rotation does not affect the look of it
                elementToMoveToView.RenderTransformOrigin = new Point(0.5, 0.5);
                TransformGroup group = new TransformGroup();
                group.Children.Add(new ScaleTransform(1, -1));
                group.Children.Add(new RotateTransform(-180));
                elementToMoveToView.RenderTransform = group;
                break;

            case Direction.RightToLeft:
                rotateAnim.KeyFrames[1].Value = -180;
                rotateXForm.CenterX           = aspect / 2;
                (rotateXForm.Rotation as AxisAngleRotation3D).Axis = new Vector3D(0, 1, 0);

                Storyboard.SetTargetProperty(translateAnim, new PropertyPath(TranslateTransform3D.OffsetXProperty));
                translateAnim.KeyFrames[1].Value = -aspect;

                elementToMoveToView.RenderTransformOrigin = new Point(0.5, 0.5);
                group = new TransformGroup();
                group.Children.Add(new ScaleTransform(1, -1));
                group.Children.Add(new RotateTransform(-180));
                elementToMoveToView.RenderTransform = group;
                break;

            case Direction.TopToBottom:
                rotateAnim.KeyFrames[1].Value = 180;
                rotateXForm.CenterY           = 0.5;
                (rotateXForm.Rotation as AxisAngleRotation3D).Axis = new Vector3D(1, 0, 0);

                Storyboard.SetTargetProperty(translateAnim, new PropertyPath(TranslateTransform3D.OffsetYProperty));
                translateAnim.KeyFrames[1].Value = -1;

                elementToMoveToView.RenderTransformOrigin = new Point(0.5, 0.5);
                group = new TransformGroup();
                group.Children.Add(new ScaleTransform(-1, 1));
                group.Children.Add(new RotateTransform(-180));
                elementToMoveToView.RenderTransform = group;
                break;

            case Direction.BottomToTop:
                rotateAnim.KeyFrames[1].Value = -180;
                rotateXForm.CenterY           = -0.5;
                (rotateXForm.Rotation as AxisAngleRotation3D).Axis = new Vector3D(1, 0, 0);

                Storyboard.SetTargetProperty(translateAnim, new PropertyPath(TranslateTransform3D.OffsetYProperty));
                translateAnim.KeyFrames[1].Value = 1;

                elementToMoveToView.RenderTransformOrigin = new Point(0.5, 0.5);
                group = new TransformGroup();
                group.Children.Add(new ScaleTransform(-1, 1));
                group.Children.Add(new RotateTransform(180));
                elementToMoveToView.RenderTransform = group;
                break;
            }
        }