Skip to content

Blurry image with CanvasVirtualControl #1002

@AndrewKeepCoding

Description

@AndrewKeepCoding

Hi, and thanks in advance!
If there's a better place to ask Win2d-related questions, please let me know.

On the right side is the blurry image rendered using CanvasVirtualControl.
On the left side is the same BMP file opened on the Paint app.

Image size: 128 x 250
File type: BMP

How can I render the image with the same clarity as the Paint app?

Image

Here's the code for this demo app:

MainWindow.xaml

<Grid x:Name="RootGrid">
    <ScrollViewer x:Name="ScrollViewer" ZoomMode="Enabled">
        <win2d:CanvasVirtualControl
            x:Name="CanvasVirtualControl"
            HorizontalAlignment="Stretch"
            VerticalAlignment="Stretch"
            HorizontalContentAlignment="Stretch"
            VerticalContentAlignment="Stretch" />
    </ScrollViewer>
</Grid>

MainWindow.xaml.cs

public MainWindow()
{
    InitializeComponent();
    this.RootGrid.Loaded += RootGrid_Loaded;
    CanvasVirtualControl.RegionsInvalidated += CanvasVirtualControl_RegionsInvalidated;
}

private CanvasVirtualBitmap? CanvasVirtualBitmap { get; set; }

private async void RootGrid_Loaded(object sender, RoutedEventArgs e)
{
    await LoadImage();
}

private async Task LoadImage()
{
    string fileName = "128x250.bmp";
    //string fileName = "2048x4000.bmp";
    string filePath = Path.Combine(AppContext.BaseDirectory, "Assets", fileName);

    if ((await StorageFile.GetFileFromPathAsync(filePath)) is not { IsAvailable: true } storageFile)
        return;

    using var fileStream = await storageFile.OpenAsync(FileAccessMode.Read);
    IRandomAccessStream streamForCanvas = fileStream.CloneStream();
    BitmapDecoder bitmapDecoder = await BitmapDecoder.CreateAsync(streamForCanvas);
    PixelDataProvider pixelDataProvider = await bitmapDecoder.GetPixelDataAsync();
    var pixelBuffer = pixelDataProvider.DetachPixelData();
    CanvasVirtualBitmap = await CanvasVirtualBitmap.LoadAsync(CanvasVirtualControl.Device, streamForCanvas);
    CanvasVirtualControl.Width = CanvasVirtualBitmap.SizeInPixels.Width;
    CanvasVirtualControl.Height = CanvasVirtualBitmap.SizeInPixels.Height;

}

private void CanvasVirtualControl_RegionsInvalidated(CanvasVirtualControl sender, CanvasRegionsInvalidatedEventArgs args)
{
    if (CanvasVirtualBitmap is null)
        return;

    foreach (Rect region in args.InvalidatedRegions)
    {
        using var session = sender.CreateDrawingSession(region);
        session.DrawImage(
            image: CanvasVirtualBitmap,
            destinationRectangle: region,
            sourceRectangle: region);
    }
}

Demo app repo:
AndrewKeepCoding/Win2dDemoApp

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions