DrawingPresenter.cs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. using Avalonia.Controls.Shapes;
  2. using Avalonia.Media;
  3. using Avalonia.Metadata;
  4. namespace Avalonia.Controls
  5. {
  6. public class DrawingPresenter : Control
  7. {
  8. public static readonly StyledProperty<Drawing> DrawingProperty =
  9. AvaloniaProperty.Register<DrawingPresenter, Drawing>(nameof(Drawing));
  10. [Content]
  11. public Drawing Drawing
  12. {
  13. get => GetValue(DrawingProperty);
  14. set => SetValue(DrawingProperty, value);
  15. }
  16. public static readonly StyledProperty<Stretch> StretchProperty =
  17. AvaloniaProperty.Register<DrawingPresenter, Stretch>(nameof(Stretch), Stretch.Uniform);
  18. public Stretch Stretch
  19. {
  20. get => GetValue(StretchProperty);
  21. set => SetValue(StretchProperty, value);
  22. }
  23. static DrawingPresenter()
  24. {
  25. AffectsMeasure(DrawingProperty);
  26. AffectsRender(DrawingProperty);
  27. }
  28. private Matrix _transform = Matrix.Identity;
  29. protected override Size MeasureOverride(Size availableSize)
  30. {
  31. if (Drawing == null) return new Size();
  32. var (size, transform) = Shape.CalculateSizeAndTransform(availableSize, Drawing.GetBounds(), Stretch);
  33. _transform = transform;
  34. return size;
  35. }
  36. public override void Render(DrawingContext context)
  37. {
  38. if (Drawing != null)
  39. {
  40. using (context.PushPreTransform(_transform))
  41. {
  42. Drawing.Draw(context);
  43. }
  44. }
  45. }
  46. }
  47. }