Reputation: 3718
I want to share an image in my app . I just have have an image in my xaml whose source is set at runtime by making canvas as bitmap.I want to share that image whose source is set at runtime.
Here is my c# code
private async void Button_Click(object sender, RoutedEventArgs e)
{
var renderTargetBitmap = new RenderTargetBitmap();
await renderTargetBitmap.RenderAsync(canvas);
myImg.Source = renderTargetBitmap;
}
This example share an image from installed location , How do I modify that to share my image?
Upvotes: 0
Views: 609
Reputation: 2433
you need to convert bitmap into RandomAccessStream then use that stream using SetBitmap Method:
args.Request.Data.SetBitmap(RandomAccessStreamReference.CreateFromStream(stream));
full code:
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();
}
Upvotes: 2