59 lines
1.7 KiB
C#
59 lines
1.7 KiB
C#
using System;
|
|
using System.IO;
|
|
using System.Threading.Tasks;
|
|
using Avalonia;
|
|
using Avalonia.Controls;
|
|
using Avalonia.Input;
|
|
using Avalonia.Interactivity;
|
|
using Avalonia.Media.Imaging;
|
|
using Avalonia.Platform.Storage;
|
|
using SimpleDraw.ViewModels;
|
|
|
|
namespace SimpleDraw.Views;
|
|
|
|
public partial class MainWindow : Window
|
|
{
|
|
public MainWindow()
|
|
{
|
|
InitializeComponent();
|
|
DataContext = new MainWindowViewModel();
|
|
Topmost = true;
|
|
Topmost = false;
|
|
}
|
|
|
|
// MVVM like implementations burst the bounds -> implemented the old school way
|
|
private async void SaveFileButton_Clicked(object sender, RoutedEventArgs args)
|
|
{
|
|
TopLevel? topLevel = TopLevel.GetTopLevel(this);
|
|
if(topLevel == null) return;
|
|
|
|
var file = await topLevel.StorageProvider.SaveFilePickerAsync(new FilePickerSaveOptions
|
|
{
|
|
Title = "Save Drawing",
|
|
DefaultExtension = ".png",
|
|
SuggestedFileName = "unnamed",
|
|
SuggestedStartLocation = await topLevel.StorageProvider.TryGetFolderFromPathAsync(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures)),
|
|
});
|
|
|
|
if (file is not null)
|
|
{
|
|
SaveCanvasAsPngAsync(Canvas, file.Path.AbsolutePath);
|
|
}
|
|
}
|
|
|
|
public async Task SaveCanvasAsPngAsync(Canvas canvas, string filePath)
|
|
{
|
|
Rect bounds = canvas.Bounds;
|
|
PixelSize pixelSize = new PixelSize((int)bounds.Width, (int)bounds.Height);
|
|
Vector dpi = new Vector(96, 96);
|
|
|
|
RenderTargetBitmap renderBitmap = new RenderTargetBitmap(pixelSize, dpi);
|
|
|
|
renderBitmap.Render(canvas);
|
|
|
|
await using (FileStream stream = File.OpenWrite(filePath))
|
|
{
|
|
renderBitmap.Save(stream);
|
|
}
|
|
}
|
|
} |