UWP Windows-10 Better way to load images

Deadly 提交于 2021-01-28 03:48:08

问题


I have a C# app targeting Windows UWP Desktop. The app displays list of images. When user clicks on any of the image in the List View, app would enlarge(detailed view) it & show the image(kind of full screen as the image size is bigger).
Whenever I click any image in the list view, the image in the detailed view first shows the previously loaded image & then it refreshes & load's the image from the current selection
I want to know how to prevent loading the previous image until, new image is fetched?
Currently, whenever user clicks an item in list view, I load the detail view image source with a blank image first & then fetch the required image & load it.
My code is here:

 await CallOnUiThreadAsync(() =>
 {
    /*Load empty image first*/
    imgBitmap = new BitmapImage();
    var uri = new System.Uri("ms-appx:///Assets/emptyImage.png");
    imgBitmap.UriSource = uri;
    img.Source = imgBitmap;
  });

  if (("/Assets/emptyImage.png" != url) || (url != String.Empty))
  {
      await Task.Run(async () =>
      {
        /*image_fetch is our proprietary api. It returns a byte array*/
        byte[] imageBytes = image_fetch;
        MemoryStream stream = new MemoryStream(imageBytes, 0, imageBytes.Length, true);
        var randomAccessStream = new MemoryRandomAccessStream(stream);
        await CallOnUiThreadAsync(async () =>
        {
            imgBitmap = new BitmapImage();
            await imgBitmap.SetSourceAsync(randomAccessStream);
            img.Source = imgBitmap;
         });
       });
   }


I am already running image_fetch in a background thread, still I see a small lag from the time user clicks list view item until the image loads in detail view.
I would like to reduce the lag. Is there a better way of doing that other than loading blank image?


回答1:


Whenever I click any image in the list view, the image in the detailed view first shows the previously loaded image & then it refreshes & load's the image from the current selection.

I think the problem is how your Mater/Detail structure implemented is. From your code I can see that you probably read images from file and set BitmapImage to the source of Image in the ListView, here I created a sample, when the window's width is over 720, the Detail will be shown at the right of the Master, and if the width is less than 720, the Detail will be enlarged(full screen).

My MainPage:

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <VisualStateManager.VisualStateGroups>
        <VisualStateGroup x:Name="AdaptiveStates">
            <VisualState x:Name="DefaultState">
                <VisualState.StateTriggers>
                    <AdaptiveTrigger MinWindowWidth="720" />
                </VisualState.StateTriggers>
            </VisualState>

            <VisualState x:Name="NarrowState">
                <VisualState.StateTriggers>
                    <AdaptiveTrigger MinWindowWidth="0" />
                </VisualState.StateTriggers>

                <VisualState.Setters>
                    <Setter Target="MasterColumn.Width" Value="*" />
                    <Setter Target="DetailColumn.Width" Value="0" />
                    <Setter Target="MasterListView.SelectionMode" Value="None" />
                </VisualState.Setters>
            </VisualState>
        </VisualStateGroup>
    </VisualStateManager.VisualStateGroups>

    <Grid.ColumnDefinitions>
        <ColumnDefinition x:Name="MasterColumn" Width="320" />
        <ColumnDefinition x:Name="DetailColumn" Width="*" />
    </Grid.ColumnDefinitions>

    <ListView x:Name="MasterListView" Grid.Column="0" ItemContainerTransitions="{x:Null}"
        IsItemClickEnabled="True" ItemClick="MasterListView_ItemClick" ItemsSource="{x:Bind itemcollection}">
        <ListView.ItemContainerStyle>
            <Style TargetType="ListViewItem">
                <Setter Property="HorizontalContentAlignment" Value="Stretch" />
            </Style>
        </ListView.ItemContainerStyle>
        <ListView.ItemTemplate>
            <DataTemplate x:DataType="local:TestItem">
                <Image Source="{x:Bind ImageItem}" />
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>

    <ContentPresenter x:Name="DetailContentPresenter" Grid.Column="1" BorderThickness="1,0,0,0"
        Padding="24,0" BorderBrush="{ThemeResource SystemControlForegroundBaseLowBrush}"
        Content="{x:Bind MasterListView.SelectedItem, Mode=OneWay}">
        <ContentPresenter.ContentTemplate>
            <DataTemplate x:DataType="local:TestItem">
                <Image Source="{x:Bind ImageItem}" />
            </DataTemplate>
        </ContentPresenter.ContentTemplate>
    </ContentPresenter>
</Grid>

code behind:

private ObservableCollection<TestItem> itemcollection = new ObservableCollection<TestItem>();

public MainPage()
{
    this.InitializeComponent();
}

protected override async void OnNavigatedTo(NavigationEventArgs e)
{
    StorageFolder picLib = KnownFolders.PicturesLibrary;
    var picfiles = await picLib.GetFilesAsync();
    foreach (var pic in picfiles)
    {
        BitmapImage bmp = new BitmapImage();
        IRandomAccessStream stream = await pic.OpenReadAsync();
        bmp.SetSource(stream);
        itemcollection.Add(new TestItem { ImageItem = bmp });
    }
}

private void MasterListView_ItemClick(object sender, ItemClickEventArgs e)
{
    var clickedItem = (TestItem)e.ClickedItem;

    if (AdaptiveStates.CurrentState == NarrowState)
    {
        Frame.Navigate(typeof(DetailPage), clickedItem);
    }
}

My Detail Page:

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <Image Source="{x:Bind image}" />
</Grid>

code behind:

private BitmapImage image;

public DetailPage()
{
    this.InitializeComponent();
}

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    base.OnNavigatedTo(e);

    var testitem = e.Parameter as TestItem;
    image = testitem.ImageItem;

    var backStack = Frame.BackStack;
    var backStackCount = backStack.Count;

    if (backStackCount > 0)
    {
        var masterPageEntry = backStack[backStackCount - 1];
        backStack.RemoveAt(backStackCount - 1);

        // Doctor the navigation parameter for the master page so it
        // will show the correct item in the side-by-side view.
        var modifiedEntry = new PageStackEntry(
            masterPageEntry.SourcePageType,
            e.Parameter,
            masterPageEntry.NavigationTransitionInfo
            );
        backStack.Add(modifiedEntry);
    }

    // Register for hardware and software back request from the system
    SystemNavigationManager systemNavigationManager = SystemNavigationManager.GetForCurrentView();
    systemNavigationManager.BackRequested += DetailPage_BackRequested;
    systemNavigationManager.AppViewBackButtonVisibility = AppViewBackButtonVisibility.Visible;
}

protected override void OnNavigatedFrom(NavigationEventArgs e)
{
    base.OnNavigatedFrom(e);

    SystemNavigationManager systemNavigationManager = SystemNavigationManager.GetForCurrentView();
    systemNavigationManager.BackRequested -= DetailPage_BackRequested;
    systemNavigationManager.AppViewBackButtonVisibility = AppViewBackButtonVisibility.Collapsed;
}

private void OnBackRequested()
{
    Frame.GoBack();
}

private void DetailPage_BackRequested(object sender, BackRequestedEventArgs e)
{
    e.Handled = true;
    OnBackRequested();
}

And my TestItem class is quite simple here:

public class TestItem
{
    public BitmapImage ImageItem { get; set; }
}

You can also refer to the official Master/detail sample. I wrote my sample according to this official sample, the key-points here are:

  • Creating a side-by-side master/detail page.

  • Navigating between the master list and detail view.

  • Changing the navigation model when the app is resized.

I am already running image_fetch in a background thread, still I see a small lag from the time user clicks list view item until the image loads in detail view.

Did you fetch Image source(from file for example) each time you clicked the ListViewItem, so can you set the image source to the detail frame? Here using DataBinding, you can just fetch all the images when you want to add data to your ListView.




回答2:


You could use FFImageLoading it uses various methods for optimising image loading (including download/memory cache):

XML <ff:FFImage VerticalAlignment="Stretch" HorizontalAlignment="Stretch" TransformPlaceholders="False" LoadingPlaceholder="loading.png" ErrorPlaceholder="error.png" Height="500" Width="500" Source="http://loremflickr.com/600/600/nature?filename=simple.jpg">



来源:https://stackoverflow.com/questions/37475023/uwp-windows-10-better-way-to-load-images

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!