UWP Windows-10 加载图片的更好方式
UWP Windows-10 Better way to load images
我有一个面向 Windows UWP 桌面的 C# 应用程序。该应用程序显示图像列表。当用户单击列表视图中的任何图像时,应用程序将放大(详细视图)并显示图像(由于图像尺寸较大,因此会显示为全屏)。
每当我在列表视图中单击任何图像时,详细视图中的图像首先显示之前加载的图像,然后刷新并加载当前选择的图像
我想知道如何防止在获取新图像之前加载以前的图像?
目前,每当用户单击列表视图中的项目时,我都会先加载带有空白图像的详细视图图像源,然后获取所需图像并加载它。
我的代码在这里:
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;
});
});
}
我已经 运行 image_fetch 在后台线程中,但我仍然看到从用户单击列表视图项目到图像在详细视图中加载之间的小延迟。
我想减少延迟。除了加载空白图片之外,还有更好的方法吗?
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.
我认为问题在于您的 Mater/Detail 结构是如何实现的。从你的代码我可以看到你可能从文件中读取图像并将 BitmapImage
设置为 ListView
中 Image
的来源,这里我创建了一个示例,当 window宽度超过720,Detail会显示在Master的右边,如果宽度小于720,Detail会放大(全屏)。
我的主页:
<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>
隐藏代码:
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);
}
}
我的详情页:
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Image Source="{x:Bind image}" />
</Grid>
隐藏代码:
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();
}
我的 TestItem
class 在这里很简单:
public class TestItem
{
public BitmapImage ImageItem { get; set; }
}
也可以参考官方Master/detail sample。我的示例是按照这个官方示例写的,这里的重点是:
正在创建并排 master/detail 页面。
在主列表和详细视图之间导航。
调整应用大小时更改导航模型。
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.
每次点击ListViewItem时是否都获取图片源(例如从文件中获取),所以可以将图片源设置为详细信息框架吗?这里使用 DataBinding,当你想向 ListView
添加数据时,你可以只获取所有图像。
您可以使用 FFImageLoading 它使用各种方法来优化图像加载(包括 download/memory 缓存):
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">
我有一个面向 Windows UWP 桌面的 C# 应用程序。该应用程序显示图像列表。当用户单击列表视图中的任何图像时,应用程序将放大(详细视图)并显示图像(由于图像尺寸较大,因此会显示为全屏)。
每当我在列表视图中单击任何图像时,详细视图中的图像首先显示之前加载的图像,然后刷新并加载当前选择的图像
我想知道如何防止在获取新图像之前加载以前的图像?
目前,每当用户单击列表视图中的项目时,我都会先加载带有空白图像的详细视图图像源,然后获取所需图像并加载它。
我的代码在这里:
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;
});
});
}
我已经 运行 image_fetch 在后台线程中,但我仍然看到从用户单击列表视图项目到图像在详细视图中加载之间的小延迟。
我想减少延迟。除了加载空白图片之外,还有更好的方法吗?
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.
我认为问题在于您的 Mater/Detail 结构是如何实现的。从你的代码我可以看到你可能从文件中读取图像并将 BitmapImage
设置为 ListView
中 Image
的来源,这里我创建了一个示例,当 window宽度超过720,Detail会显示在Master的右边,如果宽度小于720,Detail会放大(全屏)。
我的主页:
<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>
隐藏代码:
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);
}
}
我的详情页:
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Image Source="{x:Bind image}" />
</Grid>
隐藏代码:
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();
}
我的 TestItem
class 在这里很简单:
public class TestItem
{
public BitmapImage ImageItem { get; set; }
}
也可以参考官方Master/detail sample。我的示例是按照这个官方示例写的,这里的重点是:
正在创建并排 master/detail 页面。
在主列表和详细视图之间导航。
调整应用大小时更改导航模型。
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.
每次点击ListViewItem时是否都获取图片源(例如从文件中获取),所以可以将图片源设置为详细信息框架吗?这里使用 DataBinding,当你想向 ListView
添加数据时,你可以只获取所有图像。
您可以使用 FFImageLoading 它使用各种方法来优化图像加载(包括 download/memory 缓存):
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">