使用Sharpdx库(WinRT)从xaml控件创建位图图像或内存流

时间:2012-07-24 09:51:38

标签: windows-8 windows-runtime sharpdx

是否可以从Sharpdx创建xaml控件的位图图像或内存流说(gird,canvas)。我需要从我的一个窗口创建一个图像,以实现辅助磁贴引脚启动功能。

1 个答案:

答案 0 :(得分:-3)

我一直在使用Windows.Storage.Streams中的RandomAccessStreamReference类来创建位图。一个例子(这实际上是共享代码):

        var reference = RandomAccessStreamReference.CreateFromUri(new Uri(item.ImagePath.AbsoluteUri));
        request.Data.SetBitmap(reference);

另请注意,对于固定辅助磁贴,您可以在磁贴上传递徽标的URI,而无需创建实际的位图,只要徽标是应用包的一部分,如下所示:

    var uri = new Uri(item.TileImagePath.AbsoluteUri);

    var tile = new SecondaryTile(
            item.UniqueId,              // Tile ID
            item.ShortTitle,            // Tile short name
            item.Title,                 // Tile display name
            item.UniqueId,              // Activation argument
            TileOptions.ShowNameOnLogo, // Tile options
            uri                         // Tile logo URI
        );

    await tile.RequestCreateAsync();

最后,如果您要在辅助磁贴上使用的图像是在线而不是应用包的一部分,则必须先将其复制到本地,然后才能使用它。以下是一些代码:

    // This is the URI that you will then pass as the last parameter into 
    // the Secondary Tile constructor, like the code above:
    var logoUri = await GetLocalImageAsync(restaurant.ImagePath, restaurant.Key);

    // and here's the method that does the meat of the work:

/// <summary>
/// Copies an image from the internet (http protocol) locally to the AppData LocalFolder.
/// This is used by some methods (like the SecondaryTile constructor) that do not support 
/// referencing images over http but can reference them using the ms-appdata protocol.  
/// </summary>
/// <param name="internetUri">The path (URI) to the image on the internet</param>
/// <param name="uniqueName">A unique name for the local file</param>
/// <returns>Path to the image that has been copied locally</returns>
private async Task<Uri> GetLocalImageAsync(string internetUri, string uniqueName)
{
    if (string.IsNullOrEmpty(internetUri))
    {
        return null;
    }

    using (var response = await HttpWebRequest.CreateHttp(internetUri).GetResponseAsync())
    {
        using (var stream = response.GetResponseStream())
        {
            var desiredName = string.Format("{0}.jpg", uniqueName);
            var file = await ApplicationData.Current.LocalFolder.CreateFileAsync(desiredName, CreationCollisionOption.ReplaceExisting);

            using (var filestream = await file.OpenStreamForWriteAsync())
            {
                await stream.CopyToAsync(filestream);
                return new Uri(string.Format("ms-appdata:///local/{0}.jpg", uniqueName), UriKind.Absolute);
            }
        }
    }
}