Sometimes, we need to save the content presented by the control into an image, such as: InkCanvas' handwritten ink marks, web pages in WebBrowser, etc. Some people may say, this is just a screenshot. Just find the coordinates and size of the control and call the screenshot API. Indeed, for regular controls, screenshots can be achieved. However, if the control is irregular or opacity is not 100%, the visual effect of its background control will also be cut off.
To achieve screenshots of controls only, you can use the RenderTargetBitmap class to obtain the visual effects of Visual objects, thereby achieving screenshots of controls.
RenderTargetBitmap RenderVisaulToBitmap(Visual vsual, int width, int height) { var rtb = new RenderTargetBitmap(width, height, 96, 96, ); (vsual); return rtb; }
It should be noted here that the Alignment, Margin and other attributes that affect the layout of the Visual object will also be obtained. For example, when taking a screenshot of the button below,
<Button Content="Button" Margin="10,10,0,0" VerticalAlignment="Top" HorizontalAlignment="Left" Width="75" Height="22" />
The starting point coordinate of the button is not (0,0), but (10,10). If we want to set the starting point and starting point coordinates of the button to (0,0), we need to remove Alignment, Margin and other properties in the Button property. It is necessary to remove Alignment, Margin and other attributes, and to keep the position and size of the button unchanged. A simple way is to add a Border outside the button and set these attributes in the Broder (set groupings in VisualStudio and Blend, and you can complete it in one step).
<Border Margin="10,10,0,0" VerticalAlignment="Top" HorizontalAlignment="Left" Width="75" Height="22"> <Button Content="Button"/> </Border>
Through the RenderVisaulToBitmap function, the visual effects of the control can be converted into the RenderTargetBitmap object. The RenderTargetBitmap object inherits from BitmapSource and can be displayed directly in the Image control. If you want to go further and convert it to an image, you can follow my previous postAdd shadow effects to picturesSave the BitmapSource object as a picture through a PngBitmapEncoder.
public enum ImageFormat { JPG, BMP, PNG, GIF, TIF } void GenerateImage(BitmapSource bitmap, ImageFormat format, Stream destStream) { BitmapEncoder encoder = null; switch (format) { case : encoder = new JpegBitmapEncoder(); break; case : encoder = new PngBitmapEncoder(); break; case : encoder = new BmpBitmapEncoder(); break; case : encoder = new GifBitmapEncoder(); break; case : encoder = new TiffBitmapEncoder(); break; default: throw new InvalidOperationException(); } ((bitmap)); (destStream); }
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.