RenderTargetBitmapPage.cs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. using System.Diagnostics;
  2. using Avalonia;
  3. using Avalonia.Controls;
  4. using Avalonia.LogicalTree;
  5. using Avalonia.Media;
  6. using Avalonia.Media.Imaging;
  7. using Avalonia.Threading;
  8. namespace RenderDemo.Pages
  9. {
  10. public class RenderTargetBitmapPage : Control
  11. {
  12. private RenderTargetBitmap _bitmap;
  13. protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e)
  14. {
  15. _bitmap = new RenderTargetBitmap(new PixelSize(200, 200), new Vector(96, 96));
  16. base.OnAttachedToLogicalTree(e);
  17. }
  18. protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e)
  19. {
  20. _bitmap.Dispose();
  21. _bitmap = null;
  22. base.OnDetachedFromLogicalTree(e);
  23. }
  24. readonly Stopwatch _st = Stopwatch.StartNew();
  25. public override void Render(DrawingContext context)
  26. {
  27. using (var ctxi = _bitmap.CreateDrawingContext(null))
  28. using(var ctx = new DrawingContext(ctxi, false))
  29. using (ctx.PushPostTransform(Matrix.CreateTranslation(-100, -100)
  30. * Matrix.CreateRotation(_st.Elapsed.TotalSeconds)
  31. * Matrix.CreateTranslation(100, 100)))
  32. {
  33. ctxi.Clear(default);
  34. ctx.FillRectangle(Brushes.Fuchsia, new Rect(50, 50, 100, 100));
  35. }
  36. context.DrawImage(_bitmap,
  37. new Rect(0, 0, 200, 200),
  38. new Rect(0, 0, 200, 200));
  39. Dispatcher.UIThread.Post(InvalidateVisual, DispatcherPriority.Background);
  40. base.Render(context);
  41. }
  42. }
  43. }