将XAML对象转换为SoftwareBitmap

时间:2017-10-21 17:46:15

标签: uwp uwp-xaml

我在XAML中有一些控件要转换为SoftwareBitmap。这可能吗?

1 个答案:

答案 0 :(得分:4)

当然,这段代码就是这样做的:

static async Task<SoftwareBitmap> CreateSoftwareBitmap(FrameworkElement uielement)
{
    var renderTargetBitmap = new RenderTargetBitmap();
    await renderTargetBitmap.RenderAsync(uielement);

    IBuffer pixels = await renderTargetBitmap.GetPixelsAsync();
    var bitmap = SoftwareBitmap.CreateCopyFromBuffer(pixels,
                                                     BitmapPixelFormat.Bgra8,
                                                     renderTargetBitmap.PixelWidth,
                                                     renderTargetBitmap.PixelHeight,
                                                     BitmapAlphaMode.Premultiplied);
    return bitmap;
}

如果您想在SoftwareBitmap控件上显示Image,请执行以下操作:

var softwareBitmap = await CreateSoftwareBitmap(MyXamlControl);
var source = new SoftwareBitmapSource();

await source.SetBitmapAsync(softwareBitmap);
MyImageControl.Source = source;