How do I convert from a Brush (e.g. DrawingBrush) to a BitmapSource?

ⅰ亾dé卋堺 提交于 2019-12-05 07:06:32
public static BitmapSource BitmapSourceFromBrush(Brush drawingBrush, int size = 32, int dpi = 96)
{
    // RenderTargetBitmap = builds a bitmap rendering of a visual
    var pixelFormat = PixelFormats.Pbgra32;
    RenderTargetBitmap rtb = new RenderTargetBitmap(size, size, dpi, dpi, pixelFormat);

    // Drawing visual allows us to compose graphic drawing parts into a visual to render
    var drawingVisual = new DrawingVisual();
    using (DrawingContext context = drawingVisual.RenderOpen())
    {
        // Declaring drawing a rectangle using the input brush to fill up the visual
        context.DrawRectangle(drawingBrush, null, new Rect(0, 0, size, size));
    }

    // Actually rendering the bitmap
    rtb.Render(drawingVisual);
    return rtb;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!