简体   繁体   中英

How to use canvas content as a bitmap?

I'm writing a paint application in WPF, and when I want make color picker or fill tool i get a problem. I dont know how to use canvas content as bitmap, the only one solution I invent is save it, and open as bitmap then I can easy operate on pixels to get and sets pixels, but I want do it in another way. Any suggestions?

If you're looking for converting your canvas UIElement to a BitmapSource so that you can manipulate it then you can take a look at this post on MSDN MSDN .

Here is the helper function to get the BitmapSource from your canvas:

public static BitmapSource CreateBitmapSourceFromVisual(
    Double width,
    Double height,
    Visual visualToRender,
    Boolean undoTransformation)
{
    if (visualToRender == null)
    {
        return null;
    }
    RenderTargetBitmap bmp = new RenderTargetBitmap((Int32)Math.Ceiling(width),                                                        (Int32)Math.Ceiling(height), 96,96, PixelFormats.Pbgra32);

    if (undoTransformation)
    {
        DrawingVisual dv = new DrawingVisual();
        using (DrawingContext dc = dv.RenderOpen())
        {
            VisualBrush vb = new VisualBrush(visualToRender);
            dc.DrawRectangle(vb, null, new Rect(new Point(), new Size(width, height)));
        }
        bmp.Render(dv);
    }
    else
    {
        bmp.Render(visualToRender);
    }
  return bmp;
}

I didn't get what do want to say by a color picker or fill tool problem, so I can't help you with that. Good luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM