我想在我的应用中分享图片。我只是在我的xaml中有一个图像,其源是在运行时通过将canvas作为位图来设置的。我想要共享其源在运行时设置的图像。
这是我的c#代码
private async void Button_Click(object sender, RoutedEventArgs e)
{
var renderTargetBitmap = new RenderTargetBitmap();
await renderTargetBitmap.RenderAsync(canvas);
myImg.Source = renderTargetBitmap;
}
This示例分享已安装位置的图片,如何修改该图片以分享我的图片?
答案 0 :(得分:2)
您需要将位图转换为RandomAccessStream,然后使用SetBitmap方法使用该流:
args.Request.Data.SetBitmap(RandomAccessStreamReference.CreateFromStream(stream));
完整代码:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
DataTransferManager.GetForCurrentView().DataRequested+= MainPage_DataRequested;
}
private async void MainPage_DataRequested(DataTransferManager sender, DataRequestedEventArgs args)
{
var deferral = args.Request.GetDeferral();
var bitmap = new RenderTargetBitmap();
await bitmap.RenderAsync(canvas);
// 1. Get the pixels
IBuffer pixelBuffer = await bitmap.GetPixelsAsync();
byte[] pixels = pixelBuffer.ToArray();
// 2. Write the pixels to a InMemoryRandomAccessStream
var stream = new InMemoryRandomAccessStream();
var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.BmpEncoderId, stream);
encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, (uint)bitmap.PixelWidth, (uint)bitmap.PixelHeight, 96, 96,
pixels);
await encoder.FlushAsync();
stream.Seek(0);
// 3. Share it
args.Request.Data.SetBitmap(RandomAccessStreamReference.CreateFromStream(stream));
args.Request.Data.Properties.Description = "description";
args.Request.Data.Properties.Title = "title";
deferral.Complete();
}