设置图像源

时间:2013-08-24 11:06:41

标签: c# wpf image windows-store-apps imagesource

我正在尝试将图像源设置为来自计算机的内容(不在资产中) 这就是我试图这样做的方式:

Uri uri = new Uri(@"D:\Riot Games\about.png", UriKind.Absolute);
ImageSource imgSource = new BitmapImage(uri);

this.image1.Source = imgSource;

我尝试了几乎所有我能在互联网上找到的东西,但似乎没什么用。

知道为什么吗?

XAML:

<UserControl
    x:Class="App11.VideoPreview"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:App11"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="250"
    d:DesignWidth="250">

    <Grid>
        <Button Height="250" Width="250" Padding="0" BorderThickness="0">
            <StackPanel>
                <Image Name="image1" Height="250" Width="250"/>
                <Grid Margin="0,-74,0,0">
                    <Grid.Background>
                        <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0" Opacity="0.75">
                            <GradientStop Color="Black"/>
                            <GradientStop Color="#FF5B5B5B" Offset="1"/>
                        </LinearGradientBrush>
                    </Grid.Background>
                    <TextBlock x:Name="textBox1" TextWrapping="Wrap" Text="test" FlowDirection="RightToLeft" Foreground="White" Padding="5"/>
                </Grid>
            </StackPanel>
        </Button>
    </Grid>
</UserControl>

1 个答案:

答案 0 :(得分:7)

您无法直接从Windows metro应用访问磁盘驱动器。摘自File access permissions in windows store apps

  

您可以访问某些文件系统位置,例如应用安装   Windows的目录,应用程序数据位置和下载文件夹   默认情况下存储应用。应用还可以访问其他位置   通过文件选择器,或通过声明功能。

但是,通过启用包清单文件中的功能,您可以访问一些特殊文件夹,如Pictures library,文档库等。因此,从清单文件启用图片库后可以使用此代码(复制图片库文件夹中的about.png文件)

    private async void SetImageSource()
    {
        var file = await 
          Windows.Storage.KnownFolders.PicturesLibrary.GetFileAsync("about.png");
        var stream = await file.OpenReadAsync();
        var bitmapImage = new BitmapImage();
        bitmapImage.SetSource(stream);

        image1.Source = bitmapImage;
    }

但理想的解决方案是将您的文件包含在您的应用程序中,并将其构建操作设置为Content,以便可以将其与其他内容文件一起复制到 Appx 文件夹中。然后你可以像这样设置图像源 -

    public MainPage()
    {
        this.InitializeComponent();
        Uri uri = new Uri(BaseUri, "about.png");
        BitmapImage imgSource = new BitmapImage(uri);
        this.image1.Source = imgSource;
    }

或者您只能在XAML中执行此操作:

<Image x:Name="image1" Source="ms-appx:/about.png"/>

以下是您可以从应用程序访问的特殊文件夹列表 -

  1. 本地应用数据
  2. 漫游应用数据
  3. 临时应用数据
  4. 应用安装位置
  5. 下载文件夹
  6. 文档库
  7. 音乐库
  8. 图片库
  9. 视频库
  10. 可移动设备
  11. 家庭小组
  12. 媒体服务器设备
  13. 要从清单文件启用功能,请双击解决方案中的Package.appxmanifest文件,然后选中功能选项卡下的Pictures Library复选框,以便为您的应用启用它。同样,您可以为要访问的其他文件夹执行此操作。

    enter image description here

相关问题