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(); }
private void ButtonSave_Click(object sender, RoutedEventArgs e) { var rect = new Rect { Width = 512, Height = 384 }; var dv = new DrawingVisual(); var dc = dv.RenderOpen(); dc.PushTransform(new TranslateTransform(-rect.X, -rect.Y)); dc.DrawRectangle(InkCanvasMain.Background, null, rect); InkCanvasMain.Strokes.Draw(dc); dc.Close(); var rtb = new RenderTargetBitmap((int)rect.Width, (int)rect.Height, 96, 96, PixelFormats.Default); rtb.Render(dv); var enc = new PngBitmapEncoder(); enc.Frames.Add(BitmapFrame.Create(rtb)); var fn = TextBoxFileName.Text; if (!fn.EndsWith(".png", StringComparison.OrdinalIgnoreCase)) fn += ".png"; using (Stream s = File.Create(TegakiImageFolder + "/" + fn)) { enc.Save(s); } ((TegakiWindowViewModel)DataContext).AddToMediaList(System.IO.Path.GetFullPath(TegakiImageFolder + "/" + fn)); Close(); }
public void Flush() { if (Close()) { Control = drawingVisual.RenderOpen(); } }
internal static void DrawContextualMenu(DrawingVisual drawingVisual, Dictionary<int, string> itemsList) { //draw the stuff //3 cases //menu items == 7 //menu items < 7 //menu items > 7 DrawingContext context = drawingVisual.RenderOpen(); int itemsCount = itemsList.Count; if (itemsCount == 7) { } if (itemsCount < 7) { } if (itemsCount > 7) { } // position the menu correctly }
public WaveGraph() { InitializeComponent(); DrawingVisual ghostVisual; Width = 300; Height = 350; ghostVisual = new DrawingVisual(); using (DrawingContext dc = ghostVisual.RenderOpen()) { dc.DrawEllipse(Brushes.Black, new Pen(Brushes.Red, 10), new Point(95, 95), 15, 15); dc.DrawEllipse(Brushes.Black, new Pen(Brushes.Red, 10), new Point(170, 105), 15, 15); Pen p = new Pen(Brushes.Black, 10); p.StartLineCap = PenLineCap.Round; p.EndLineCap = PenLineCap.Round; dc.DrawLine(p, new Point(75, 160), new Point(175, 150)); } this.AddVisualChild(ghostVisual); this.AddLogicalChild(ghostVisual); }
private void RenderMyVisual(DrawingVisual v) { using (var dc = v.RenderOpen()) { RenderRectangles(dc); } }
private DrawingVisual CreateNodeVisual(VisibilityType visibility, bool IsHighlighted, bool IsPathHighlighted, bool IsSelected, bool UsedInConstruction) { var visual = new DrawingVisual(); using (var context = visual.RenderOpen()) { // Draw the actual circle var size = this.GetSize(IsHighlighted, IsPathHighlighted, IsSelected, UsedInConstruction); switch (visibility) { case VisibilityType.Important: context.DrawEllipse( this.GetFillBrush(IsSelected, UsedInConstruction), this.GetStrokePen(IsHighlighted, IsPathHighlighted, IsSelected, UsedInConstruction), new Point(0, 0), size.Width / 2, size.Height / 2); break; case VisibilityType.ShowWhenNecessary: if ((IsPathHighlighted) || (IsSelected) || (IsHighlighted) || (UsedInConstruction)) { context.DrawEllipse( this.GetFillBrush(IsSelected, UsedInConstruction), this.GetStrokePen(IsHighlighted, IsPathHighlighted, IsSelected, UsedInConstruction), new Point(0, 0), size.Width / 2, size.Height / 2); } break; } } return visual; }
private BitmapSource MakeTileBitmap() { const double dotsPerInch = 96.0; IDisposable disposable = null; try { Rect sourceRect, targetRect; if (!MakeSourceAndTargetRects(out sourceRect, out targetRect)) return null; DrawingVisual drawingVisual = new DrawingVisual(); using (DrawingContext drawingContext = drawingVisual.RenderOpen()) disposable = _image.DrawPortion(drawingContext, targetRect, sourceRect, _level); RenderTargetBitmap tileBitmap = new RenderTargetBitmap((int)targetRect.Width, (int)targetRect.Height, dotsPerInch, dotsPerInch, PixelFormats.Default); tileBitmap.Render(drawingVisual); return tileBitmap; } finally { if (disposable != null) disposable.Dispose(); } }
/// <summary> /// /// </summary> /// <param name="geometry"></param> /// <param name="bitmapSize"></param> /// <param name="geometryPositionOnBitmap"></param> /// <param name="brush">The Brush with which to fill the Geometry. This is optional, and can be null. If the brush is null, no fill is drawn.</param> /// <param name="pen">The Pen with which to stroke the Geometry. This is optional, and can be null. If the pen is null, no stroke is drawn</param> /// <param name="pixelFormat"></param> /// <param name="dpiX"></param> /// <param name="dpiY"></param> /// <returns></returns> public static BitmapSource RenderToBitmap( this Geometry geometry, Size bitmapSize, Point geometryPositionOnBitmap, Size geometrySize, Brush brush, Pen pen, PixelFormat pixelFormat, double dpiX = 96.0, double dpiY = 96.0) { var rtb = new RenderTargetBitmap((int)(bitmapSize.Width * dpiX / 96.0), (int)(bitmapSize.Height * dpiY / 96.0), dpiX, dpiY, pixelFormat); var dv = new DrawingVisual(); using (var cx = dv.RenderOpen()) { cx.Render(geometry, geometryPositionOnBitmap, brush, pen); } rtb.Render(dv); return rtb; }
public void Draw( EdgeLayout layoutState ) { var styleState = myPresentation.GetPropertySetFor<EdgeStyle>().Get( Owner.Id ); var stream = new StreamGeometry(); var context = stream.Open(); context.BeginFigure( layoutState.Points.First(), false, false ); context.PolyBezierTo( layoutState.Points.Skip( 1 ).ToList(), true, false ); // draw arrow head var start = layoutState.Points.Last(); var v = start - layoutState.Points.ElementAt( layoutState.Points.Count() - 2 ); v.Normalize(); start = start - v * 0.15; context.BeginFigure( start + v * 0.28, true, true ); double t = v.X; v.X = v.Y; v.Y = -t; // Rotate 90° context.LineTo( start + v * 0.08, true, true ); context.LineTo( start + v * -0.08, true, true ); context.Close(); var pen = new Pen( styleState.Color, 0.016 ); // http://stackoverflow.com/questions/1755520/improve-drawingvisual-renders-speed Visual = new DrawingVisual(); var dc = Visual.RenderOpen(); dc.DrawGeometry( pen.Brush, pen, stream ); dc.Close(); Visual.SetValue( GraphItemProperty, Owner ); }
public void DrawPoints(SortedList <double, double> points, Point[] line) { _children.Clear(); double width = ActualWidth; double height = ActualHeight; foreach (var point in line) { System.Windows.Media.DrawingVisual drawingVisual = new System.Windows.Media.DrawingVisual(); DrawingContext drawingContext = drawingVisual.RenderOpen(); double x = point.X * width; double y = height - point.Y * height; drawingContext.DrawEllipse(Brushes.Blue, null, new Point(x, y), 1, 1); drawingContext.Close(); _children.Add(drawingVisual); } foreach (var point in points) { System.Windows.Media.DrawingVisual drawingVisual = new System.Windows.Media.DrawingVisual(); DrawingContext drawingContext = drawingVisual.RenderOpen(); Pen pen = new Pen(Brushes.AntiqueWhite, 3); drawingContext.DrawEllipse(Brushes.Transparent, pen, new Point(point.Key * width, height - point.Value * height), 3, 3); drawingContext.Close(); _children.Add(drawingVisual); } }
private void OnSelectTileImageSourceCommand() { var openFileService = this.GetDependencyResolver().Resolve<IOpenFileService>(); openFileService.Filter = Constants.SupportedImageSourceFilter; openFileService.CheckFileExists = true; if (openFileService.DetermineFile()) { var imageSource = new BitmapImage(new Uri(openFileService.FileName)) { CacheOption = BitmapCacheOption.OnLoad }; if (imageSource.PixelWidth != Model.TileWidth || imageSource.PixelHeight != Model.TileHeight) { var messageService = this.GetDependencyResolver().Resolve<IMessageService>(); messageService.ShowWarningAsync($"图片分辨率必须为 {Model.TileWidth}x{Model.TileHeight}。"); return; } if (imageSource.DpiX != 96 || imageSource.DpiY != 96) { var drawing = new DrawingVisual(); using (var context = drawing.RenderOpen()) { context.DrawImage(imageSource, new Rect(0, 0, 60, 30)); } var bitmap = new RenderTargetBitmap(60, 30, 96, 96, PixelFormats.Pbgra32); bitmap.Render(drawing); TileImageSource = imageSource; return; } TileImageSource = imageSource; } }
/// <summary> /// Draw feedback ColorFrame in a correct pixel format (Pbgra32) /// </summary> /// <param name="colorFrame">Byte array corresponding to the pixel data</param> /// <param name="nWidthImage">Image Width</param> /// <param name="nHeightImage">Image Height</param> /// <returns></returns> public static byte[] FeedbackColorFrame(byte[] colorFrame, int nWidthImage, int nHeightImage) { try { // Create BitmapSource with the data pixel (pixel format : Bgr32) BitmapSource sourceColor = BitmapSource.Create(nWidthImage, nHeightImage, 96, 96, PixelFormats.Bgr32, null, colorFrame, nWidthImage * 4); DrawingVisual refDrawingVisual = new DrawingVisual(); // Draw the BitmapSource in DrawingVisual using (DrawingContext dc = refDrawingVisual.RenderOpen()) { dc.DrawImage(sourceColor, new Rect(0.0, 0.0, nWidthImage, nHeightImage)); DrawKinectModeOnStream(dc); } // Convert the pixel format to the Pbgra32 var rtb = new RenderTargetBitmap(nWidthImage, nHeightImage, 96d, 96d, PixelFormats.Pbgra32); rtb.Render(refDrawingVisual); // return a byte array with a correct pixel format return ConvertBitmapToByteArray(rtb, nWidthImage, nHeightImage); } catch (Exception ex) { DebugLog.DebugTraceLog("Error reading color frame " + ex.ToString(), true); return null; } }
public void HighlightItems(IEnumerable<object> baseObjects) { DrawingVisual drawingVisual = new DrawingVisual(); this.drawingContext_0 = drawingVisual.RenderOpen(); foreach (object current in baseObjects) { TreeItem treeItem = this.TreemapHost.FindTreeItem(current); if (treeItem != null) { this.drawingContext_0.DrawRectangle(this.brush_0, null, new Rect { X = treeItem.Bounds.X, Y = treeItem.Bounds.Y, Width = treeItem.Bounds.Width, Height = treeItem.Bounds.Height }); } } this.drawingContext_0.Close(); this.drawingContext_0 = null; Matrix transformToDevice = PresentationSource.FromVisual(Application.Current.MainWindow).CompositionTarget.TransformToDevice; double dpiX = transformToDevice.M11 * 96.0; double dpiY = transformToDevice.M22 * 96.0; if (this.TreemapHost.DesiredWidth == 0.0 || this.TreemapHost.DesiredHeight == 0.0) { base.Source = null; } else { RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap(Convert.ToInt32(this.TreemapHost.DesiredWidth), Convert.ToInt32(this.TreemapHost.DesiredHeight), dpiX, dpiY, PixelFormats.Default); renderTargetBitmap.Render(drawingVisual); base.Source = renderTargetBitmap; } }
public static Sm.DrawingVisual ToVisualDrawing(this Shape input) { Sm.DrawingVisual drawingVisual = new Sm.DrawingVisual(); Sm.DrawingContext drawingContext = drawingVisual.RenderOpen(); Sm.GeometryGroup drawing = new Sm.GeometryGroup(); if (input.IsCompound) { foreach (Geometry geo in input.Geometries) { Sm.Geometry geometry = geo.ToGeometry(); drawing.Children.Add(geometry); } } else { Sm.Geometry geometry = input.ToGeometry(); drawing.Children.Add(geometry); } drawingContext.DrawGeometry(input.Graphic.Fill.ToMediaBrush(), input.Graphic.Stroke.ToMediaPen(), drawing); drawingContext.Close(); if (input.Graphic.Effects.HasBlurEffect) { drawingVisual.Effect = input.Graphic.Effects.Blur.ToMediaEffect(); } if (input.Graphic.Effects.HasShadowEffect) { drawingVisual.Effect = input.Graphic.Effects.Shadow.ToMediaEffect(); } return(drawingVisual); }
private ImageSource CreateImage(CustomMaterial material) { var bitmapSourceBackground = material.FlyerFrontSide.ToBitmapImage(); var visual = new DrawingVisual(); using (var drawingContext = visual.RenderOpen()) { drawingContext.PushClip(new RectangleGeometry(new Rect(0, 0, bitmapSourceBackground.Width, bitmapSourceBackground.Height))); drawingContext.DrawImage(bitmapSourceBackground, new Rect(0, 0, bitmapSourceBackground.Width, bitmapSourceBackground.Height)); foreach (var textField in material.MaterialFields.Select(materialToTextFieldConverter.CreateTextField)) { drawingContext.DrawText(textField.FormattedText, textField.Origin); } if (material.CustomLogo.HasLogo) { var flyerLogo = material.CustomLogo.Logo.ToBitmapImage(); drawingContext.DrawImage(flyerLogo, new Rect(material.CustomLogo.LogoLeftMargin, material.CustomLogo.LogoTopMargin, material.CustomLogo.LogoWidth, material.CustomLogo.LogoHeight)); } } var image = new DrawingImage(visual.Drawing); image.Freeze(); return image; }
/// <summary> /// Creates a new System.Windows.Media.ImageSource of a specified FontAwesomeIcon and foreground System.Windows.Media.Brush. /// </summary> /// <param name="icon">The FontAwesome icon to be drawn.</param> /// <param name="foregroundBrush">The System.Windows.Media.Brush to be used as the foreground.</param> /// <returns>A new System.Windows.Media.ImageSource</returns> public static System.Windows.Media.ImageSource GetImageSource(int icon, System.Windows.Media.Brush foregroundBrush, double emSize = 100, double margin = 0) { string charIcon = char.ConvertFromUtf32(icon); if (_Typeface == null) { _Typeface = new System.Windows.Media.Typeface(FontFamily, System.Windows.FontStyles.Normal, System.Windows.FontWeights.Normal, System.Windows.FontStretches.Normal); } ; System.Windows.Media.DrawingVisual visual = new System.Windows.Media.DrawingVisual(); using (System.Windows.Media.DrawingContext drawingContext = visual.RenderOpen()) { FormattedText ft = new System.Windows.Media.FormattedText( charIcon, System.Globalization.CultureInfo.InvariantCulture, System.Windows.FlowDirection.LeftToRight, _Typeface, emSize - (2 * margin), foregroundBrush); ft.TextAlignment = System.Windows.TextAlignment.Center; drawingContext.DrawRectangle(null, new Pen(Brushes.Black, 0), new System.Windows.Rect(0, 0, emSize, emSize)); drawingContext.DrawText(ft, new System.Windows.Point(emSize / 2, margin)); }; return(new System.Windows.Media.DrawingImage(visual.Drawing)); }
// Create a DrawingVisual that contains a rectangle. private System.Windows.Media.DrawingVisual CreateUniverseGrid(bool[,] universe, int width, int height) { System.Windows.Media.DrawingVisual drawingVisual = new System.Windows.Media.DrawingVisual(); // Retrieve the DrawingContext in order to create new drawing content. DrawingContext drawingContext = drawingVisual.RenderOpen(); int cellWidth = width / universe.GetLength(0); int cellHeight = height / universe.GetLength(1); for (int i = 0; i < universe.GetLength(0); i++) { for (int j = 0; j < universe.GetLength(1); j++) { // Create a rectangle and draw it in the DrawingContext. Rect rect = new Rect(new Point(i * cellWidth, j * cellHeight), new Size(cellWidth, cellHeight)); drawingContext.DrawRectangle( brush: !universe[i, j] ? Brushes.Black : Brushes.LightSalmon, pen: new Pen(Brushes.DarkGray, 1), rectangle: rect); } } // Persist the drawing content. drawingContext.Close(); return(drawingVisual); }
protected override void OnUpdate(double[] values) { const double space = 3; const double barwidth = 8; int pts = values.Length / 2; int width = 1000;//pts * (space + barwidth) - space; int height = width / 4; if (_bmp == null || width != _bmp.PixelWidth) { _bmp = new RenderTargetBitmap(width, height, 120, 96, PixelFormats.Pbgra32); } DrawingVisual drawingVisual = new DrawingVisual(); DrawingContext drawingContext = drawingVisual.RenderOpen(); Brush brush = DrawingBrush.Clone(); brush.Freeze(); double totalWidth = width / pts; double totalBarWidth = totalWidth * ((barwidth) / (barwidth + space)); double totalSpace = totalWidth * ((space) / (barwidth + space)); for (int i = 0; i < pts; i++) { double x = i * totalWidth; double y1 = height; double y2 = y1 - values[i] * height; drawingContext.DrawRectangle(brush, null, new Rect(x, y2, totalBarWidth, y1)); } drawingContext.Close(); _bmp.Clear(); _bmp.Render(drawingVisual); PART_visualationDisplay.Source = _bmp; }
/// <summary> /// /// </summary> /// <param name="container"></param> /// <param name="renderer"></param> /// <returns></returns> private static Viewbox ToViewbox(Container container, IRenderer renderer) { var visual = new DrawingVisual(); using (var dc = visual.RenderOpen()) { renderer.Draw(dc, container, container.Properties, null); } visual.Drawing.Freeze(); var host = new VisualHost() { Width = container.Width, Height = container.Height }; host.Visuals.Add(visual); var vb = new Viewbox() { Stretch = Stretch.Uniform }; vb.Child = host; return vb; }
/// /// Gets a JPG "screenshot" of the current UIElement /// /// UIElement to screenshot /// Scale to render the screenshot /// JPG Quality /// Byte array of JPG data public byte[] GetJpgImage(double scale, int quality, int dpi) { double actualHeight = this.RootVisual.RenderSize.Height; double actualWidth = this.RootVisual.RenderSize.Width; double renderHeight = actualHeight * scale; double renderWidth = actualWidth * scale; RenderTargetBitmap renderTarget = new RenderTargetBitmap((int)renderWidth, (int)renderHeight, dpi, dpi, PixelFormats.Pbgra32); VisualBrush sourceBrush = new VisualBrush(this.RootVisual); DrawingVisual drawingVisual = new DrawingVisual(); DrawingContext drawingContext = drawingVisual.RenderOpen(); using (drawingContext) { drawingContext.PushTransform(new ScaleTransform(scale, scale)); drawingContext.DrawRectangle(sourceBrush, null, new Rect(new Point(0, 0), new Point(actualWidth, actualHeight))); } renderTarget.Render(drawingVisual); JpegBitmapEncoder jpgEncoder = new JpegBitmapEncoder(); jpgEncoder.QualityLevel = quality; jpgEncoder.Frames.Add(BitmapFrame.Create(renderTarget)); Byte[] _imageArray; using (MemoryStream outputStream = new MemoryStream()) { jpgEncoder.Save(outputStream); _imageArray = outputStream.ToArray(); } return _imageArray; }
public override DocumentPage GetPage(int pageNumber) { // Get the requested page. DocumentPage page = flowDocumentPaginator.GetPage(pageNumber); // Wrap the page in a Visual. You can then add a transformation and extras. ContainerVisual newVisual = new ContainerVisual(); newVisual.Children.Add(page.Visual); // Create a header. DrawingVisual header = new DrawingVisual(); using (DrawingContext context = header.RenderOpen()) { Typeface typeface = new Typeface("Times New Roman"); FormattedText text = new FormattedText("Page " + (pageNumber + 1).ToString(), CultureInfo.CurrentCulture, FlowDirection.LeftToRight, typeface, 14, Brushes.Black); // Leave a quarter-inch of space between the page edge and this text. context.DrawText(text, new Point(96*0.25, 96*0.25)); } // Add the title to the visual. newVisual.Children.Add(header); // Wrap the visual in a new page. DocumentPage newPage = new DocumentPage(newVisual); return newPage; }
public static byte[] GetScreenShot(this UIElement source, double scale, int quality) { double renderHeight = source.RenderSize.Height * scale; double renderWidth = source.RenderSize.Width * scale; RenderTargetBitmap renderTarget = new RenderTargetBitmap((int)renderWidth, (int)renderHeight, 96, 96, PixelFormats.Pbgra32); VisualBrush sourceBrush = new VisualBrush(source); DrawingVisual drawingVisual = new DrawingVisual(); DrawingContext drawingContext = drawingVisual.RenderOpen(); using (drawingContext) { drawingContext.PushTransform(new ScaleTransform(scale, scale)); drawingContext.DrawRectangle(sourceBrush, null, new Rect(new Point(0, 0), new Point(source.RenderSize.Width, source.RenderSize.Height))); } renderTarget.Render(drawingVisual); JpegBitmapEncoder jpgEncoder = new JpegBitmapEncoder(); jpgEncoder.QualityLevel = quality; jpgEncoder.Frames.Add(BitmapFrame.Create(renderTarget)); Byte[] image; using (MemoryStream outputStream = new MemoryStream()) { jpgEncoder.Save(outputStream); image = outputStream.ToArray(); } return image; }
protected override sealed void CreateImage(ImageGenerationContext context) { base.CreateImage(context); Rect bounds = new Rect(StrokeWidth / 2, StrokeWidth / 2, CalculatedWidth - StrokeWidth, CalculatedHeight - StrokeWidth); Brush brush = Fill.GetBrush(); Pen pen = GetPen(); DrawingVisual dv = new DrawingVisual(); DrawingContext dc = dv.RenderOpen(); if (Roundness == 0) dc.DrawRectangle(brush, pen, bounds); else dc.DrawRoundedRectangle(brush, pen, bounds, Roundness, Roundness); dc.Close(); RenderTargetBitmap rtb = RenderTargetBitmapUtility.CreateRenderTargetBitmap(CalculatedWidth, CalculatedHeight); rtb.Render(dv); Bitmap = new FastBitmap(rtb); }
public static RenderTargetBitmap GetImage(UIElement fe, Brush background = null, Size sz = default(Size), int dpi = 144) { if (sz.Width < alib.Math.math.ε || sz.Height < alib.Math.math.ε) { fe.Measure(util.infinite_size); sz = fe.DesiredSize; //VisualTreeHelper.GetContentBounds(fe).Size; // } DrawingVisual dv = new DrawingVisual(); RenderOptions.SetEdgeMode(dv, EdgeMode.Aliased); using (DrawingContext ctx = dv.RenderOpen()) { Rect r = new Rect(0, 0, sz.Width, sz.Height); if (background != null) ctx.DrawRectangle(background, null, r); VisualBrush br = new VisualBrush(fe); br.AutoLayoutContent = true; ctx.DrawRectangle(br, null, r); } Double f = dpi / 96.0; RenderTargetBitmap bitmap = new RenderTargetBitmap( (int)(sz.Width * f) + 1, (int)(sz.Height * f) + 1, dpi, dpi, PixelFormats.Pbgra32); bitmap.Render(dv); return bitmap; }
protected override sealed void CreateImage() { base.CreateImage(); Rect bounds = new Rect(StrokeWidth / 2, StrokeWidth / 2, CalculatedWidth - StrokeWidth, CalculatedHeight - StrokeWidth); Brush brush = Fill.GetBrush(); PointCollection points = GetPoints(bounds); PathGeometry geometry = CanonicalSplineHelper.CreateSpline(points, Roundness / 100.0, null, true, true, 0.25); Pen pen = GetPen(); DrawingVisual dv = new DrawingVisual(); DrawingContext dc = dv.RenderOpen(); // Draw polygon. dc.DrawGeometry(brush, pen, geometry); dc.Close(); RenderTargetBitmap rtb = RenderTargetBitmapUtility.CreateRenderTargetBitmap(CalculatedWidth, CalculatedHeight); rtb.Render(dv); Bitmap = new FastBitmap(rtb); }
public System.IO.MemoryStream GetPNGImage2(double width, double height, double actualWidth, double actualHeight, bool whiteBG = false) { double dpiX = (width / actualWidth) * 96d; double dpiY = (height / actualHeight) * 96d; RenderTargetBitmap bitmap = new RenderTargetBitmap((int)width, (int)height, dpiX, dpiY, PixelFormats.Default); if (whiteBG) { DrawingVisual backgroundVisual = new System.Windows.Media.DrawingVisual(); using (var dc = backgroundVisual.RenderOpen()) dc.DrawRectangle(Brushes.White, null, new Rect(0, 0, actualWidth, actualHeight)); bitmap.Render(backgroundVisual); } bitmap.Render(m_visual); PngBitmapEncoder encoder = new PngBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(bitmap)); System.IO.MemoryStream returnStream = new System.IO.MemoryStream(); encoder.Save(returnStream); returnStream.Flush(); m_visual.Offset = new Vector(0, 0); return(returnStream); }
/// <summary> /// Applies the filter to the specified <paramref name="bitmap"/>. This method /// first calls <see cref="ImageReplacementFilter.GetDestinationDimensions(FastBitmap, out Int32, out Int32)" /> /// to calculate the size of the destination image. Then it calls /// <see cref="ImageReplacementFilter.ApplyFilter(FastBitmap, DrawingContext, int, int)" /> /// which is where the overridden class implements its filter algorithm. /// </summary> /// <param name="bitmap"> /// Image to apply the <see cref="ImageReplacementFilter" /> to. /// </param> public override sealed void ApplyFilter(FastBitmap bitmap) { OnBeginApplyFilter(bitmap); // get destination dimensions int width, height; bool shouldContinue = GetDestinationDimensions(bitmap, out width, out height); if (!shouldContinue) return; DrawingVisual dv = new DrawingVisual(); ConfigureDrawingVisual(bitmap, dv); DrawingContext dc = dv.RenderOpen(); ApplyFilter(bitmap, dc, width, height); dc.Close(); RenderTargetBitmap rtb = RenderTargetBitmapUtility.CreateRenderTargetBitmap(width, height); rtb.Render(dv); FastBitmap destination = new FastBitmap(rtb); // copy metadata // TODO /*foreach (PropertyItem propertyItem in bitmap.InnerBitmap.PropertyItems) destination.InnerBitmap.SetPropertyItem(propertyItem);*/ // set new image bitmap.InnerBitmap = destination.InnerBitmap; OnEndApplyFilter(); }
public void Init_DrawLT(int running_train) { int i; int temp; int late_time_range; late_time_range = 1000; temp = 0; x1 = 30; y1 = 10; x2 = 700; y2 = 580; narrow_x = (double)running_train / (x2 - x1); narrow_y = (double)late_time_range / (y2 - y1); drawingVisual = new DrawingVisual(); dc = drawingVisual.RenderOpen(); dc.DrawLine(new Pen(Brushes.Black, 1.5), new Point(x1, x1), new Point(x1, y2)); dc.DrawLine(new Pen(Brushes.Black, 1.5), new Point(x1, y2), new Point(x2, y2)); dc.DrawText(new FormattedText("N", CultureInfo.GetCultureInfo("en-us"), FlowDirection.LeftToRight, new Typeface("Verdana"), 12, System.Windows.Media.Brushes.Black), new System.Windows.Point(x2 - 30, y2 + 6)); dc.DrawText(new FormattedText("T", CultureInfo.GetCultureInfo("en-us"), FlowDirection.LeftToRight, new Typeface("Verdana"), 12, System.Windows.Media.Brushes.Black), new System.Windows.Point(x1 - 10, y1 - 8)); for (i = 0; i < (x2 - x1); i++) { if (i % ((x2 - x1) / 5) == 0) { dc.DrawLine(new Pen(Brushes.Black, 1.5), new Point(x1 + i, y2), new Point(x1 + i, y2 - 3)); dc.DrawText(new FormattedText((temp * running_train / 5).ToString(), CultureInfo.GetCultureInfo("en-us"), FlowDirection.LeftToRight, new Typeface("Verdana"), 12, System.Windows.Media.Brushes.Black), new System.Windows.Point(i + x1 - 5, y2 + 7)); temp++; } } temp = 0; for (i = 0; i < (y2 - y1); i++) { if (i % ((y2 - y1) / 5) == 0) { dc.DrawLine(new Pen(Brushes.Black, 1.5), new Point(x1, y2 - i), new Point(x1 + 3, y2 - i)); dc.DrawText(new FormattedText((temp * late_time_range / 5).ToString(), CultureInfo.GetCultureInfo("en-us"), FlowDirection.LeftToRight, new Typeface("Verdana"), 12, System.Windows.Media.Brushes.Black), new System.Windows.Point(x1 - 28, y2 - i - 9)); temp++; } } }
/// <summary> /// </summary> /// <param name="source"> </param> /// <param name="scale"> </param> /// <param name="quality"> </param> /// <returns> </returns> public static byte[] GetJpgImage(UIElement source, double scale, int quality) { var actualHeight = source.RenderSize.Height; var actualWidth = source.RenderSize.Width; var renderHeight = actualHeight * scale; var renderWidth = actualWidth * scale; var renderTarget = new RenderTargetBitmap((int) renderWidth, (int) renderHeight, 96, 96, PixelFormats.Pbgra32); var sourceBrush = new VisualBrush(source); var drawingVisual = new DrawingVisual(); var drawingContext = drawingVisual.RenderOpen(); using (drawingContext) { drawingContext.PushTransform(new ScaleTransform(scale, scale)); drawingContext.DrawRectangle(sourceBrush, null, new Rect(new Point(0, 0), new Point(actualWidth, actualHeight))); } renderTarget.Render(drawingVisual); var jpgEncoder = new JpegBitmapEncoder { QualityLevel = quality }; jpgEncoder.Frames.Add(BitmapFrame.Create(renderTarget)); Byte[] imageArray; using (var outputStream = new MemoryStream()) { jpgEncoder.Save(outputStream); imageArray = outputStream.ToArray(); } return imageArray; }
public void SetPreviewElement(FrameworkElement element) { double x = 0; double y = 0; GetCurrentDPI(out x, out y); // Does the DrawingBrush thing seem a little hacky? Yeah, it's a necessary hack. See: // http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=364041 Rect bounds = VisualTreeHelper.GetDescendantBounds(element); RenderTargetBitmap r = new RenderTargetBitmap((int)(element.ActualWidth * x / 96), (int)(element.ActualHeight * y / 96), (int)x, (int)y, PixelFormats.Pbgra32); DrawingVisual dv = new DrawingVisual(); using (DrawingContext ctx = dv.RenderOpen()) { VisualBrush vb = new VisualBrush(element); ctx.DrawRectangle(vb, null, new Rect(new Point(), bounds.Size)); } r.Render(dv); DragImage = r; InvalidateMeasure(); }
public static RenderTargetBitmap GetRenderTargetBitmap(this UIElement source, double scale) { if (source.RenderSize.Height == 0 || source.RenderSize.Width == 0) return null; double actualHeight = source.RenderSize.Height; double actualWidth = source.RenderSize.Width; double renderHeight = actualHeight*scale; double renderWidth = actualWidth*scale; var renderTarget = new RenderTargetBitmap((int) renderWidth, (int) renderHeight, 96, 96, PixelFormats.Pbgra32); var sourceBrush = new VisualBrush(source); var drawingVisual = new DrawingVisual(); DrawingContext drawingContext = drawingVisual.RenderOpen(); using (drawingContext) { drawingContext.PushTransform(new ScaleTransform(scale, scale)); drawingContext.DrawRectangle(sourceBrush, null, new Rect(new Point(0, 0), new Point(actualWidth, actualHeight))); } renderTarget.Render(drawingVisual); return renderTarget; }
public void SaveToPng( Canvas surface, string file ) { // Save current canvas transform var transform = surface.LayoutTransform; // reset current transform (in case it is scaled or rotated) surface.LayoutTransform = null; var size = new Size( 1600, 900 ); // Attentation: Measure and arrange the surface ! surface.Measure( size ); surface.Arrange( new Rect( size ) ); var renderBitmap = new RenderTargetBitmap( (int)size.Width, (int)size.Height, 96d, 96d, PixelFormats.Pbgra32 ); var bounds = VisualTreeHelper.GetDescendantBounds( surface ); var dv = new DrawingVisual(); using ( var ctx = dv.RenderOpen() ) { var vb = new VisualBrush( surface ); ctx.DrawRectangle( vb, null, new Rect( new Point(), bounds.Size ) ); } renderBitmap.Render( dv ); using ( var outStream = new FileStream( file, FileMode.OpenOrCreate, FileAccess.Write ) ) { var encoder = new PngBitmapEncoder(); encoder.Frames.Add( BitmapFrame.Create( renderBitmap ) ); encoder.Save( outStream ); } // Restore previously saved layout surface.LayoutTransform = transform; }
protected override Effect GetEffect(FastBitmap source) { // Fill temporary graphics buffer with mask (currently always a rectangle). DrawingVisual dv = new DrawingVisual { Effect = new BlurEffect { Radius = Radius, KernelType = KernelType.Gaussian } }; DrawingContext dc = dv.RenderOpen(); dc.DrawImage(source.InnerBitmap, new Rect(0, 0, source.Width, source.Height)); dc.Close(); RenderTargetBitmap rtb = RenderTargetBitmapUtility.CreateRenderTargetBitmap(source.Width, source.Height); rtb.Render(dv); Brush blurredImage = new ImageBrush(rtb); return new UnsharpMaskEffect { BlurMask = blurredImage, Amount = Amount / 100.0, Threshold = Threshold }; }
/// <summary> /// Преобразует XAML Drawing/DrawingGroup в png base64 string /// </summary> /// <param name="width"></param> /// <param name="height"></param> /// <param name="drawing"></param> /// <returns>Base64 string containing png bitmap</returns> public static string XamlDrawingToPngBase64String(int width, int height, Drawing drawing) { var bitmapEncoder = new PngBitmapEncoder(); // The image parameters... double dpiX = 96; double dpiY = 96; // The Visual to use as the source of the RenderTargetBitmap. var drawingVisual = new DrawingVisual(); using (var drawingContext = drawingVisual.RenderOpen()) { drawingContext.DrawDrawing(drawing); } var bounds = drawingVisual.ContentBounds; var targetBitmap = new RenderTargetBitmap( width * 10, height * 10, dpiX, dpiY, PixelFormats.Pbgra32); drawingVisual.Transform = new ScaleTransform(width * 10 / bounds.Width, height * 10 / bounds.Height); targetBitmap.Render(drawingVisual); // Encoding the RenderBitmapTarget as an image. bitmapEncoder.Frames.Add(BitmapFrame.Create(targetBitmap)); byte[] values; using (var str = new MemoryStream()) { bitmapEncoder.Save(str); values = str.ToArray(); } return Convert.ToBase64String(values); }
public void CreateFromImage(Bitmap image) { this.image = image; initialClip = new RectangleF(0, 0, image.Width, image.Height); bounds = initialClip.ToWpf(); visual = drawingVisual = new swm.DrawingVisual(); Control = drawingVisual.RenderOpen(); Control.DrawImage(image.ToWpf(1), bounds); }
public void CreateFromImage(Bitmap image) { this.image = image; drawingVisual = new swm.DrawingVisual(); Control = drawingVisual.RenderOpen(); Control.DrawImage(image.ControlObject as swm.ImageSource, new sw.Rect(0, 0, image.Size.Width, image.Size.Height)); visual = drawingVisual; this.ImageInterpolation = Eto.Drawing.ImageInterpolation.Default; }
// Create a DrawingVisual that contains an ellipse. private System.Windows.Media.DrawingVisual CreateDrawingVisualEllipses() { System.Windows.Media.DrawingVisual drawingVisual = new System.Windows.Media.DrawingVisual(); DrawingContext drawingContext = drawingVisual.RenderOpen(); drawingContext.DrawEllipse(Brushes.Maroon, null, new Point(430, 136), 20, 20); drawingContext.Close(); return(drawingVisual); }
public void CreateFromImage(Bitmap image) { this.image = image; bounds = new sw.Rect(0, 0, image.Size.Width, image.Size.Height); drawingVisual = new swm.DrawingVisual(); visual = drawingVisual; Control = drawingVisual.RenderOpen(); Control.DrawImage(image.ControlObject as swm.ImageSource, bounds); PushGuideLines(bounds); ImageInterpolation = ImageInterpolation.Default; }
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); }
public void Clear(SolidBrush brush) { var rect = clipBounds ?? initialClip; if (drawingVisual != null) { CloseGroup(); // bitmap Control.Close(); var newbmp = new swmi.RenderTargetBitmap((int)bounds.Width, (int)bounds.Height, 96, 96, swm.PixelFormats.Pbgra32); newbmp.RenderWithCollect(visual); swm.Geometry maskgeometry; if (clipPath != null) { maskgeometry = clipPath; } else { maskgeometry = new swm.RectangleGeometry(rect.ToWpf()); } var boundsgeometry = new swm.RectangleGeometry(bounds); maskgeometry = swm.Geometry.Combine(boundsgeometry, maskgeometry, swm.GeometryCombineMode.Exclude, null); var dr = new swm.GeometryDrawing(swm.Brushes.Black, null, maskgeometry); var db = new swm.DrawingBrush(dr); visual = drawingVisual = new swm.DrawingVisual(); Control = drawingVisual.RenderOpen(); Control.PushOpacityMask(db); Control.DrawImage(newbmp, bounds); Control.Pop(); ApplyAll(); } else { // drawable if (brush == null || brush.Color.A < 1.0f) { Widget.FillRectangle(Brushes.Black, rect); } } if (brush != null) { Widget.FillRectangle(brush, rect); } }
// Create a DrawingVisual that contains a rectangle. private System.Windows.Media.DrawingVisual CreateDrawingVisualRectangle() { System.Windows.Media.DrawingVisual drawingVisual = new System.Windows.Media.DrawingVisual(); // Retrieve the DrawingContext in order to create new drawing content. DrawingContext drawingContext = drawingVisual.RenderOpen(); // Create a rectangle and draw it in the DrawingContext. Rect rect = new Rect(new Point(160, 100), new Size(320, 80)); drawingContext.DrawRectangle(Brushes.LightBlue, null, rect); // Persist the drawing content. drawingContext.Close(); return(drawingVisual); }
/// <summary> /// Resizes a bitmap frame /// </summary> /// <param name="photo"></param> /// <param name="width"></param> /// <param name="height"></param> /// <param name="scalingMode"></param> /// <returns></returns> public static BitmapFrame Resize(BitmapFrame photo, int width, int height, System.Windows.Media.BitmapScalingMode scalingMode) { var group = new System.Windows.Media.DrawingGroup(); System.Windows.Media.RenderOptions.SetBitmapScalingMode(group, scalingMode); group.Children.Add(new System.Windows.Media.ImageDrawing(photo, new System.Windows.Rect(0, 0, width, height))); var targetVisual = new System.Windows.Media.DrawingVisual(); var targetContext = targetVisual.RenderOpen(); targetContext.DrawDrawing(group); var target = new RenderTargetBitmap(width, height, 96, 96, System.Windows.Media.PixelFormats.Default); targetContext.Close(); target.Render(targetVisual); var targetFrame = BitmapFrame.Create(target); return(targetFrame); }
public void Create(Image image, int width, int height, ImageInterpolation interpolation) { ApplicationHandler.InvokeIfNecessary(() => { var source = image.ToWpf(); // use drawing group to allow for better quality scaling var group = new swm.DrawingGroup(); swm.RenderOptions.SetBitmapScalingMode(group, interpolation.ToWpf()); group.Children.Add(new swm.ImageDrawing(source, new sw.Rect(0, 0, width, height))); var drawingVisual = new swm.DrawingVisual(); using (var drawingContext = drawingVisual.RenderOpen()) drawingContext.DrawDrawing(group); var resizedImage = new swm.Imaging.RenderTargetBitmap(width, height, source.DpiX, source.DpiY, swm.PixelFormats.Default); resizedImage.Render(drawingVisual); Control = resizedImage; }); }
public override object Resize(object handle, double width, double height) { var oldImg = (SWMI.BitmapSource)handle; width = WidthToDPI(oldImg, width); height = HeightToDPI(oldImg, height); SWM.DrawingVisual visual = new SWM.DrawingVisual(); using (SWM.DrawingContext ctx = visual.RenderOpen()) { ctx.DrawImage(oldImg, new System.Windows.Rect(0, 0, width, height)); } SWMI.RenderTargetBitmap bmp = new SWMI.RenderTargetBitmap((int)width, (int)height, oldImg.DpiX, oldImg.DpiY, oldImg.Format); bmp.Render(visual); return(bmp); }
static swmi.BitmapFrame Resize(swmi.BitmapSource image, float scale, int width, int height, swm.BitmapScalingMode scalingMode) { 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(); var targetContext = targetVisual.RenderOpen(); targetContext.DrawDrawing(group); width = (int)Math.Round(width * scale); height = (int)Math.Round(height * scale); var target = new swmi.RenderTargetBitmap(width, height, 96 * scale, 96 * scale, swm.PixelFormats.Default); targetContext.Close(); target.Render(targetVisual); return(swmi.BitmapFrame.Create(target)); }
private DrawingVisual CreateDrawingVisualAA() { System.Windows.Media.DrawingVisual drawingVisual = new System.Windows.Media.DrawingVisual(); DrawingContext drawingContext = drawingVisual.RenderOpen(); drawingVisual.XSnappingGuidelines = new DoubleCollection(new List <double>() { 1 }); drawingVisual.YSnappingGuidelines = new DoubleCollection(new List <double>() { 1 }); drawingContext.DrawLine(new Pen(Brushes.Maroon, 1), new Point(430, 136), new Point(136, 430)); drawingContext.Close(); return(drawingVisual); }
public override object Crop(object handle, int srcX, int srcY, int w, int h) { var oldImg = (SWMI.BitmapSource)handle; double width = WidthToDPI(oldImg, w); double height = HeightToDPI(oldImg, h); SWM.DrawingVisual visual = new SWM.DrawingVisual(); using (SWM.DrawingContext ctx = visual.RenderOpen()) { //Not sure whether this actually works, untested ctx.DrawImage(oldImg, new System.Windows.Rect(-srcX, -srcY, srcX + width, srcY + height)); } SWMI.RenderTargetBitmap bmp = new SWMI.RenderTargetBitmap((int)width, (int)height, oldImg.DpiX, oldImg.DpiY, oldImg.Format); bmp.Render(visual); return(bmp); }
ImageSource RenderFrame(ApplicationContext actx, double scaleFactor, double width, double height) { ImageDescription idesc = new ImageDescription() { Alpha = 1, Size = new Size(width * scaleFactor, height * scaleFactor) }; SWM.DrawingVisual visual = new SWM.DrawingVisual(); using (SWM.DrawingContext ctx = visual.RenderOpen()) { Draw(actx, ctx, 1, 0, 0, idesc); } SWMI.RenderTargetBitmap bmp = new SWMI.RenderTargetBitmap((int)idesc.Size.Width, (int)idesc.Size.Height, 96, 96, PixelFormats.Pbgra32); bmp.Render(visual); AddFrame(bmp); return(bmp); }
ImageSource RenderFrame(ApplicationContext actx, double scaleFactor, ImageDescription idesc) { SWM.DrawingVisual visual = new SWM.DrawingVisual(); using (SWM.DrawingContext ctx = visual.RenderOpen()) { ctx.PushTransform(new ScaleTransform(scaleFactor, scaleFactor)); Draw(actx, ctx, scaleFactor, 0, 0, idesc); ctx.Pop(); } SWMI.RenderTargetBitmap bmp = new SWMI.RenderTargetBitmap((int)(idesc.Size.Width * scaleFactor), (int)(idesc.Size.Height * scaleFactor), 96, 96, PixelFormats.Pbgra32); bmp.Render(visual); var f = new ImageFrame(bmp, idesc.Size.Width, idesc.Size.Height); if (drawCallback == null) { AddFrame(f); } return(bmp); }
// Create a DrawingVisual that contains text. private System.Windows.Media.DrawingVisual CreateDrawingVisualText() { // Create an instance of a DrawingVisual. System.Windows.Media.DrawingVisual drawingVisual = new System.Windows.Media.DrawingVisual(); // Retrieve the DrawingContext from the DrawingVisual. DrawingContext drawingContext = drawingVisual.RenderOpen(); // Draw a formatted text string into the DrawingContext. drawingContext.DrawText( new FormattedText("Click Me!", CultureInfo.GetCultureInfo("en-us"), FlowDirection.LeftToRight, new Typeface("Verdana"), 36, Brushes.Black), new Point(200, 116)); // Close the DrawingContext to persist changes to the DrawingVisual. drawingContext.Close(); return(drawingVisual); }
private DrawingVisual CreateDrawingImage() { var uri = $"wallpaper_mikael_gustafsson.png"; System.Windows.Media.DrawingVisual drawingVisual = new System.Windows.Media.DrawingVisual(); DrawingContext drawingContext = drawingVisual.RenderOpen(); drawingVisual.XSnappingGuidelines = new DoubleCollection(new List <double>() { 1 }); drawingVisual.YSnappingGuidelines = new DoubleCollection(new List <double>() { 1 }); //Image image = new Image() { Source = }; var source = new BitmapImage(new Uri(uri, UriKind.Relative)); drawingContext.DrawImage(source, new Rect(new Size(800, 450))); drawingContext.Close(); return(drawingVisual); }
ImageSource RenderFrame(ApplicationContext actx, double scaleFactor, double width, double height) { ImageDescription idesc = new ImageDescription() { Alpha = 1, Size = new Size(width, height) }; SWM.DrawingVisual visual = new SWM.DrawingVisual(); using (SWM.DrawingContext ctx = visual.RenderOpen()) { ctx.PushTransform(new ScaleTransform(scaleFactor, scaleFactor)); Draw(actx, ctx, scaleFactor, 0, 0, idesc); ctx.Pop(); } SWMI.RenderTargetBitmap bmp = new SWMI.RenderTargetBitmap((int)(width * scaleFactor), (int)(height * scaleFactor), 96, 96, PixelFormats.Pbgra32); bmp.Render(visual); var f = new ImageFrame(bmp, width, height); AddFrame(f); return(bmp); }
// Create a DrawingVisual that contains text. private System.Windows.Media.DrawingVisual CreateDrawingVisualText() { // Create an instance of a DrawingVisual. System.Windows.Media.DrawingVisual drawingVisual = new System.Windows.Media.DrawingVisual(); // Retrieve the DrawingContext from the DrawingVisual. DrawingContext drawingContext = drawingVisual.RenderOpen(); #pragma warning disable CS0618 // 'FormattedText.FormattedText(string, CultureInfo, FlowDirection, Typeface, double, Brush)' is obsolete: 'Use the PixelsPerDip override' // Draw a formatted text string into the DrawingContext. drawingContext.DrawText( new FormattedText("Click Me!", CultureInfo.GetCultureInfo("en-us"), FlowDirection.LeftToRight, new Typeface("Verdana"), 36, Brushes.Black), new Point(200, 116)); #pragma warning restore CS0618 // 'FormattedText.FormattedText(string, CultureInfo, FlowDirection, Typeface, double, Brush)' is obsolete: 'Use the PixelsPerDip override' // Close the DrawingContext to persist changes to the DrawingVisual. drawingContext.Close(); return(drawingVisual); }
public Bitmap Shader(Bitmap src, double radius = 10) { Bitmap result = new Bitmap(src); #region Get DPI float dpiX = 96f; float dpiY = 96f; using (Graphics g = Graphics.FromHwnd(IntPtr.Zero)) { dpiX = g.DpiX; dpiY = g.DpiY; } #endregion int width = (int)Math.Ceiling(radius); int offset = 4 * width; #region Create Effect var effect = new MyShaderEffect(); //Media.Effects.ShaderRenderMode = Media.Effects.ShaderRenderMode.Auto; //effect. #endregion #region Draw source bitmap to DrawingVisual Media.DrawingVisual drawingVisual = new Media.DrawingVisual(); drawingVisual.Effect = effect; using (var drawingContext = drawingVisual.RenderOpen()) { //drawingContext.PushEffect( new Media.Effects.BlurBitmapEffect(), null ); System.Windows.Rect dRect = new System.Windows.Rect(2 * width, 2 * width, src.Width, src.Height); drawingContext.DrawImage(src.ToBitmapSource(), dRect); drawingContext.Close(); } #endregion #region Render the DrawingVisual into a RenderTargetBitmap var rtb = new Media.Imaging.RenderTargetBitmap( src.Width + offset, src.Height * offset, dpiX, dpiY, Media.PixelFormats.Pbgra32); rtb.Render(drawingVisual); #endregion #region Create a System.Drawing.Bitmap var bitmap = new Bitmap(rtb.PixelWidth, rtb.PixelHeight, PixelFormat.Format32bppArgb); #endregion #region Copy the RenderTargetBitmap pixels into the bitmap's pixel buffer var pdata = bitmap.LockBits( new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.WriteOnly, bitmap.PixelFormat); rtb.CopyPixels(System.Windows.Int32Rect.Empty, pdata.Scan0, pdata.Stride * pdata.Height, pdata.Stride); bitmap.UnlockBits(pdata); #endregion #region Crop Opaque var rect = bitmap.ContentBound(); rect.Width = rect.Width < 0 ? 1 : rect.Width + 2; rect.Height = rect.Height < 0 ? 1 : rect.Height + 2; result = new Bitmap(rect.Width, rect.Height, bitmap.PixelFormat); using (var g = Graphics.FromImage(result)) { g.DrawImage(bitmap, 0, 0, rect, GraphicsUnit.Pixel); } #endregion return(result); }
public Bitmap Shadow(Bitmap src, Color color, int width, double opacity = 0.6f, double angle = 315) { Bitmap result = new Bitmap(src); #region Get DPI float dpiX = 96f; float dpiY = 96f; using (Graphics g = Graphics.FromHwnd(IntPtr.Zero)) { dpiX = g.DpiX; dpiY = g.DpiY; } #endregion int offset = 4 * width; #region Create Effect var effect = new Media.Effects.DropShadowEffect(); effect.BlurRadius = width; effect.Color = color.ToMediaColor(); effect.Direction = angle; effect.Opacity = opacity; effect.ShadowDepth = width; //var effect = new Media.Effects.BlurEffect(); //effect.Radius = 50; #endregion #region Draw source bitmap to DrawingVisual Media.DrawingVisual drawingVisual = new Media.DrawingVisual(); drawingVisual.Effect = effect; using (var drawingContext = drawingVisual.RenderOpen()) { System.Windows.Rect dRect = new System.Windows.Rect(2 * width, 2 * width, src.Width, src.Height); drawingContext.DrawImage(src.ToBitmapSource(), dRect); drawingContext.Close(); } #endregion #region Render the DrawingVisual into a RenderTargetBitmap var rtb = new Media.Imaging.RenderTargetBitmap( src.Width + offset, src.Height + offset, dpiX, dpiY, Media.PixelFormats.Pbgra32); rtb.Render(drawingVisual); #endregion #region Create a System.Drawing.Bitmap var bitmap = new Bitmap(rtb.PixelWidth, rtb.PixelHeight, PixelFormat.Format32bppArgb); #endregion #region Copy the RenderTargetBitmap pixels into the bitmap's pixel buffer var pdata = bitmap.LockBits( new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.WriteOnly, bitmap.PixelFormat); rtb.CopyPixels(System.Windows.Int32Rect.Empty, pdata.Scan0, pdata.Stride * pdata.Height, pdata.Stride); bitmap.UnlockBits(pdata); #endregion #region Crop Transparent Area var rect = bitmap.ContentBound(); result = new Bitmap(rect.Width, rect.Height, bitmap.PixelFormat); using (var g = Graphics.FromImage(result)) { g.DrawImage(bitmap, 0, 0, rect, GraphicsUnit.Pixel); } #endregion return(result); }
public DrawGraphicsOnBitmap() { Title = "Draw Graphics on Bitmap"; // ��Ʈ���� ������� �����ϱ� ���� ����� ������. Background = Brushes.Khaki; // RenderTargetBitmap ������. RenderTargetBitmap renderbitmap = new RenderTargetBitmap(100, 100, 96, 96, PixelFormats.Default); // DrawingVisual ��ü�� ������. DrawingVisual drawvis = new DrawingVisual(); DrawingContext dc = drawvis.RenderOpen(); // Render �ҵ� ȣ�� dc.DrawRoundedRectangle(Brushes.Blue, new Pen(Brushes.Red, 10), new Rect(25, 25, 50, 50), 10, 10); dc.Close(); // RenderTargetBitmap ���� DrawingVisual ��ü�� ��. renderbitmap.Render(drawvis); // �̹��� ��ä ���� -> ������Ƽ ���� Image img = new Image(); img.Source = renderbitmap; // ��� Content = img; }