“Freeze” that VisualBrush

So you can’t “freeze” a VisualBrush. But you can create an ImageBrush from a VisualBrush!

Visual Brushes are great but sometimes you want to use exactly on the screen without it changing if you obscure it from view or apply render transformations! This is really handy for situations, say like a ScatterViewItem. I created a method that, given a FrameworkElement will produce a RenderTargetBitmap of it.

Then using the RenderTargetBitmap you can generate an ImageBrush and now you can do whatever you feel like to “myControl” and it won’t affect elements that use the ImageBrush.

RenderTargetBitmap rtb = RenderBitmap(myControl);

Rectangle r = new Rectangle();

r.Fill = new ImageBrush(BitmapFrame.Create(rtb));

public RenderTargetBitmap RenderBitmap(FrameworkElement element) {

double topLeft = 0;

double topRight = 0;

int width = (int)element.ActualWidth;

int height = (int)element.ActualHeight;

double dpiX = 96; // this is the magic number

double dpiY = 96; // this is the magic number

PixelFormat pixelFormat = PixelFormats.Default;

VisualBrush elementBrush = new VisualBrush(element);

DrawingVisual visual = new DrawingVisual();

DrawingContext dc = visual.RenderOpen();

dc.DrawRectangle(elementBrush, null, new Rect(topLeft, topRight, width, height));

dc.Close();

RenderTargetBitmap bitmap = new RenderTargetBitmap(width, height, dpiX, dpiY, pixelFormat);

bitmap.Render(visual);

return bitmap;

}

One thought on ““Freeze” that VisualBrush

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s