0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【UWP】UIElementの描画内容をDrawingSessionにDrawする方法

Last updated at Posted at 2024-12-31
using Microsoft.Graphics.Canvas;
using System;
using System.Threading.Tasks;
using Windows.Graphics.DirectX;
using Windows.Storage.Streams;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Media.Imaging;
#nullable enable
namespace SampleApp.Views;
public static class CanvasDrawingSessionXamlExtensions
{
    // DirectXPixelFormat https://learn.microsoft.com/en-us/uwp/api/windows.ui.xaml.media.imaging.rendertargetbitmap.getpixelsasync?view=winrt-26100
    public static async Task DrawXamlUIAsync(this CanvasDrawingSession ds, 
        UIElement source, 
        int scaledWidth, 
        int scaledHeight, 
        RenderTargetBitmap? recycleRtb = null)
    {
        RenderTargetBitmap renderTargetBitmap = recycleRtb ?? new ();
        await renderTargetBitmap.RenderAsync(source, scaledWidth, scaledHeight);
        IBuffer buffer = await renderTargetBitmap.GetPixelsAsync();
        using CanvasBitmap crt = CanvasBitmap.CreateFromBytes(
            ds.Device,
            buffer,
            renderTargetBitmap.PixelWidth,
            renderTargetBitmap.PixelHeight,
            DirectXPixelFormat.B8G8R8A8UIntNormalized);
        ds.DrawImage(crt);
    }
}

補足

  • Rtb.RenderAsync()は与えるUIElementの子孫の数にもよるが10ms単位で処理時間が増えるため概ね1フレーム以上掛かるような激重処理であることを理解して使う必要がある
    • また、おそらくRenderAsyncの内部でUIElementのVisualTreeを排他制御しているようで、表示にチラツキが生じるケースもあり特に低いクロック周波数のCPUではその影響が顕著にみられる
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?