Beispiel #1
3
        public void CreateBitmap()
        {
            int width = 100;
            int height = 100;
            int dpi = 96;

            Tracing.Log(">> CreateBitmap");
            var thread = new Thread(new ThreadStart(() => 
            {
                Tracing.Log(">> CreateBitmap - Thread start; creating drawing visual");
                //Dispatcher.Invoke(new Action(() => {
                _drawingVisual = new DrawingVisual();
                _drawingContext = _drawingVisual.RenderOpen();
                //}));

                Tracing.Log(">> CreateBitmap - Drawing to context");
                _drawingContext.DrawRectangle(new SolidColorBrush(Colors.HotPink), new Pen(), new Rect(0, 0, 50, 50));
                _drawingContext.DrawRectangle(new SolidColorBrush(Colors.Blue), new Pen(), new Rect(50, 0, 50, 50));
                _drawingContext.DrawRectangle(new SolidColorBrush(Colors.Orange), new Pen(), new Rect(0, 50, 50, 50));
                _drawingContext.DrawRectangle(new SolidColorBrush(Colors.DarkRed), new Pen(), new Rect(50, 50, 50, 50));
                _drawingContext.Close();

                Tracing.Log(">> CreateBitmap - Finished drawing; creating render target bitmap");
                _bitmap = new RenderTargetBitmap(width, height, dpi, dpi, PixelFormats.Default);
                _bitmap.Render(_drawingVisual);
                Tracing.Log(">> CreateBitmap - Finished work");
                _bitmap.Freeze();
            }));
            //thread.IsBackground = true;
            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();
        }
 public void Execute(object parameter)
 {
     var window = _shell as Window;
     var targetBitmap = new RenderTargetBitmap(175, 150, 96d, 96d, PixelFormats.Default);
     targetBitmap.Render(window);
     targetBitmap.Freeze();
     var thumbnail = targetBitmap.ToBase64String();
     _logger.Info(thumbnail);
 }
Beispiel #3
0
 /// <summary>Captures a snapshot of the source element as a bitmap image. The snapshot is created based on the specified rendering parameters.</summary>
 /// <param name="sourceElement">The source element.</param>
 /// <param name="bitmapSize">The bitmap size.</param>
 /// <param name="scalingMode">The bitmap scaling mode.</param>
 /// <param name="bitmapDpi">The bitmap dpi.</param>
 /// <param name="pixelFormat">The bitmap pixel format.</param>
 /// <returns>The snapshot of the source element.</returns>
 public static BitmapSource CaptureSnapshot(FrameworkElement sourceElement, Size bitmapSize, BitmapScalingMode scalingMode, Vector bitmapDpi, PixelFormat pixelFormat) {
    if (sourceElement == null || bitmapSize.IsZero()) return null;
    var snapshot = new RenderTargetBitmap((int)bitmapSize.Width, (int)bitmapSize.Height, bitmapDpi.X, bitmapDpi.Y, pixelFormat);
    sourceElement.SetValue(RenderOptions.BitmapScalingModeProperty, scalingMode);
    snapshot.Render(sourceElement);
    sourceElement.ClearValue(RenderOptions.BitmapScalingModeProperty);
    snapshot.Freeze();
    return snapshot;
 }
		private static void RegisterImageSource(LibraryDevice libraryDevice)
		{
			var frameworkElement = DeviceControl.GetDefaultPicture(libraryDevice);
			frameworkElement.SnapsToDevicePixels = false;
			frameworkElement.Width = DesignerItem.DefaultPointSize;
			frameworkElement.Height = DesignerItem.DefaultPointSize;
			frameworkElement.Arrange(new Rect(new Size(frameworkElement.Width, frameworkElement.Height)));
			var imageSource = new RenderTargetBitmap(DesignerItem.DefaultPointSize, DesignerItem.DefaultPointSize, EnvironmentParameters.DpiX, EnvironmentParameters.DpiY, PixelFormats.Pbgra32);
			imageSource.Render(frameworkElement);
			imageSource.Freeze();
			_imageSources.Add(libraryDevice == null ? Guid.Empty : libraryDevice.DriverId, imageSource);
		}
 private void DoDrawing()
 {
     var drawing = new DrawingVisual();
     using (var context = drawing.RenderOpen())
     {
         DrawImageOperations(context, _imageDrawingOperations);
         DrawImageOperations(context, _extraImageDrawingOperations);
     }
     var output = new RenderTargetBitmap((int)_boundingRect.Width, (int)_boundingRect.Height, 96, 96, PixelFormats.Pbgra32);
     output.Render(drawing);
     output.Freeze();
     Output = output;
 }
        public static BitmapSource Render(double rating)
        {
            StarsRenderer sr = new StarsRenderer();
            sr.FillStars(rating);

            RenderTargetBitmap rtb = new RenderTargetBitmap(249, 32, 0, 0, PixelFormats.Default);
            sr.Measure(new Size(249, 32));
            sr.Arrange(new Rect(new Size(249, 32)));
            rtb.Render(sr);
            rtb.Freeze();

            return rtb;
        }
Beispiel #7
0
        public swmi.BitmapFrame Get(swmi.BitmapSource image, float scale, int width, int height, swm.BitmapScalingMode scalingMode)
        {
            if (width <= 0 || height <= 0 || scale <= 0)
            {
                return(null);
            }

            var _cachedFrame = _cachedFrameReference?.Target as swmi.BitmapFrame;

            // if parameters are the same, return cached bitmap
            if (_cachedFrame != null && scale == _scale && width == _width && height == _height && scalingMode == _scalingMode)
            {
                return(_cachedFrame);
            }

            // generate a new bitmap with the desired size & scale.
            var scaledwidth  = (int)Math.Round(width * scale);
            var scaledheight = (int)Math.Round(height * scale);

            if (scaledwidth <= 0 || scaledheight <= 0)
            {
                return(null);
            }
            var group = new swm.DrawingGroup();

            swm.RenderOptions.SetBitmapScalingMode(group, scalingMode);
            group.Children.Add(new swm.ImageDrawing(image, new sw.Rect(0, 0, width, height)));

            var targetVisual = new swm.DrawingVisual();

            using (var targetContext = targetVisual.RenderOpen())
                targetContext.DrawDrawing(group);

            // note, this uses a GDI handle, which are limited (only 5000 or so can be created).
            // There's no way to get around it other than just not creating that many and using GC.Collect/WaitForPendingFinalizers.
            // we can't do it in Eto as it'd be a serious performance hit.
            var target = new swmi.RenderTargetBitmap(scaledwidth, scaledheight, 96 * scale, 96 * scale, swm.PixelFormats.Default);

            target.Render(targetVisual);
            target.Freeze();

            _cachedFrame = swmi.BitmapFrame.Create(target);
            _cachedFrame.Freeze();
            _scale                = scale;
            _width                = width;
            _height               = height;
            _scalingMode          = scalingMode;
            _cachedFrameReference = new WeakReference(_cachedFrame);
            return(_cachedFrame);
        }
Beispiel #8
0
        private void generateImages(List<string> combos, List<BitmapImage> icons, bool saveToDisk)
        {
            for(int i = 1; i < combos.Count; i++)
            {
                String combo = combos[i];
               
                int imageWidth = combo.Length * MaxIconWidth;
                int imageHeight = MaxIconHeight;       

                RenderTargetBitmap bitmap = new RenderTargetBitmap(imageWidth, imageHeight, 96, 96, PixelFormats.Pbgra32);

                DrawingVisual drawingVisual = new DrawingVisual();             
                RenderOptions.SetBitmapScalingMode(drawingVisual, BitmapScalingMode.HighQuality);

                using (DrawingContext drawingContext = drawingVisual.RenderOpen())
                {
                    for (int j = 0; j < combo.Length; j++)
                    {
                        BitmapImage icon = icons[int.Parse(combo[j].ToString())];

                        int x = j * MaxIconWidth;
                        int y = 0;
                        Rect destRect = new Rect(x, y, MaxIconWidth, MaxIconHeight);

                        drawingContext.DrawImage(icon, destRect);                      

                    }

                }

                RenderOptions.SetBitmapScalingMode(bitmap, BitmapScalingMode.HighQuality);                  
                bitmap.Render(drawingVisual);
                bitmap.Freeze();

                if (saveToDisk == true)
                {
                    JpegBitmapEncoder encoder = new JpegBitmapEncoder();

                    encoder.Frames.Add(BitmapFrame.Create(bitmap, null, null, null));
                   
                    FileStream outputFile = new FileStream("d:\\image" + i + ".jpg", FileMode.Create);
                
                    encoder.Save(outputFile);

                }

                ImageHash.Add(combo, bitmap);
            }
        }
Beispiel #9
0
		private void RegisterImageSource(LibraryDevice libraryDevice)
		{
			if (libraryDevice == null)
				return;
			var frameworkElement = DeviceControl.GetDefaultPicture(libraryDevice);
			frameworkElement.Width = 100;
			frameworkElement.Height = 100;
			frameworkElement.Measure(new Size(frameworkElement.Width, frameworkElement.Height));
			frameworkElement.Arrange(new Rect(new Size(frameworkElement.Width, frameworkElement.Height)));
			var imageSource = new RenderTargetBitmap(100, 100, 96, 96, PixelFormats.Pbgra32);
			imageSource.Render(frameworkElement);
			//RenderOptions.SetCachingHint(imageSource, CachingHint.Cache);
			imageSource.Freeze();
			_imageSources.Add(libraryDevice.DriverId, imageSource);
		}
 public IBasicImage RenderToImageInMemory()
 {
     float density = 1;
     float dpi = 96;
     using (var g = System.Drawing.Graphics.FromHwnd(IntPtr.Zero))
     {
         dpi = g.DpiX;
         density = g.DpiX/96f;
     }
     var bitmap = new RenderTargetBitmap((int)(BoundsWidth * density), (int)(BoundsHeight * density), dpi, dpi, PixelFormats.Default);
     bitmap.Render(_drawingVisual);
     bitmap.Freeze();
     var image = new BasicImage(bitmap);
     return image;
 }
        /// <summary>
        /// The arrow demo is uses an adaption of Chales Petzold's WPF arrow class 
        /// http://charlespetzold.com/blog/2007/04/191200.html to be used as custom MapSape
        /// </summary>
        /// <param name="layer"></param>
        public void AddPinWithLabel(ShapeLayer layer)
        {
            var center = new System.Windows.Point(8.4, 49); // KA
            var radius = 1; // radius in degrees of latitude

            var rand = new Random();
            Func<System.Windows.Point, double, System.Windows.Point> randomCoordinate = (c, r) =>
            {
                var angle = rand.NextDouble() * 2 * Math.PI;
                var distance = r * Math.Sqrt(rand.NextDouble());

                return new System.Windows.Point
                {
                    X = c.X + distance * Math.Cos(angle),
                    Y = c.Y + distance * Math.Sin(angle)
                };
            };

            bool useBitmapCache = true;

            var pin = new Pyramid();
            pin.Width = pin.Height = 10;

            pin.Measure(new Size(pin.Width, pin.Height));
            pin.Arrange(new Rect(0, 0, pin.Width, pin.Height));

            var bitmap = new RenderTargetBitmap((int)pin.Width, (int)pin.Height, 96, 96, PixelFormats.Pbgra32);
            bitmap.Render(pin);
            bitmap.Freeze();
            for (int i = 0; i < 5000; i++)
            {
                FrameworkElement symbol = null;
                if(useBitmapCache)
                    symbol = new Image { Source = bitmap };
                else
                    symbol = new Pyramid();
                symbol.Width = pin.Height = 10;
                ShapeCanvas.SetLocation(symbol, randomCoordinate(center, radius));
                symbol.ToolTip = "Hello";
                layer.Shapes.Add(symbol);
            }

            this.Map.SetMapLocation(center, 9);
        }
        public ParticleSystem(int maxCount, System.Windows.Media.Color color, Uri source)
        {
            this.maxParticleCount = maxCount;

            this.particleList = new List<Particle>();

            this.particleModel = new GeometryModel3D();
            this.particleModel.Geometry = new MeshGeometry3D();

            Image e = new Image();
            e.Source = new BitmapImage( source);

              //  Ellipse e = new Ellipse();

            e.Width = 32.0;
            e.Height = 32.0;
               // RadialGradientBrush b = new RadialGradientBrush();
               // b.GradientStops.Add(new GradientStop(System.Windows.Media.Color.FromArgb(0xFF, color.R, color.G, color.B), 0.25));
               // b.GradientStops.Add(new GradientStop(System.Windows.Media.Color.FromArgb(0x00, color.R, color.G, color.B), 1.0));

               // e.Fill = b;

            e.Measure(new System.Windows.Size(32, 32));
            e.Arrange(new Rect(0, 0, 32, 32));

            System.Windows.Media.Brush brush = null;

            #if USE_VISUALBRUSH
            brush = new VisualBrush(e);
            #else
            RenderTargetBitmap renderTarget = new RenderTargetBitmap(32, 32, 96, 96, PixelFormats.Pbgra32);
            renderTarget.Render(e);
            renderTarget.Freeze();
            brush = new ImageBrush(renderTarget);
            #endif

            DiffuseMaterial material = new DiffuseMaterial(brush);

            this.particleModel.Material = material;

            this.rand = new Random(brush.GetHashCode());
        }
        public static BitmapSource ToBitmapSource(this TextBlock element, bool freeze = true)
        {
            var target = new RenderTargetBitmap((int)(element.Width), (int)(element.Height), 96, 96, System.Windows.Media.PixelFormats.Pbgra32);
            var brush = new System.Windows.Media.VisualBrush(element);

            var visual = new System.Windows.Media.DrawingVisual();
            var drawingContext = visual.RenderOpen();


            drawingContext.DrawRectangle(brush, null, new Rect(new System.Windows.Point(0, 0),
                new System.Windows.Point(element.Width, element.Height)));

            drawingContext.Close();
            target.Render(visual);
            if (freeze)
            {
                target.Freeze();
            }
            return target;
        }
Beispiel #14
0
        public static BitmapSource RenderToBitmapSource(this UIElement visual, double scale)
        {
            Matrix m = PresentationSource.FromVisual(visual).CompositionTarget.TransformToDevice;

            int renderHeight = (int)(visual.RenderSize.Height * scale);
            int renderWidth = (int)(visual.RenderSize.Width * scale);
            var renderTarget = new RenderTargetBitmap(renderWidth, renderHeight,  96,  96, PixelFormats.Pbgra32);

            var sourceBrush = new VisualBrush(visual);
            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(visual.RenderSize.Width, visual.RenderSize.Height)));
            }

            renderTarget.Render(drawingVisual);
            renderTarget.Freeze();

            return renderTarget;
        }
Beispiel #15
0
        public ParticleSystem(int maxCount, Color color)
        {
            MaxParticleCount = maxCount;

            _particleList = new List<Particle>();

            _particleModel = new GeometryModel3D {Geometry = new MeshGeometry3D()};

            var e = new Ellipse
            {
                Width = 32.0,
                Height = 32.0
            };
            var b = new RadialGradientBrush();
            b.GradientStops.Add(new GradientStop(Color.FromArgb(0xFF, color.R, color.G, color.B), 0.25));
            b.GradientStops.Add(new GradientStop(Color.FromArgb(0x00, color.R, color.G, color.B), 1.0));
            e.Fill = b;
            e.Measure(new Size(32, 32));
            e.Arrange(new Rect(0, 0, 32, 32));

            Brush brush = null;

#if USE_VISUALBRUSH
            brush = new VisualBrush(e);
#else
            var renderTarget = new RenderTargetBitmap(32, 32, 96, 96, PixelFormats.Pbgra32);
            renderTarget.Render(e);
            renderTarget.Freeze();
            brush = new ImageBrush(renderTarget);
#endif

            var material = new DiffuseMaterial(brush);

            _particleModel.Material = material;

            _rand = new Random(brush.GetHashCode());
        }
        private void RenderToBitmapCore(TileIndex id)
        {
            rendering = true;
            var visible = GetTileBounds(id);

            Debug.WriteLine(String.Format("Visible is {0} for id={1}", visible.ToString(), id.ToString()));

            plotter.Visible = visible;
            //plotter.InvalidateVisual();

            if (!BackgroundRenderer.GetUsesBackgroundRendering(child))
            {
                // this is done to make all inside plotter to perform measure and arrange procedures
                plotter.Dispatcher.Invoke(() => { }, DispatcherPriority.Input);
                RenderTargetBitmap bmp = new RenderTargetBitmap((int)tileSize.Width, (int)tileSize.Height, 96, 96, PixelFormats.Pbgra32);
                bmp.Render(plotter);
                bmp.Freeze();
                ReportSuccessAsync(null, bmp, id);
                rendering = false;
            }
        }
        private void SaveImage(ColorImagePoint position,TrackingTime trackingTime,FrameworkElement control)
        {
            _fn = GetFilename(trackingTime);
            try
            {
               RenderTargetBitmap renderTargetBitmap=new RenderTargetBitmap(640,480,96,96,PixelFormats.Pbgra32);
                renderTargetBitmap.Render(control);
                renderTargetBitmap.Freeze();
                int x = position.X - croppedImageWidth/2;
                if (x<0)
                {
                    x = 0;
                }
                int width = croppedImageWidth;
                if (x+width>renderTargetBitmap.Width)
                {
                    width = (int)renderTargetBitmap.Width - x;
                }
                CroppedBitmap croppedBitmap = new CroppedBitmap(renderTargetBitmap, new Int32Rect(x,0,width,(int)renderTargetBitmap.Height));
                string ext = System.IO.Path.GetExtension(_fn).ToLower();
                BitmapEncoder encoder = new PngBitmapEncoder();
                if (encoder == null) return;
                encoder.Frames.Add(BitmapFrame.Create(croppedBitmap));

                using (Stream stm = File.Create(_fn))
                {
                    encoder.Save(stm);
                }

               //backgroundWorker.RunWorkerAsync(_fn);
            }
            catch (Exception x)
            {
                MessageBox.Show("Sorry, I had trouble saving that photo.\n\nError: " + x.Message);
                //IsAutoEnabled = false;
                // timer.Stop();
            }
        }
		private void RenderToBitmapCore(TileIndex id)
		{
			isRendering[GetIndex()] = true;

			var plotter = GetPlotter();
			var visible = GetTileBounds(id);

			plotter.Visible = visible;

			// this is done to make all inside plotter to perform measure and arrange procedures
			plotter.Dispatcher.Invoke(() => { }, DispatcherPriority.Background);

			RenderTargetBitmap bmp = new RenderTargetBitmap((int)tileSize.Width, (int)tileSize.Height, 96, 96, PixelFormats.Pbgra32);
			bmp.Render(plotter);
			bmp.Freeze();

			ReportSuccessAsync(null, bmp, id);

			isRendering[GetIndex()] = false;
		}
Beispiel #19
0
        BitmapSource CreateSymbolBitmap(SymbolID symbolID, Color color, bool dark)
        {
            DrawingVisual drawingVisual = new DrawingVisual();
            DrawingContext drawingContext = drawingVisual.RenderOpen();

            Drawing d = m_symbolDrawingCache.GetDrawing(symbolID, color);

            drawingContext.PushTransform(new ScaleTransform(Math.Floor(m_size) / 100, Math.Floor(m_size) / 100));
            drawingContext.DrawDrawing(d);
            drawingContext.Pop();

            drawingContext.Close();

            if (dark)
                drawingVisual.Opacity = 0.2;

            RenderTargetBitmap bmp = new RenderTargetBitmap((int)m_size, (int)m_size, 96, 96, PixelFormats.Default);
            bmp.Render(drawingVisual);
            bmp.Freeze();
            return bmp;
        }
Beispiel #20
0
        static BitmapSource DrawPublicationImage(string title, string author) {
            var size = new Size(800, 1200);

            var titleText = new FormattedText(title,
                new System.Globalization.CultureInfo("en-us"),
                System.Windows.FlowDirection.LeftToRight,
                new Typeface("Segoe UI"),
                72,
                Brushes.CornflowerBlue);
            titleText.MaxTextWidth = size.Width;
            titleText.TextAlignment = TextAlignment.Center;

            var authorText = new FormattedText(author,
                new System.Globalization.CultureInfo("en-us"),
                FlowDirection.LeftToRight,
                new Typeface("Segoe UI"),
                48,
                Brushes.CornflowerBlue);
            authorText.MaxTextWidth = size.Width;
            authorText.TextAlignment = TextAlignment.Center;

            var visual = new DrawingVisual();

            var ctx = visual.RenderOpen();
            ctx.DrawRectangle(Brushes.White, null, new Rect(size));
            ctx.DrawText(titleText, new Point(0, 100));
            ctx.DrawText(authorText, new Point(0, 100 + titleText.Height + 20));
            ctx.Close();

            var bitmap = new RenderTargetBitmap((int)size.Width, (int)size.Height, 92, 92, PixelFormats.Pbgra32);
            bitmap.Render(visual);
            bitmap.Freeze();
            return bitmap;
        }
Beispiel #21
0
        private void InitCanvas()
        {
            _wallBmp = new WriteableBitmap(_scrRect32.Width, _scrRect32.Height,
                Constants.DPIX, Constants.DPIY, PixelFormats.Pbgra32, null);

            simDrawing.ClipGeometry = new RectangleGeometry(_scrRect);

            _liquidEffect = new Effect.LiquidEffect();
            _liquidEffect.Threashold = 0.8;
            _liquidEffect.FillColor = Config.Instance.LiquidColor;
            _liquidEffect.Freeze();

            _particleBrush = new SolidColorBrush(Config.Instance.LiquidColor);

            // 粒子をぼかして描画するための画像作成
            _liquidGradPoint = new RenderTargetBitmap((int)_liquidRadius * 2, (int)_liquidRadius * 2,
                Constants.DPIX, Constants.DPIY, PixelFormats.Pbgra32);
            DrawingVisual dv = new DrawingVisual();
            using (DrawingContext dc = dv.RenderOpen())
            {
                dc.DrawRectangle(Brushes.Transparent, null, new Rect(0, 0, _liquidGradPoint.PixelWidth, _liquidGradPoint.PixelHeight));
                dc.DrawEllipse(_gradBrush, null, new Point(_liquidRadius, _liquidRadius), _liquidRadius, _liquidRadius);
            }
            _liquidGradPoint.Render(dv);
            _liquidGradPoint.Freeze();
        }
Beispiel #22
0
        private void Menu_ScreenShot(object sender, RoutedEventArgs e)
        {
            const int maxsize = 3000;
            Rect2D contentBounds = Tree.picActiveLinks.ContentBounds;
            contentBounds *= 1.2;
            if (!double.IsNaN(contentBounds.Width) && !double.IsNaN(contentBounds.Height))
            {
                double aspect = contentBounds.Width / contentBounds.Height;
                double xmax = contentBounds.Width;
                double ymax = contentBounds.Height;
                if (aspect > 1 && xmax > maxsize)
                {
                    xmax = maxsize;
                    ymax = xmax / aspect;
                }
                if (aspect < 1 & ymax > maxsize)
                {
                    ymax = maxsize;
                    xmax = ymax * aspect;
                }

                _clipboardBmp = new RenderTargetBitmap((int)xmax, (int)ymax, 96, 96, PixelFormats.Pbgra32);
                var db = new VisualBrush(Tree.SkillTreeVisual);
                db.ViewboxUnits = BrushMappingMode.Absolute;
                db.Viewbox = contentBounds;
                var dw = new DrawingVisual();

                using (DrawingContext dc = dw.RenderOpen())
                {
                    dc.DrawRectangle(db, null, new Rect(0, 0, xmax, ymax));
                }
                _clipboardBmp.Render(dw);
                _clipboardBmp.Freeze();

                Clipboard.SetImage(_clipboardBmp);

                recSkillTree.Fill = new VisualBrush(Tree.SkillTreeVisual);
            }
        }
Beispiel #23
0
        // Render part of a map to a bitmap.
        static BitmapSource RenderBitmap(Map map, int bmWidth, int bmHeight, RectangleF mapArea)
        {
            // Calculate the transform matrix.
            Point midpoint = new Point(bmWidth / 2.0F, bmHeight / 2.0F);
            double scaleFactor = bmWidth / mapArea.Width;
            PointF centerPoint = new PointF((mapArea.Left + mapArea.Right) / 2, (mapArea.Top + mapArea.Bottom) / 2);
            Matrix matrix = Matrix.Identity;
            matrix.TranslatePrepend(midpoint.X, midpoint.Y);
            matrix.ScalePrepend(scaleFactor, -scaleFactor);  // y scale is negative to get to cartesian orientation.
            matrix.TranslatePrepend(-centerPoint.X, -centerPoint.Y);

            // Get the render options.
            RenderOptions renderOpts = new RenderOptions();
            renderOpts.usePatternBitmaps = false;
            renderOpts.minResolution = (float) (1 / scaleFactor);

            // Create a drawing of the map.
            DrawingVisual visual = new DrawingVisual();
            DrawingContext dc = visual.RenderOpen();

            // Clear the bitmap
            dc.DrawRectangle(Brushes.White, null, new Rect(-1, -1, bmWidth + 2, bmHeight + 2));  // clear background.

            // Transform to map coords.
            dc.PushTransform(new MatrixTransform(matrix));

            // Draw the map.
            using (map.Read())
                map.Draw(dc, mapArea, renderOpts);
            dc.Close();

            // Draw into a new bitmap.
            RenderTargetBitmap bitmapNew = new RenderTargetBitmap(bmWidth, bmHeight, 96.0, 96.0, PixelFormats.Pbgra32);
            bitmapNew.Render(visual);
            bitmapNew.Freeze();

            return bitmapNew;
        }
Beispiel #24
0
      /// <summary>
      /// gets image of the current view
      /// </summary>
      /// <returns></returns>
      public ImageSource ToImageSource()
      {
         FrameworkElement obj = this;

         // Save current canvas transform
         Transform transform = obj.LayoutTransform;
         obj.LayoutTransform = null;

         // fix margin offset as well
         Thickness margin = obj.Margin;
         obj.Margin = new Thickness(0, 0,
         margin.Right - margin.Left, margin.Bottom - margin.Top);

         // Get the size of canvas
         Size size = new Size(obj.ActualWidth, obj.ActualHeight);

         // force control to Update
         obj.Measure(size);
         obj.Arrange(new Rect(size));

         RenderTargetBitmap bmp = new RenderTargetBitmap(
         (int)size.Width, (int)size.Height, 96, 96, PixelFormats.Pbgra32);

         bmp.Render(obj);

         if(bmp.CanFreeze)
         {
            bmp.Freeze();
         }

         // return values as they were before
         obj.LayoutTransform = transform;
         obj.Margin = margin;

         return bmp;
      }
        private void OnChildRenderingFinished(object sender, RoutedEventArgs e)
        {
            plotter.Dispatcher.Invoke(() => { }, DispatcherPriority.Input);

            RenderTargetBitmap bmp = new RenderTargetBitmap((int)tileSize.Width, (int)tileSize.Height, 96, 96, PixelFormats.Pbgra32);
            bmp.Render(plotter);
            bmp.Freeze();
            rendering = false;
            ReportSuccessAsync(null, bmp, renderingID);

            Debug.WriteLine(String.Format("Finished rendering ID={0}", renderingID));
        }
        private static BitmapSource ElementToBitmap(FrameworkElement element, Double dpi = HiResDpi)
        {
            // Scale dimensions from 96 dpi to provided dpi.
            double scale = dpi / DefaultDpi;

            RenderTargetBitmap bitmap = new RenderTargetBitmap(
                (Int32)(scale * element.ActualWidth),
                (Int32)(scale * element.ActualHeight),
                scale * DefaultDpi,
                scale * DefaultDpi,
                PixelFormats.Default);

            bitmap.Render(element);
            bitmap.Freeze();

            return bitmap;
        }
Beispiel #27
0
        /// <summary>
        /// Creates the text material.
        /// </summary>
        /// <param name="items">The items.</param>
        /// <param name="createElement">The create element.</param>
        /// <param name="background">The background.</param>
        /// <param name="elementMap">The element map.</param>
        /// <param name="elementPositions">The element positions.</param>
        /// <returns>A text material.</returns>
        public static Material CreateTextMaterial(
            IEnumerable<TextItem> items,
            Func<string, FrameworkElement> createElement,
            Brush background,
            out Dictionary<string, FrameworkElement> elementMap,
            out Dictionary<FrameworkElement, Rect> elementPositions)
        {
            var panel = new WrapPanel();
            elementMap = new Dictionary<string, FrameworkElement>();
            double maxWidth = 16;
            foreach (var item in items)
            {
                if (elementMap.ContainsKey(item.Text))
                {
                    continue;
                }

                var e = createElement(item.Text);
                e.Measure(new Size(2048, 2048));
                maxWidth = Math.Max(maxWidth, e.DesiredSize.Width);
                elementMap[item.Text] = e;
                panel.Children.Add(e);
            }

            var pw = (int)OptimizeSize(panel, maxWidth, 1024);
            var ph = (int)Math.Min(pw, panel.ActualHeight);

            elementPositions = new Dictionary<FrameworkElement, Rect>();
            foreach (FrameworkElement element in panel.Children)
            {
                var loc = element.TranslatePoint(new Point(0, 0), panel);
                double x = (int)Math.Floor(loc.X);
                double y = (int)Math.Floor(loc.Y);
                double x2 = (int)Math.Ceiling(loc.X + element.RenderSize.Width);
                double y2 = (int)Math.Ceiling(loc.Y + element.RenderSize.Height);
                elementPositions[element] = new Rect(x / pw, y / ph, (x2 - x) / pw, (y2 - y) / ph);
            }

            // Create the bitmap
            var rtb = new RenderTargetBitmap(pw, ph, 96, 96, PixelFormats.Pbgra32);
            rtb.Render(panel);
            rtb.Freeze();
            var ib = new ImageBrush(rtb)
                         {
                             Stretch = Stretch.Fill,
                             ViewboxUnits = BrushMappingMode.RelativeToBoundingBox,
                             Viewbox = new Rect(0, 0, 1, 1),
                             ViewportUnits = BrushMappingMode.Absolute,
                             Viewport = new Rect(0, 0, 1, 1),
                             TileMode = TileMode.None,
                             AlignmentX = AlignmentX.Left,
                             AlignmentY = AlignmentY.Top
                         };

            if (background != null && !background.Equals(Brushes.Transparent))
            {
                var mg = new MaterialGroup();
                mg.Children.Add(new DiffuseMaterial(Brushes.Black));
                mg.Children.Add(new EmissiveMaterial(ib));
                return mg;
            }

            return new DiffuseMaterial(ib) { Color = Colors.White };
        }
        /// <summary>
        /// Creates a new ImageSource with the specified width/height
        /// </summary>
        /// <remarks>
        /// http://blogs.msdn.com/b/delay/archive/2007/11/11/bigger-isn-t-always-better-how-to-resize-images-without-reloading-them-with-wpf.aspx
        /// </remarks>
        ImageSource CreateResizedImage(ImageSource source, int width, int height)
        {
            if (source == null)
                throw new ArgumentException("source");
            if (width <= 0)
                throw new ArgumentException("width");
            if (height <= 0)
                throw new ArgumentException("height");

            // Target Rect for the resize operation
            Rect rect = new Rect(0, 0, width, height);

            // Create a DrawingVisual/Context to render with
            DrawingVisual drawingVisual = new DrawingVisual();
            using (DrawingContext drawingContext = drawingVisual.RenderOpen())
            {
                drawingContext.DrawImage(source, rect);
            }

            // Use RenderTargetBitmap to resize the original image
            RenderTargetBitmap resizedImage = new RenderTargetBitmap(
                (int)rect.Width, (int)rect.Height,  // Resized dimensions
                96, 96,                             // Default DPI values
                PixelFormats.Default);              // Default pixel format

            resizedImage.Render(drawingVisual);
            resizedImage.Freeze();

            // Return the resized image
            return resizedImage;
        }
        void UpdateShadow()
        {
            if (substance == null) return;
            if (style == null) return;

            Thread.Sleep(300);

            // Black material
            DiffuseMaterial material = new DiffuseMaterial(Brushes.Black);
            material.Freeze();

            // Create molecules
            ModelVisual3D container = new ModelVisual3D();
            foreach (Data.Molecule molecule in substance.Molecules)
            {
                foreach (Data.Atom atom in molecule.Atoms)
                {
                    if (style.ColorStyle.ColorScheme[atom.Element].Diffuse.A < 5) continue;
                    Sphere sphere = new Sphere();
                    sphere.Material = material;
                    sphere.Radius = Atom.GetAtomRadius(atom, style.GeometryStyle);
                    sphere.Center = atom.Position;
                    container.Children.Add(sphere);
                }
                double bondRadius = Bond.GetBondRadius(style.GeometryStyle);
                foreach (Data.Bond bond in molecule.Bonds)
                {
                    if (style.ColorStyle.UseSingleBondMaterial)
                    {
                        if (style.ColorStyle.BondMaterial.Diffuse.A < 5) continue;
                    }
                    else if (style.ColorStyle.ColorScheme[bond.Begin.Element].Diffuse.A < 5 ||
                             style.ColorStyle.ColorScheme[bond.End.Element].Diffuse.A < 5) continue;
                    Cylinder cylinder = new Cylinder(bond.Begin.Position, bond.End.Position, bondRadius);
                    cylinder.Material = material;
                    container.Children.Add(cylinder);
                }

                #region Build approximation of ribbon

                double radius = 0.45;
                foreach (Data.Chain chain in molecule.Chains)
                {
                    for (int i = 0; i < chain.Residues.Count; i++)
                    {
                        if (chain.Residues[i].GetStructureType() == SecondaryStructureType.Helix)
                           if (style.GeometryStyle.HelixHeight < 0.05 || style.GeometryStyle.HelixWidth < 0.05) continue;
                           else radius = Residue.HelixWidth * ((style.GeometryStyle.HelixHeight + style.GeometryStyle.HelixWidth) / 2.0);
                        if (chain.Residues[i].GetStructureType() == SecondaryStructureType.Sheet)
                           if (style.GeometryStyle.SheetHeight < 0.05 || style.GeometryStyle.SheetWidth < 0.05) continue;
                           else radius = Residue.SheetWidth * ((style.GeometryStyle.SheetHeight + style.GeometryStyle.SheetWidth) / 2.0);
                        if (chain.Residues[i].GetStructureType() == SecondaryStructureType.NotDefined)
                           if (style.GeometryStyle.TurnHeight < 0.05 || style.GeometryStyle.TurnWidth < 0.05) continue;
                           else radius = Residue.TurnWidth * ((style.GeometryStyle.TurnHeight + style.GeometryStyle.TurnWidth) / 2.0);

                        if (chain.Residues[i].GetStructureType() == SecondaryStructureType.Helix && style.ColorStyle.HelixMaterial.Diffuse.A < 5) continue;
                        if (chain.Residues[i].GetStructureType() == SecondaryStructureType.Sheet && style.ColorStyle.SheetMaterial.Diffuse.A < 5) continue;
                        if (chain.Residues[i].GetStructureType() == SecondaryStructureType.NotDefined && style.ColorStyle.TurnMaterial.Diffuse.A < 5) continue;

                        Data.Atom alfaCarbon = chain.Residues[i].AlfaCarbon;
                        if (alfaCarbon != null)
                        {
                            Point3D begin = alfaCarbon.Position;
                            alfaCarbon = null;
                            for (int j = i + 1; j < chain.Residues.Count; j++)
                            {
                                alfaCarbon = chain.Residues[j].AlfaCarbon;
                                if (alfaCarbon != null) break;
                            }
                            if (alfaCarbon != null)
                            {
                                Point3D end = alfaCarbon.Position;
                                Cylinder cylinder = new Cylinder(begin, end, radius);
                                container.Children.Add(cylinder);
                            }
                        }
                    }
                }

                #endregion
            }

            // Get bounding box
            Rect3D boundingBox = VisualTreeHelper.GetDescendantBounds(container);
            if (boundingBox.IsEmpty)
            {
                shadowRefreshStarted = false;
                return;
            }

            #region Render Shadow

            const double blurSize = 25;
            const int renderTargetWidth = 200;
            int renderTargetHeight = (int)(200.0 * (boundingBox.SizeX / boundingBox.SizeY));
            RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap(renderTargetWidth, renderTargetHeight, 96, 96, PixelFormats.Pbgra32);

            Viewport3D shadowViewport3D = new Viewport3D();
            Border border = new Border();
            border.Padding = new Thickness(blurSize);
            border.Child = shadowViewport3D;

            // Change size of the visualizer
            border.Width = renderTargetBitmap.PixelWidth;
            border.Height = renderTargetBitmap.PixelHeight;
            border.Measure(new Size(renderTargetBitmap.PixelWidth, renderTargetBitmap.PixelHeight));
            border.Arrange(new Rect(0, 0, renderTargetBitmap.PixelWidth, renderTargetBitmap.PixelHeight));

            shadowViewport3D.Children.Add(container);

            // Create camera
            OrthographicCamera orthographicCamera = new OrthographicCamera();

            #region Accomodate camera to fit content

            orthographicCamera.Position = new Point3D(boundingBox.Location.X + boundingBox.SizeX / 2.0,
                                                      boundingBox.Location.Y,
                                                      boundingBox.Location.Z + boundingBox.SizeZ / 2.0);
            orthographicCamera.LookDirection = new Vector3D(0, 1, 0);
            orthographicCamera.UpDirection = new Vector3D(-1, 0, 0);
            orthographicCamera.Width = boundingBox.SizeZ;

            #endregion

            orthographicCamera.NearPlaneDistance = 0;

            // Set the camera & correct lights
            shadowViewport3D.Camera = orthographicCamera;

            BlurEffect blurEffect = new BlurEffect();
            blurEffect.Radius = blurSize;

            border.Effect = blurEffect;

            renderTargetBitmap.Render(border);
            renderTargetBitmap.Freeze();

            #endregion

            // Invoke in main thread
            Dispatcher.BeginInvoke((Action) delegate
            {
                #region Create Plane

                Vector3D margin = new Vector3D(boundingBox.SizeX * 0.4, 0, boundingBox.SizeZ * 0.4);
                Point3D[] points = new Point3D[]
                {
                    boundingBox.Location + new Vector3D(-margin.X, -margin.Y, -margin.Z),
                    boundingBox.Location +
                    new Vector3D(margin.X + boundingBox.SizeX, -margin.Y, -margin.Z),
                    boundingBox.Location +
                    new Vector3D(margin.X + boundingBox.SizeX, -margin.Y,
                                margin.Z + boundingBox.SizeZ),
                    boundingBox.Location +
                    new Vector3D(-margin.X, -margin.Y, margin.Z + boundingBox.SizeZ)
                };

                Polygon shadowPlane = new Polygon();
                shadowPlane.Positions = points;
                shadowPlane.TextureCoordinates = new Point[] { new Point(0, 0), new Point(0, 1), new Point(1, 1), new Point(1, 0) };

                #endregion
                shadowBrush.ImageSource = renderTargetBitmap;
                shadowBrush.Stretch = Stretch.Fill;
                shadowTargetOpacity = 0.8;

                shadowPlane.Material = new DiffuseMaterial(shadowBrush);
                shadowContainer.Children.Clear();
                shadowContainer.Children.Add(shadowPlane);

                // Update shadow hash
                shadowRefreshStarted = false;

              }, DispatcherPriority.SystemIdle);
        }
Beispiel #30
0
        /// <summary>
        /// Called when the visual changed.
        /// </summary>
        private void VisualChanged()
        {
            if (string.IsNullOrEmpty(this.Text))
            {
                this.Content = null;
                return;
            }

            // First we need a textblock containing the text of our label
            var textBlock = new TextBlock(new Run(this.Text))
                                {
                                    Foreground = this.Foreground,
                                    Background = this.Background,
                                    FontWeight = this.FontWeight,
                                    Padding = this.Padding
                                };
            if (this.FontFamily != null)
            {
                textBlock.FontFamily = this.FontFamily;
            }
            if (this.FontSize > 0)
            {
                textBlock.FontSize = this.FontSize;
            }

            var element = this.BorderBrush != null
                              ? (FrameworkElement)
                                new Border
                                    {
                                        BorderBrush = this.BorderBrush,
                                        BorderThickness = this.BorderThickness,
                                        Child = textBlock
                                    }
                              : textBlock;

            element.Measure(new Size(1000, 1000));
            element.Arrange(new Rect(element.DesiredSize));

            Material material;
            if (this.FontSize > 0)
            {
                var rtb = new RenderTargetBitmap(
                    (int)element.ActualWidth + 1, (int)element.ActualHeight + 1, 96, 96, PixelFormats.Pbgra32);
                rtb.Render(element);
                rtb.Freeze();
                material = new DiffuseMaterial(new ImageBrush(rtb));
            }
            else
            {
                material = new DiffuseMaterial { Brush = new VisualBrush(element) };
            }

            double width = element.ActualWidth / element.ActualHeight * this.Height;

            var position = this.Position;
            var textDirection = this.TextDirection;
            var updirection = this.UpDirection;
            var height = this.Height;

            // Set horizontal alignment factor
            var xa = -0.5;
            if (this.HorizontalAlignment == HorizontalAlignment.Left)
            {
                xa = 0;
            }
            if (this.HorizontalAlignment == HorizontalAlignment.Right)
            {
                xa = -1;
            }

            // Set vertical alignment factor
            var ya = -0.5;
            if (this.VerticalAlignment == VerticalAlignment.Top)
            {
                ya = -1;
            }
            if (this.VerticalAlignment == VerticalAlignment.Bottom)
            {
                ya = 0;
            }

            // Since the parameter coming in was the center of the label,
            // we need to find the four corners
            // p0 is the lower left corner
            // p1 is the upper left
            // p2 is the lower right
            // p3 is the upper right
            Point3D p0 = position + (xa * width) * textDirection + (ya * height) * updirection;
            Point3D p1 = p0 + updirection * height;
            Point3D p2 = p0 + textDirection * width;
            Point3D p3 = p0 + updirection * height + textDirection * width;

            // Now build the geometry for the sign.  It's just a
            // rectangle made of two triangles, on each side.
            var mg = new MeshGeometry3D { Positions = new Point3DCollection { p0, p1, p2, p3 } };

            bool isDoubleSided = this.IsDoubleSided;
            if (isDoubleSided)
            {
                mg.Positions.Add(p0); // 4
                mg.Positions.Add(p1); // 5
                mg.Positions.Add(p2); // 6
                mg.Positions.Add(p3); // 7
            }

            mg.TriangleIndices.Add(0);
            mg.TriangleIndices.Add(3);
            mg.TriangleIndices.Add(1);
            mg.TriangleIndices.Add(0);
            mg.TriangleIndices.Add(2);
            mg.TriangleIndices.Add(3);

            if (isDoubleSided)
            {
                mg.TriangleIndices.Add(4);
                mg.TriangleIndices.Add(5);
                mg.TriangleIndices.Add(7);
                mg.TriangleIndices.Add(4);
                mg.TriangleIndices.Add(7);
                mg.TriangleIndices.Add(6);
            }

            double u0 = this.IsFlipped ? 1 : 0;
            double u1 = this.IsFlipped ? 0 : 1;

            // These texture coordinates basically stretch the
            // TextBox brush to cover the full side of the label.
            mg.TextureCoordinates.Add(new Point(u0, 1));
            mg.TextureCoordinates.Add(new Point(u0, 0));
            mg.TextureCoordinates.Add(new Point(u1, 1));
            mg.TextureCoordinates.Add(new Point(u1, 0));

            if (isDoubleSided)
            {
                mg.TextureCoordinates.Add(new Point(u1, 1));
                mg.TextureCoordinates.Add(new Point(u1, 0));
                mg.TextureCoordinates.Add(new Point(u0, 1));
                mg.TextureCoordinates.Add(new Point(u0, 0));
            }

            this.Content = new GeometryModel3D(mg, material);
        }
Beispiel #31
0
 /// <summary>Creates a static image of the current view.</summary>
 /// <returns>An image of the current map.</returns>
 public ImageSource CreateImage()
 {
     RenderTargetBitmap bitmap = new RenderTargetBitmap((int)this.ActualWidth, (int)this.ActualHeight, 96, 96, PixelFormats.Default);
     bitmap.Render(_tilePanel);
     bitmap.Freeze();
     return bitmap;
 }