Universal Windows InkCanvas strokes disappear on RenderTargetBitmap.RenderAsync - xaml

I try to render the strokes of a InkCanvas to a RenderTargetBitmap in a windows 10 universal App. Here is my xaml code:
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="10" />
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid x:Name="container">
<Rectangle Fill="LightBlue" />
<InkCanvas x:Name="InkCanvas" />
</Grid>
<Image Grid.Row="2" x:Name="TheImage" />
<Button Grid.Row="3" Content="CopyToRendertargt" Click="Button_Click" />
</Grid>
And here is my code to set the Image.Source property:
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
InkCanvas.InkPresenter.InputDeviceTypes = Windows.UI.Core.CoreInputDeviceTypes.Mouse;
}
private async void Button_Click(object sender, RoutedEventArgs e)
{
RenderTargetBitmap renderTarget = new RenderTargetBitmap();
await renderTarget.RenderAsync(this.container);
this.TheImage.Source = renderTarget;
}
}
When i click to button the strokes i made on the InkCanvas disappear and the InkCanvas is forzen until i resize the app window. The strokes are not getting rendered to the RenderTargetBitmap. The Image shows just the LightBlue Rectangle.
Does sombody have a solution for this?
** UPDATE **
For those who are searching for the right way to save strokes to a bitmap on uwp. I found the UWP-way of saving InkCanvas Strokes to a Bitmap: The InkStrokeContainer Object has a method called SaveAsync(...) which saves the strokes to a stream. If you use this stream as source for a Bitmap you get the strokes as Bitmap.
InkStrokeContainer container = TheInkCanvas.InkPresenter.StrokeContainer;
WriteableBitmap bmp;
using (InMemoryRandomAccessStream ims =
new InMemoryRandomAccessStream())
{
await container.SaveAsync(ims);
bmp = await new WriteableBitmap(1, 1)
.FromStream(ims, BitmapPixelFormat.Bgra8);
}
*Note: WriteableBitmapEx is used in this sample code (https://www.nuget.org/packages/WriteableBitmapEx/)

You can use Win2D to render the Ink Strokes.
Add Win2D.uwp to the project from NuGet
Add this InkCanvasExtensions.cs file to your project
Change the namespace or add using Zoetrope; to your source
Create an image file or stream and pass it to the InkCanvas.RenderAsync()
InkCanvasExtensions.cs
namespace Zoetrope
{
using System;
using System.Threading.Tasks;
using Microsoft.Graphics.Canvas;
using Windows.Graphics.Display;
using Windows.Storage.Streams;
using Windows.UI;
using Windows.UI.Xaml.Controls;
/// <summary>
/// InkCanvas Extensions
/// </summary>
public static class InkCanvasExtensions
{
/// <summary>
/// Render an InkCanvas to a stream
/// </summary>
/// <param name="inkCanvas">the ink canvas</param>
/// <param name="fileStream">the file stream</param>
/// <param name="backgroundColor">the background color</param>
/// <param name="fileFormat">the file format</param>
/// <returns>an async task</returns>
public static async Task RenderAsync(
this InkCanvas inkCanvas,
IRandomAccessStream fileStream,
Color backgroundColor,
CanvasBitmapFileFormat fileFormat)
{
// do not put in using{} structure - it will close the shared device.
var device = CanvasDevice.GetSharedDevice();
var width = (float) inkCanvas.ActualWidth;
var height = (float) inkCanvas.ActualHeight;
var currentDpi = DisplayInformation.GetForCurrentView().LogicalDpi;
using (var offscreen = new CanvasRenderTarget(device, width, height, currentDpi))
{
using (var session = offscreen.CreateDrawingSession())
{
session.Clear(backgroundColor);
session.DrawInk(inkCanvas.InkPresenter.StrokeContainer.GetStrokes());
}
await offscreen.SaveAsync(fileStream, fileFormat);
}
}
}
}

In the XAML visuals and RenderTargetBitmap section in the RenderTargetBitmap documentation, it describes: Content that can't be captured will appear as blank in the captured image, but other content in the same visual tree can still be captured and will render (the presence of content that can't be captured won't invalidate the entire capture of that XAML composition).So it could be that the content of InkCanvas is not captureable.
An alternative is to use Win2D (Direct2D .NET wrapper from Microsoft). Win2D can be used in an UWP app via a nuget package. You will be able to manage the ink strokes and save them to image (jpeg, png, and other formats).

Related

How to make sure a Popup control match its parent Page when the parent is resized? UWP

I have a Popup which will fill the whole page when opened.
<Grid x:Name="gridRoot" Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Button Content="Open" HorizontalAlignment="Center" Click="{x:Bind viewModel.OpenPopup}" />
<Popup x:Name="popupCorrect" VerticalAlignment="Top" IsOpen="{Binding IsOpen}" IsLightDismissEnabled="False">
<Popup.ChildTransitions>
<TransitionCollection>
<PaneThemeTransition Edge="Left" />
</TransitionCollection>
</Popup.ChildTransitions>
<uc:MyPopup Width="{Binding ElementName=gridRoot, Path=ActualWidth}" Height="{Binding ElementName=gridRoot, Path=ActualHeight}"/>
</Popup>
</Grid>
The Popup is a UserControl
<Grid Background="Red">
<Button Content="Close" HorizontalAlignment="Center" Click="{x:Bind viewModel.ClosePopup}" />
</Grid>
The page
When popup is shown
Close the popup, resize the page, then reopen the popup. Notice that it does not match the new size of container page even though its Width and Height is bound to gridRoot . Do I have to manually set a new Width and Height for the popup? Why can't I achieve this with binding? This issue also appears on mobile during 'OrientationChanged'
Based on Decade Moon comment, this is how to resize the popup to match the parent container as its size changed.
Create a dependency property in the code behind
public double PageWidth
{
get { return (double)GetValue(PageWidthProperty); }
set { SetValue(PageWidthProperty, value); }
}
public static readonly DependencyProperty PageWidthProperty =
DependencyProperty.Register("PageWidth", typeof(double), typeof(GamePage), new PropertyMetadata(0d));
public double PageHeight
{
get { return (double)GetValue(PageHeightProperty); }
set { SetValue(PageHeightProperty, value); }
}
public static readonly DependencyProperty PageHeightProperty =
DependencyProperty.Register("PageHeight", typeof(double), typeof(GamePage), new PropertyMetadata(0d));
Update the value on SizeChanged event
private void GamePage_SizeChanged(object sender, SizeChangedEventArgs e)
{
if (e.NewSize.Width > 0d && e.NewSize.Height > 0d)
{
PageWidth = e.NewSize.Width;
PageHeight = e.NewSize.Height;
}
}
Then in XAML, just use x:Bind to bind the popup width and height
<Popup x:Name="popupCorrect" VerticalAlignment="Top" IsOpen="{Binding IsPopupCorrectOpen, Mode=TwoWay}" IsLightDismissEnabled="False">
<Popup.ChildTransitions>
<TransitionCollection>
<PaneThemeTransition Edge="Left" />
</TransitionCollection>
</Popup.ChildTransitions>
<uc:PopupCorrect Width="{x:Bind PageWidth, Mode=TwoWay}" Height="{x:Bind PageHeight, Mode=TwoWay}"/>
</Popup>
Pretty straight forward. Just remember not to use the ActualWidth or ActualHeight properties for binding source as they do not raise the PropertyChanged event.
Although it has an ActualWidthProperty backing field, ActualWidth does not raise property change notifications and it should be thought of as a regular CLR property and not a dependency property.
For purposes of ElementName binding, ActualWidth does not post updates when it changes (due to its asynchronous and run-time calculated nature). Do not attempt to use ActualWidth as a binding source for an ElementName binding. If you have a scenario that requires updates based on ActualWidth, use a SizeChanged handler.
#PutraKg have a great way.
But I have two way to solve it.
The first is set the VerticalAlignment="Center" HorizontalAlignment="Center" that can make the popup in the center.
But I think youare not content to put it in the center.
The great way is use the screen position.
You can get the Grid's screen postion and make it to popup.
In open button
private void Button_OnClick(object sender, RoutedEventArgs e)
{
var grid = (UIElement)popupCorrect.Parent; //get grid
var p = grid.TransformToVisual (Window.Current.Content).TransformPoint(new Point(0, 0)); //get point
popupCorrect.HorizontalOffset = p.X;
popupCorrect.VerticalOffset = p.Y;
popupCorrect.IsOpen = !popupCorrect.IsOpen;
}

XAML Slider inside ScrollViewer

For Windows 10 UWP app I have such XAML structure:
<ScrollViewer>
<StackPanel>
<Slider />
<Slider />
...
</StackPanel>
</ScrollViewer>
I would like to create such user experience:
When the user begins horizontal swipe gesture, the slider under the touch should receive the input and start changing its value, while vertical scrolling is completely disabled (even when the user continue draw circle motions)
When the user begins vertical swipe gesture, the scrollviewer should receive the input and start scrolling vertically, while sliders under the touch should stay intact (even when the user continue draw circle motions).
Is it possible to implement this behavior in pure XAML? I think I have tried all possible combinations of properties related to scroll... No luck. Any idea anybody?
After testing on mobile emulator with OS version 10586, I found that when the ScrollViewer is vertically scrolled, it won't effect the Slider inside even if I draw circle, and when the Slider is swiped horizontally, only when its value reaches the max value, the vertical scrolling of the ScrollViewer will be effected if I draw circle.
Is it possible to implement this behavior in pure XAML?
Yes, it is possible.
When the user begins horizontal swipe gesture, the slider under the touch should receive the input and start changing its value, while vertical scrolling is completely disabled (even when the user continue draw circle motions)
You can install the Microsoft.Xaml.Behaviors.Uwp.Managed package in your project, then use its DataTriggerBehavior for example like this:
<ScrollViewer x:Name="scrollViewer" HorizontalScrollMode="Disabled" VerticalScrollMode="Auto">
<Interactivity:Interaction.Behaviors>
<Core:DataTriggerBehavior Binding="{Binding ElementName=slider1,Path=FocusState}" ComparisonCondition="NotEqual" Value="Unfocused">
<Core:ChangePropertyAction PropertyName="VerticalScrollMode" Value="Disabled" />
</Core:DataTriggerBehavior>
<Core:DataTriggerBehavior Binding="{Binding ElementName=slider1,Path=FocusState}" ComparisonCondition="Equal" Value="Unfocused">
<Core:ChangePropertyAction PropertyName="VerticalScrollMode" Value="Auto" />
</Core:DataTriggerBehavior>
<Core:DataTriggerBehavior Binding="{Binding ElementName=slider2,Path=FocusState}" ComparisonCondition="NotEqual" Value="Unfocused">
<Core:ChangePropertyAction PropertyName="VerticalScrollMode" Value="Disabled" />
</Core:DataTriggerBehavior>
<Core:DataTriggerBehavior Binding="{Binding ElementName=slider2,Path=FocusState}" ComparisonCondition="Equal" Value="Unfocused">
<Core:ChangePropertyAction PropertyName="VerticalScrollMode" Value="Auto" />
</Core:DataTriggerBehavior>
</Interactivity:Interaction.Behaviors>
<StackPanel Height="1300">
<Slider Margin="0,200" x:Name="slider1" />
<Slider x:Name="slider2" />
</StackPanel>
</ScrollViewer>
When using this package in xaml, you will need to declare it in the header for example like this:
xmlns:Interactivity="using:Microsoft.Xaml.Interactivity"
xmlns:Core="using:Microsoft.Xaml.Interactions.Core"
xmlns:Media="using:Microsoft.Xaml.Interactions.Media"
As you can see in my code, I compared FocusState property of the Slider, if its value is Unfocused, then the vertical scroll mode of the ScrollViewer is enabled. So when user interact with this layout, after swiping on the Slider, he will need to click on the blank part to make the Slider lost focus first, then the vertical scroll mode can be enabled.
When the user begins vertical swipe gesture, the scrollviewer should receive the input and start scrolling vertically, while sliders under the touch should stay intact (even when the user continue draw circle motions).
Base on my test, I think this gesture is ensured by default, so I didn't code for this. If it is not by your side, please leave a comment and provide your device type and OS version so can I have a test.
I have a very similar issue and was able to resolve it with the following custom control. This is a CommandSlider that also allows you to send commands like a button after the sliding is complete (not what you need) but the ScrollViewer manipulation code is in there also. See if this helps your situation. It allows you to do all the work in complete XAML like you've requested.
NOTE: The slider must have ManipulationMode="TranslateX" or "TranslateY"depending on the orientation for this to work also.
public sealed class CommandSlider : Slider
{
public CommandSlider()
{
IsThumbToolTipEnabled = false;
PointerCaptureLost += (s, e) => (Command?.CanExecute(CommandParameter)).GetValueOrDefault().Switch(() => Command?.Execute(CommandParameter));
Loaded += (s, e) => ParentScrollViewer = this.GetParent<ScrollViewer>();
}
private ScrollViewer ParentScrollViewer { get; set; }
protected override void OnManipulationDelta(ManipulationDeltaRoutedEventArgs e)
{
base.OnManipulationDelta(e);
if (ParentScrollViewer != null)
{
var scrollX = Orientation == Orientation.Vertical
? e.Position.X * -1 + ParentScrollViewer.HorizontalOffset
: ParentScrollViewer.HorizontalOffset;
var scrollY = Orientation == Orientation.Horizontal
? e.Position.Y * -1 + ParentScrollViewer.VerticalOffset
: ParentScrollViewer.VerticalOffset;
var zoom = ParentScrollViewer.ZoomFactor;
ParentScrollViewer.ChangeView(scrollX, scrollY, zoom);
}
}
public object CommandParameter
{
get => GetValue(CommandParameterProperty);
set => SetValue(CommandParameterProperty, value);
}
public static readonly DependencyProperty CommandParameterProperty =
DependencyProperty.Register(nameof(CommandParameter), typeof(object), typeof(CommandSlider), new PropertyMetadata(null));
public ICommand Command
{
get => (ICommand)GetValue(CommandProperty);
set => SetValue(CommandProperty, value);
}
public static readonly DependencyProperty CommandProperty =
DependencyProperty.Register(nameof(Command), typeof(ICommand), typeof(CommandSlider), new PropertyMetadata(null));
public double SourceValue
{
get => (double)GetValue(SourceValueProperty);
set => SetValue(SourceValueProperty, value);
}
public static readonly DependencyProperty SourceValueProperty =
DependencyProperty.Register(nameof(SourceValue), typeof(double), typeof(CommandSlider), new PropertyMetadata(0d,
(s, e) => (s as CommandSlider).Value = (double)e.NewValue));
}
Custom Extension Method
public static class XAMLExtensions
{
public static T GetParent<T>(this DependencyObject dependencyObject) where T : DependencyObject
{
var parentDependencyObject = VisualTreeHelper.GetParent(dependencyObject);
switch (parentDependencyObject)
{
case null:
return null;
case T parent:
return parent;
default:
return GetParent<T>(parentDependencyObject);
}
}
}

RenderTargetBitmap messes up the WebView scaling

I have a very simple repro case of RenderTargetBitmap.RenderAsync overload messing up the WebView scaling. All I have on the MainPage is a WebView and a button:
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<WebView Source="http://bing.com"></WebView>
<Button Content="Render me"
HorizontalAlignment="Right"
VerticalAlignment="Bottom"
Click="ButtonBase_OnClick" />
</Grid>
In code behind there's only a simple event handler
private async void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
RenderTargetBitmap rtb = new RenderTargetBitmap();
await rtb.RenderAsync(this, 1280, 720);
}
This is what the page looks like before RenderAsync call:
and this is what happens after the call:
Any idea why and how to prevent this? Note that it only happens if I call
await rtb.RenderAsync(this, 1280, 720);
but NOT if I call the overload without the scaling
await rtb.RenderAsync(this);
EDIT: Due to the first answer I received, I wanted to clarify why the aspect ratio is not the problem here, but only serves the purpose of proving that there actually is a problem. Think of the following scenario - very high DPI screen where only a lower resolution screenshot is needed - even if you scale it down with the RIGHT ratio, it still messes up the WebView. Also, for my scenario, resizing the screenshot manually afterwards is not an option - the RenderAsync overload with scaled dimensions is much much faster and I would really prefer to use that method.
Very strange behavior...
I found one very dirty (!) fix to this. I basically hide and show the webview (wv) again.
private async void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
RenderTargetBitmap rtb = new RenderTargetBitmap();
await rtb.RenderAsync(wv, 1280, 720);
wv.Visibility = Visibility.Collapsed;
await Task.Delay(100);
wv.Visibility = Visibility.Visible;
}
I'm not proud of this solution and the webview flashes, but at least it's not 'blown up' any more...
This is a bit of a hack too, but I found that if you set the contents of another control through a WebViewBrush and then render that control, then the source WebView doesn't get any scaling. I have modified the XAML you provided so it looks like this:
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Border x:Name="Target" Width="1280" Height="720" />
<WebView x:Name="webView" Source="http://bing.com" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"></WebView>
<Button Content="Render me" Grid.Row="1"
HorizontalAlignment="Right"
VerticalAlignment="Bottom"
Click="ButtonBase_OnClick" />
</Grid>
In your case, you should opt to set the Border control behind your WebView (however, don't change its Visibility or put it outside of the window bounds, as RenderAsync will fail). Then, on the code behind, set the Background of the target control to an instance of a WebViewBrush that feeds on the WebView:
private async void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
WebViewBrush brush = new WebViewBrush();
brush.SetSource(webView);
Target.Background = brush;
Target.InvalidateMeasure();
Target.InvalidateArrange();
RenderTargetBitmap rtb = new RenderTargetBitmap();
await rtb.RenderAsync(Target, 1280, 720);
var pixels = await rtb.GetPixelsAsync();
}
You will get your final image without any issues caused to the source WebView (however, note that the final image will look distorted since the aspect ratios don't match). However this comes with a few caveats, the most important one being that the WebView size must match the one of the RenderTargetBitmap or you will get empty areas.
Instead of using fixed values, use VisibleBounds to get the current window size.
Here's the code:
private async void pressMe_Click(object sender, RoutedEventArgs e)
{
var windowBounds = ApplicationView.GetForCurrentView().VisibleBounds;
RenderTargetBitmap rtb = new RenderTargetBitmap();
await rtb.RenderAsync(this, (int)windowBounds.Width, (int)windowBounds.Height);
}

Change button background image when click in Windows Phone using XAML only?

So basically I want to have a button with a certain background image.
For example, when the app is loaded you would see a button with it's background image as image1.png and then when it is clicked you see image2.png as the background image. Then when you click again, the background image is switched back to image1.png.
Even though I have done this in C#, I want to do it in XAML because every time you click a button it automatically lights up according to the theme color, and the only way to get rid of that is via XAML.
Here is my code so fa:
<Button x:Name="Buttons" Content="" HorizontalAlignment="Left" Margin="155,0,0,69" BorderBrush="Transparent" Width="140" Click="Button_Click" Height="141" VerticalAlignment="Bottom">
<Button.Background>
<ImageBrush Stretch="Fill" ImageSource="/Assets/image1.png"/>
</Button.Background>
</Button>
Thanks in advance!
Try this,
http://visualstudiomagazine.com/articles/2013/02/15/customize-windows-phone-togglebutton.aspx
Here, the ToggleButton that ships with the SDK has been templated to add a clicked and unclicked image.
Alternate Solution with a checkbox:
Creating own toggle button in WP8?
VisualStudio 2017 "Blank App"
XAML
<Button x:Name="button" Content="Button1" HorizontalAlignment="Left" Margin="400,20,0,0" VerticalAlignment="Top" RenderTransformOrigin="-1.258,-5" Click="Button_Click" Height="80" Width="80"/>
C# (Set the original image in the properties of the button: right-click -> Brush -> image)
private void Button1_Click(object sender, RoutedEventArgs e)
{
button1.Background = new ImageBrush { ImageSource = new BitmapImage(new Uri("ms-appx:/Images/timerg.png", UriKind.RelativeOrAbsolute)) };
}
or C#
private void Button1_Click(object sender, RoutedEventArgs e)
{
BitmapImage bmp = new BitmapImage();
Uri u = new Uri("ms-appx:/Images/timer.png", UriKind.RelativeOrAbsolute);
bmp.UriSource = u;
// NOTE: change starts here
Image i = new Image();
i.Source = bmp;
button1.Content = i;
}

Image rotation as animation

I am making a Windows 8 application in visual studio 2012 c#.
I am having an image '1.png' and I want to rotate it at any angle as an animation along its center point.
But i want to do it with the help of c# code rather than XAML code.
Thank You in Advance.
In your XAML, have the following image:
<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
<Image Source="/Assets/Logo.png" Width="300" RenderTransformOrigin="0.5, 0.5">
<Image.RenderTransform>
<RotateTransform x:Name="rotateTransform"/>
</Image.RenderTransform>
</Image>
</Grid>
Then, in code, write the following when you want to animate (you create the Storyboard programmatically, then add to it a relevant Timeline. Note that you can also create the RotateTransform in code if you want.
async void MainPage_Loaded(object sender, RoutedEventArgs e)
{
await Task.Delay(500);
Storyboard board = new Storyboard();
var timeline = new DoubleAnimationUsingKeyFrames();
Storyboard.SetTarget(timeline, rotateTransform);
Storyboard.SetTargetProperty(timeline, "Angle");
var frame = new EasingDoubleKeyFrame() { KeyTime = TimeSpan.FromSeconds(1), Value = 360, EasingFunction = new QuadraticEase() { EasingMode = EasingMode.EaseOut } };
timeline.KeyFrames.Add(frame);
board.Children.Add(timeline);
board.Begin();
}
This will rotate the object 360 degrees.
BTW: I am writing a set of posts that show an even better way of animating. It's not done yet, but it will give you a general idea on how to get a framework for certain types of animations..
First part of the series
Thanks Shahar! I took your example and made a custom control. It's actually an infinite spinning of one ring image.
Spinner.xaml:
<UserControl x:Class="MyControls.Spinner"
...
<Grid >
<Image Source="/Assets/Images/spinner.png" Width="194" RenderTransformOrigin="0.5, 0.5">
<Image.RenderTransform>
<RotateTransform x:Name="rotateTransform"/>
</Image.RenderTransform>
</Image>
</Grid>
</UserControl>
Spinner.cs:
namespace MyControls
{
public partial class Spinner: UserControl
{
public Spinner()
{
InitializeComponent();
this.Loaded += Spinner_Loaded;
}
private void PlayRotation()
{
Storyboard board = new Storyboard();
var timeline = new DoubleAnimationUsingKeyFrames();
Storyboard.SetTarget(timeline, rotateTransform);
Storyboard.SetTargetProperty(timeline, new PropertyPath("(Angle)"));
var frame = new EasingDoubleKeyFrame() { KeyTime = TimeSpan.FromSeconds(5), Value = 360, EasingFunction = new QuadraticEase() { EasingMode = EasingMode.EaseOut } };
timeline.KeyFrames.Add(frame);
board.Children.Add(timeline);
board.RepeatBehavior = RepeatBehavior.Forever;
board.Begin();
}
private async void Spinner_Loaded(object sender, RoutedEventArgs e)
{
PlayRotation();
}
}
}
Then when you want to use Spinner in another xaml, it's very simple:
Just add a line for it inside any Grid etc:
<include:Spinner/>
(of course you need to define include as something like:
xmlns:include="MyControls"
on top of your xaml)