wpf

[wpf] Object Capture 컨트롤 캡쳐

동동(이재동) 2016. 4. 5. 18:16
Usercontrol등 Element등을 캡쳐 할수 있도록 만들었다.

용도는 캠 이미지위에 배경및 각종 clip art들을 얹혀서 캡쳐 하기위한 용도~


public static string SaveCamCapture(string filePath, FrameworkElement targetControl)
{
targetControl.UpdateLayout();
// Get the size of the Visual and its descendants.
Rect rect = VisualTreeHelper.GetDescendantBounds(targetControl);
// Make a DrawingVisual to make a screen
// representation of the control.
DrawingVisual dv = new DrawingVisual();
// Fill a rectangle the same size as the control
// with a brush containing images of the control.
using (DrawingContext ctx = dv.RenderOpen())
{
VisualBrush brush = new VisualBrush(targetControl);
ctx.DrawRectangle(brush, null, new Rect(rect.Size));
}
RenderTargetBitmap targetBitmap = new RenderTargetBitmap((int)(targetControl.ActualWidth), (int)(targetControl.ActualHeight), 96, 96, PixelFormats.Pbgra32);
targetBitmap.Render(dv);
var bitmapEncoder = new PngBitmapEncoder();
bitmapEncoder.Frames.Add(BitmapFrame.Create(targetBitmap));
if (filePath != null)
{
using (var filestream = new FileStream(filePath, FileMode.Create))
{
bitmapEncoder.Save(filestream);
}
}
return filePath;
}