RenderTargetBitmap and Viewport3D - Quality Issues - c#

I'm wanting to export a 3D scene from a Viewport3D to a bitmap.
The obvious way to do this would be to use RenderTargetBitmap -- however when I this the quality of the exported bitmap is significantly lower than the on-screen image. Looking around on the internet, it seems that RenderTargetBitmap doesn't take advantage of hardware rendering. Which means that the rendering is done at Tier 0. Which means no mip-mapping etc, hence the reduced quality of the exported image.
Does anyone know how to export a bitmap of a Viewport3D at on-screen quality?
Clarification
Though the example given below doesn't show this, I need to eventually export the bitmap of the Viewport3D to a file. As I understand the only way to do this is to get the image into something that derives from BitmapSource. Cplotts below shows that increasing the quality of the export using RenderTargetBitmap improves the image, but as the rendering is still done in software, it is prohibitively slow.
Is there a way to export a rendered 3D scene to a file, using hardware rendering? Surely that should be possible?
You can see the problem with this xaml:
<Window x:Class="RenderTargetBitmapProblem.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Height="400" Width="500">
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Viewport3D Name="viewport3D">
<Viewport3D.Camera>
<PerspectiveCamera Position="0,0,3"/>
</Viewport3D.Camera>
<ModelVisual3D>
<ModelVisual3D.Content>
<AmbientLight Color="White"/>
</ModelVisual3D.Content>
</ModelVisual3D>
<ModelVisual3D>
<ModelVisual3D.Content>
<GeometryModel3D>
<GeometryModel3D.Geometry>
<MeshGeometry3D Positions="-1,-10,0 1,-10,0 -1,20,0 1,20,0"
TextureCoordinates="0,1 0,0 1,1 1,0"
TriangleIndices="0,1,2 1,3,2"/>
</GeometryModel3D.Geometry>
<GeometryModel3D.Material>
<DiffuseMaterial>
<DiffuseMaterial.Brush>
<ImageBrush ImageSource="http://www.wyrmcorp.com/galleries/illusions/Hermann%20Grid.png"
TileMode="Tile" Viewport="0,0,0.25,0.25"/>
</DiffuseMaterial.Brush>
</DiffuseMaterial>
</GeometryModel3D.Material>
</GeometryModel3D>
</ModelVisual3D.Content>
<ModelVisual3D.Transform>
<RotateTransform3D>
<RotateTransform3D.Rotation>
<AxisAngleRotation3D Axis="1,0,0" Angle="-82"/>
</RotateTransform3D.Rotation>
</RotateTransform3D>
</ModelVisual3D.Transform>
</ModelVisual3D>
</Viewport3D>
<Image Name="rtbImage" Visibility="Collapsed"/>
<Button Grid.Row="1" Click="Button_Click">RenderTargetBitmap!</Button>
</Grid>
</Window>
And this code:
private void Button_Click(object sender, RoutedEventArgs e)
{
RenderTargetBitmap bmp = new RenderTargetBitmap((int)viewport3D.ActualWidth,
(int)viewport3D.ActualHeight, 96, 96, PixelFormats.Default);
bmp.Render(viewport3D);
rtbImage.Source = bmp;
viewport3D.Visibility = Visibility.Collapsed;
rtbImage.Visibility = Visibility.Visible;
}

There is no setting on RenderTargetBitmap to tell it to render using hardware, so you will have to fall back to using Win32 or DirectX. I would recommend using the DirectX technique given in this article. The following code from the article and shows how it can be done (this is C++ code):
extern IDirect3DDevice9* g_pd3dDevice;
Void CaptureScreen()
{
IDirect3DSurface9* pSurface;
g_pd3dDevice->CreateOffscreenPlainSurface(ScreenWidth, ScreenHeight,
D3DFMT_A8R8G8B8, D3DPOOL_SCRATCH, &pSurface, NULL);
g_pd3dDevice->GetFrontBufferData(0, pSurface);
D3DXSaveSurfaceToFile("Desktop.bmp",D3DXIFF_BMP,pSurface,NULL,NULL);
pSurface->Release();
}
You can create the Direct3D device corresponding to the place where the WPF content is being rendered as follows:
Calling Visual.PointToScreen on a point within your onscreen image
Calling MonitorFromPoint in User32.dll to get the hMonitor
Calling Direct3DCreate9 in d3d9.dll to get a pD3D
Calling pD3D->GetAdapterCount() to count adapters
Iterating from 0 to count-1 and calling pD3D->GetAdapterMonitor() and comparing with the previously retrieved hMonitor to determine the adapter index
Calling pD3D->CreateDevice() to create the device itself
I would probably do most of this in a separate library coded in C++/CLR because that approach is familiar to me, but you may find it easy to translate it to pure C# and managed code using using SlimDX. I haven't tried that yet.

I don't know what mip-mapping is (or whether the software renderer does that and/or multi-level anti-aliasing), but I do recall a post by Charles Petzold a while ago that was all about printing hi-res WPF 3D visuals.
I tried it out with your sample code and it appears to work great. So, I assume you just needed to scale things up a bit.
You need to set Stretch to None on the rtbImage and modify the Click event handler as follows:
private void Button_Click(object sender, RoutedEventArgs e)
{
// Scale dimensions from 96 dpi to 600 dpi.
double scale = 600 / 96;
RenderTargetBitmap bmp =
new RenderTargetBitmap
(
(int)(scale * (viewport3D.ActualWidth + 1)),
(int)(scale * (viewport3D.ActualHeight + 1)),
scale * 96,
scale * 96,
PixelFormats.Default
);
bmp.Render(viewport3D);
rtbImage.Source = bmp;
viewport3D.Visibility = Visibility.Collapsed;
rtbImage.Visibility = Visibility.Visible;
}
Hope that solves your problem!

I think you were getting a blank screen for a couple reasons. First, the VisualBrush needed to be pointing to a visible Visual. Second, maybe you forgot that the RectangleGeometry needed to have dimensions (I know I did at first).
I did see some odd things that I don't quite understand. That is, I do not understand why I had to set AlignmentY to Bottom on the VisualBrush.
Other than that, I think it works ... and I think you should easily be able to modify the code for your real situation.
Here is the button click event handler:
private void Button_Click(object sender, RoutedEventArgs e)
{
GeometryDrawing geometryDrawing = new GeometryDrawing();
geometryDrawing.Geometry =
new RectangleGeometry
(
new Rect(0, 0, viewport3D.ActualWidth, viewport3D.ActualHeight)
);
geometryDrawing.Brush =
new VisualBrush(viewport3D)
{
Stretch = Stretch.None,
AlignmentY = AlignmentY.Bottom
};
DrawingImage drawingImage = new DrawingImage(geometryDrawing);
image.Source = drawingImage;
}
Here is Window1.xaml:
<Window
x:Class="RenderTargetBitmapProblem.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
SizeToContent="WidthAndHeight"
>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="400"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="400"/>
</Grid.ColumnDefinitions>
<Viewport3D
x:Name="viewport3D"
Grid.Row="0"
Grid.Column="0"
>
<Viewport3D.Camera>
<PerspectiveCamera Position="0,0,3"/>
</Viewport3D.Camera>
<ModelVisual3D>
<ModelVisual3D.Content>
<AmbientLight Color="White"/>
</ModelVisual3D.Content>
</ModelVisual3D>
<ModelVisual3D>
<ModelVisual3D.Content>
<GeometryModel3D>
<GeometryModel3D.Geometry>
<MeshGeometry3D
Positions="-1,-10,0 1,-10,0 -1,20,0 1,20,0"
TextureCoordinates="0,1 0,0 1,1 1,0"
TriangleIndices="0,1,2 1,3,2"
/>
</GeometryModel3D.Geometry>
<GeometryModel3D.Material>
<DiffuseMaterial>
<DiffuseMaterial.Brush>
<ImageBrush
ImageSource="http://www.wyrmcorp.com/galleries/illusions/Hermann%20Grid.png"
TileMode="Tile"
Viewport="0,0,0.25,0.25"
/>
</DiffuseMaterial.Brush>
</DiffuseMaterial>
</GeometryModel3D.Material>
</GeometryModel3D>
</ModelVisual3D.Content>
<ModelVisual3D.Transform>
<RotateTransform3D>
<RotateTransform3D.Rotation>
<AxisAngleRotation3D Axis="1,0,0" Angle="-82"/>
</RotateTransform3D.Rotation>
</RotateTransform3D>
</ModelVisual3D.Transform>
</ModelVisual3D>
</Viewport3D>
<Image
x:Name="image"
Grid.Row="0"
Grid.Column="0"
/>
<Button Grid.Row="1" Click="Button_Click">Render!</Button>
</Grid>
</Window>

I think the issue here indeed is that the software renderer for WPF does not perform mip-mapping and multi-level anti aliasing. Rather than using RanderTargetBitmap, you may be able to create an DrawingImage whose ImageSource is the 3D scene you want to render. In theory, the hardware render should produce the scene image, which you can then programmatically extract from the DrawingImage.

Using SlimDX, try accessing the DirectX surface that the ViewPort3D renders to,
then performing a read-pixel to read the buffer from the graphics card's pixel buffer into regular memory.
Once you have the (unmanaged) buffer, copy it into an existing writable bitmap using unsafe code or marshalling.

I've also had a few useful answers to this question over at the Windows Presentation Foundation forums at http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/50989d46-7240-4af5-a8b5-d034cb2a498b/.
In particular, I'm going to try these two answers, both from Marco Zhou:
Or you could try rendering the
Viewport3D into a off-screen
HwndSource, and then grab its HWND,
and feed it into Bitblt function . The
Bitblt will copy what's already
rendered by the hardware rasterizer
back to your own in memory buffer. I
am not trying this method myself, but
it's worth trying, and theoretically
speaking, it should work.
and
I think one easy way without pinvoking
into the WIN32 API is to place the
Viewport3D into ElementHost, and call
its ElementHost.DrawToBitmap(), one
caveat here is that you need to call
the DrawToBitmap() at the right time
after the Viewport3D is "fully
rendered", you could manually pump the
messages by calling
System.Windows.Forms.Application.DoEvents(),
and hook up
CompositionTarget.Rendering event to
get callback from the composition
thread (This might work since I am not
exactly sure if the Rendering event is
reliable in this typical
circumstance). BTW, the above method
is based on the assumption that you
don't need to display the ElementHost
on the screen. The ElementHost will be
displayed on the screen, you could
directly call the DrawToBitmap()
method.

Related

Possible to cut an image based on the shape of another image?

In Windows Presentation Foundation, I can't seem to find a way of how to cut an image based on the shape of another image.
E.g. I'd like to display someone's photo in the shape of a heart.
There are answers like this one which crop an image into a rectangle or like this one which draw a radius to clip the image into a circle.
But is cropping really the only way?
Can WPF overlay the image on top of a shape and have the image be cut based on the shape dimensions?
The code that I have so far does the inverse of what I'm trying to do. What I have so far uses an overlay layer as a mask to cover the image:
<Image
Name="HeartOverlay"
VerticalAlignment="Stretch"
HorizontalAlignment="Stretch"
Panel.ZIndex="2"
/>
<Canvas
Name="Canvas"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch">
<Image
Name="Image"
Stretch="Uniform"
Panel.ZIndex="1"
/>
/>
HeartOverlay.Source = new Bitmap(#"C:\heart.png");
Image.Source = new Bitmap(#"C:\image.png");
The problem here is that overlay is merged together with the image and saving/printing the image also shows the overlay.
See image below as an example. Note the white borders, which are especially evident when viewing the image in something like the Mac Preview app. I'm looking to save/print the image without the white borders.
Appreciate any pointers!
You could simply fill a Path with a heart-shaped Geometry with an ImageBrush:
<Path Width="100" Height="150" Stretch="Uniform"
Data="M1,2 L0,1 A0.5,0.5 1 1 1 1,0 A0.5,0.5 1 1 1 2,1 Z">
<Path.Fill>
<ImageBrush ImageSource="C:\image.png"/>
</Path.Fill>
</Path>

RenderTargetBitmap Image Sliding

I'm having a problem with RenderTargetBitmap whenever I render canvas and clear its children and set the rendered bitmap as background of canvas it slide toward bottom right.
can't insert images until 10 reputation :(.
WPF:
<Window x:Class="WpfApp1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp1"
mc:Ignorable="d"
Title="MainWindow" Height="500" Width="700"
KeyDown="Window_KeyDown">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="50"/>
<RowDefinition Height="*"/>
<RowDefinition Height="50"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="50"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="50"/>
</Grid.ColumnDefinitions>
<Border BorderBrush="Black" BorderThickness="1" Grid.Row="1" Grid.Column="1">
<Canvas x:Name="Pad">
<Rectangle Height="100" Width="100" Fill="Red" Canvas.Left="10" Canvas.Top="10"></Rectangle>
</Canvas>
</Border>
</Grid>
</Window>
c# code:
namespace WpfApp1
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Window_KeyDown(object sender, KeyEventArgs e)
{
RenderTargetBitmap rendrer = new RenderTargetBitmap(Convert.ToInt32(Pad.ActualWidth), Convert.ToInt32(Pad.ActualHeight), 96, 96, PixelFormats.Pbgra32);
rendrer.Render(Pad);
Pad.Background = new ImageBrush(rendrer);
Pad.Children.Clear();
}
}
}
To avoid any offset problems with drawing a Visual into a RenderTargetBitmap, you may use an intermediate DrawingVisual:
var rect = new Rect(Pad.RenderSize);
var visual = new DrawingVisual();
using (var dc = visual.RenderOpen())
{
dc.DrawRectangle(new VisualBrush(Pad), null, rect);
}
var bitmap = new RenderTargetBitmap(
(int)rect.Width, (int)rect.Height, 96, 96, PixelFormats.Default);
bitmap.Render(visual);
Pad.Background = new ImageBrush(bitmap);
Pad.Children.Clear();
Note that without setting any further properties of the ImageBrush (like e.g. its Viewport), it will fill the entire area of the Rectangle. For details, see TileBrush Overview.
Your primary problem stems from the fact that, due to the 1-pixel border around the Canvas, its VisualOffset vector is (1,1). Thus, any visual effect, like the background brush, will be applied at that offset. When you render the visual into a bitmap, it captures the present appearance, and then when you set the bitmap as the brush, it gets shifted.
Ironically, one of the easiest ways to fix this is to insert another <Border/> element into your XAML:
<Border BorderBrush="Black" BorderThickness="1" Grid.Row="1" Grid.Column="1">
<Border>
<Canvas x:Name="Pad">
<Rectangle Height="100" Width="100" Fill="Red" Canvas.Left="10" Canvas.Top="10"/>
</Canvas>
</Border>
</Border>
Then the offset caused by the outer <Border/> element is handled by the new <Border/> element's transform, rather than being applied to the <Canvas/> element.
That change alone will almost fix your code completely. However, there's one other little artifact that you may still notice: every time you render the visual, it gets just a teensy bit blurrier. This is because the default value for the Brush object's Stretch property is Stretch.Fill, and because your <Canvas/> element is not precisely an integral width or height, the bitmap (which necessarily does have integral width and height) gets stretched just a teensy bit when rendered. With each iteration, this becomes more and more apparent.
You can fix that by setting the Stretch property to Stretch.None. At the same time, you'll also want to set the brush's alignment to Left and Top:
private void Window_KeyDown(object sender, KeyEventArgs e)
{
RenderTargetBitmap renderer = new RenderTargetBitmap(
Convert.ToInt32(Pad.ActualWidth), Convert.ToInt32(Pad.ActualHeight), 96, 96, PixelFormats.Pbgra32);
renderer.Render(Pad);
ImageBrush brush = new ImageBrush(renderer);
brush.AlignmentX = AlignmentX.Left;
brush.AlignmentY = AlignmentY.Top;
brush.Stretch = Stretch.None;
Pad.Background = brush;
Pad.Children.Clear();
}
The defaults are Center, which again incurs the rounding error and will cause both movement and blurring of the image after repeated iterations of the process.
With the above changes, I found a perfectly stable image, regardless of the number of iterations.
The "wrap in a border" idea came from here: https://blogs.msdn.microsoft.com/jaimer/2009/07/03/rendertargetbitmap-tips/
On that page you'll find a more general-purpose solution which does not require modification of the actual XAML. In your example above, the "wrap in a border" approach seems like a reasonable work-around, but it is admittedly not as clean as forcing an unadorned context into which you can render the visual, as shown on that blog page.

How to override all Shapes in a specific area WPF

Currently I am filling my MainWindow with a slightly transparent black:
But I want it to have a "hole" where this effect doesn't take place which should look like the following:
So this needs to be done at runtime since the area which the hole represents is going to change multiple times while the program is running.
What I thought I could do
So at first I thought I could just cut the area in the middle out
like you could do with a Graphics object, but the slightly
transparent black is nothing but a rectangle which is added as a child on a canvas which is currently done like this:
var background = new System.Windows.Shapes.Rectangle
{
Fill = new SolidColorBrush(System.Windows.Media.Color.FromArgb(150, 0, 0, 0)),
Width = ScreenInfo.Width,
Height = ScreenInfo.Height
};
MainCanvas.Children.Add(background);
But I couldn't fine any way to achieve this cut effect.
Creating 4 Rectangles which would look something like this: but this way of doing it didn't seem to me as the most effecient way of achieving this.
Thanks for any kind of help!
Create a CombinedGeometry by cutting a smaller square out of a larger one and then use that with a path. How you size it will depend on your application, a Viewbox will probably be good enough for most cases:
<Grid>
<TextBlock Text="Hello World!" FontSize="200" Foreground="Red" TextWrapping="Wrap" TextAlignment="Center"/>
<Viewbox Stretch="UniformToFill">
<Path Fill="#C0000000">
<Path.Data>
<CombinedGeometry GeometryCombineMode="Exclude">
<CombinedGeometry.Geometry1>
<RectangleGeometry Rect="0,0,4,4" />
</CombinedGeometry.Geometry1>
<CombinedGeometry.Geometry2>
<RectangleGeometry x:Name="cutRect" Rect="1,1,2,2" />
</CombinedGeometry.Geometry2>
</CombinedGeometry>
</Path.Data>
</Path>
</Viewbox>
</Grid>
Then to change the size of the inner geometry you can either bind its Rect to a view model property or change it directly in code-behind:
cutRect.Rect = new Rect(1, 1, 1, 1);

Irregular behavior - XAML / UWP Community Toolkit Scale animation

Problem : I am using UWP Community Toolkit Scale animation and it works as expected for most of the images in the GridView, but for some the image goes out of bounds . (Please see the image below)
I have detected that the issue happens when the image width is more than 2x (2 times) the height of the image. That is when the image is very wide.
Code
I am using a user control as data template
Xaml :
<!-- Grid View -->
<GridView x:Name="gridView" SelectionChanged="gridView_SelectionChanged">
<GridView.ItemTemplate>
<DataTemplate>
<local:GridViewMenu/>
</DataTemplate>
</GridView.ItemTemplate>
</GridView>
<!-- GridViewMenu User Control markup -->
<Grid>
<StackPanel>
<Image Source="{Binding webformatURL}" Stretch="UniformToFill" PointerEntered="image_PointerEntered" PointerExited="image_PointerExited"/>
</StackPanel>
</Grid>
C# Code :
private void image_PointerEntered(object sender, PointerRoutedEventArgs e)
{
Image img = sender as Image;
img.Scale(centerX: (float)(grid.ActualWidth / 2),
centerY: 100,
scaleX: 1.2f,
scaleY: 1.2f,
duration: 500, delay: 0).StartAsync();
}
private void image_PointerExited(object sender, PointerRoutedEventArgs e)
{
Image img = sender as Image;
img.Scale(centerX: (float)(grid.ActualWidth / 2),
centerY: 100,
scaleX: 1f,
scaleY: 1f,
duration: 500, delay: 0).StartAsync();
}
Result (Top left image is not scaling as expected, that is, it is going out of bounds)
How can I solve this issue ?
The scale animation of UWP Community Toolkit package actually use the CompositeTransform class for scaling. According to the description of Transforms and layout section:
Because layout comes first, you'll sometimes get unexpected results if you transform elements that are in a Grid cell or similar layout container that allocates space during layout. The transformed element may appear truncated or obscured because it's trying to draw into an area that didn't calculate the post-transform dimensions when dividing space within its parent container.
So that the parts overflow the bound that being truncated are unexpected. In another words, the image goes out is the transform expected. The current way you are using to meet your requirements is not reliable. If you change width-height ratio of GridViewMenu to 1.0 , you may find more images that width-height ratio larger than 1.0 will go out.
For a solution inside GridView, you could consider to use the ScrollViewer to zoom in the image instead, which can ensure the image is limited in a fixed area. For example:
<Grid x:Name="grid">
<ScrollViewer
x:Name="currentscroll"
HorizontalScrollBarVisibility="Hidden"
VerticalScrollBarVisibility="Hidden">
<Image
x:Name="myImage"
Width="300"
Height="180"
PointerEntered="image_PointerEntered"
PointerExited="image_PointerExited"
Source="{Binding webformatURL}"
Stretch="UniformToFill">
</Image>
</ScrollViewer>
</Grid>
Code behind:
private void image_PointerEntered(object sender, PointerRoutedEventArgs e)
{
currentscroll.ChangeView(0, 0, 1.2f );
}
private void image_PointerExited(object sender, PointerRoutedEventArgs e)
{
currentscroll.ChangeView(0, 0, 1.0f);
}
You can try to use clipping:
<Grid>
<StackPanel>
<Image Source="{Binding webformatURL}" Stretch="UniformToFill"
PointerEntered="image_PointerEntered"
PointerExited="image_PointerExited">
<Image.Clip>
<RectangleGeometry Rect="0,0,300,150" />
</Image.Clip>
</Image>
</StackPanel>
</Grid>
300 and 150 would be the width and height of the grid item.
Otherwise it looks like a bug in the UWP Community Toolkit, it would be best to report it as an issue on GitHub.

XAML gradient issue in UWP for some devices

I'm using Page as landing screen in my app. XAML looks like this:
<Grid x:Name="LayoutRoot">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="3*"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="7*"/>
</Grid.RowDefinitions>
<Rectangle StrokeThickness="0" Fill="#FF79D2F4" Margin="0,0,0,-10" Grid.RowSpan="2"/>
<Rectangle StrokeThickness="0" Fill="#FF1F8CC5" Margin="0,-10,0,0" Grid.Row="2" Grid.RowSpan="2"/>
<Image Source="ms-appx:///Assets/ViewMedia/Banners/Banner_Light_Big.jpg" Grid.Row="1" Grid.RowSpan="2"/>
<Rectangle StrokeThickness="0" Grid.Row="2" Grid.RowSpan="2">
<Rectangle.Fill>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Offset="0"/>
<GradientStop Color="#7F000000" Offset="1"/>
</LinearGradientBrush>
</Rectangle.Fill>
</Rectangle>
</Grid>
<StackPanel MaxWidth="300" Margin="20,35"
HorizontalAlignment="Stretch" VerticalAlignment="Bottom">
<Button x:Name="LoginButton" x:Uid="LoginButton" Style="{StaticResource BrandButtonStyle}" Margin="0,5"
Click="LoginButton_Click"/>
<Button x:Name="RegisterButton" x:Uid="RegisterButton" Style="{StaticResource BrandButtonStyle}" Margin="0,5"
Click="RegisterButton_Click"/>
</StackPanel>
</Grid>
I've got 3 devices on which I'm running the app:
Microsoft Lumia 950 XL [M]
Custom build PC [PC]
Lenovo ThinkPad Tablet 2 [T]
When running the app this page renders well on M and PC but on T Gradient and two Buttons at the bottom are not rendered at all. I don't see them but I can press Buttons and their tap event handlers will strike. But if I comment Rectangle with gradient everything is fine on all devices.
This is how the app looks on T when using gradient. No buttons. And gradient is also not visible.
This is how the app looks on T without gradient. Buttons are in place.
And this is how it should look running on PC. Buttons and gradient are visible.
I don't see any errors in output when running the app. I don't know why this happens only on specific devices. Maybe this is kind of known issue?
UPDATE 1
From users feedback, I can say that this bug hits only Atom-powered devices. But I'm not sure if this is 100% true for all Atom-powered devices.
UPDATE 2
I'd updated T with W10 from Insider Preview Fast Ring. The bug is in place. So this is not connected to OS builds.
UPDATE 3
Switching Buttons Style back to normal does not solve this. So Style is good, it's not the cause.
Try removing the Grid.RowSpan="2" from the Rectangle (or add a RowDefinition), you have 4 rows (4 RowDefinition) but with the Rectangle having Grid.RowSpan=2 it adds up to 5 rows, so it might be causing you trouble.
EDIT: My bad, Rectangle actually spans over rows 2 and 3 (Grid.Row="2"), so it's ok.
Since you're just stacking <StackPanel> over <Grid> (with nothing fancy), you could try to replace the root layout <Grid x:Name="LayoutRoot"> with <Canvas x:Name="LayoutRoot"> and see if that makes a difference.
I've come across similar issues, and went for a different and more portable approach.
I made a gradient image of height 1 (to save space), and sufficient pixels in width to give the proper gradient resolution. Added an image and stretched it. Quite a bit faster and offloads the renderling pipeline as well.
And it works just as well in Xamarin.Forms.
The fact that the rectangle has a gradient in it is a probably a "red herring".
Focus first on why the buttons don't appear at all. Once you solve that, it should be easy to add the gradient.
There are two likely reasons:
Adding the rectangle pushes the buttons down offscreen.
or 2. The renderer "choked" on the gradient, and didn't render anything else after it encountered it.
IMHO, #1 is more likely. I say that because I notice your overlaid StackLayout has VerticalAlignment="Bottom". So if the layout engine has (mistakenly?) decided that the single cell in the outermost grid is much taller than the screen, then two things will happen: the gradient will be stretched very far vertically (so appears not to change), and the buttons will be pushed off the bottom of the screen.
#2 would be a renderer bug involving gradient (but I doubt that will be the case).
back to #1:
What is the actual pixel height of "Banner_Light_Big.jpg"? Consider making a smaller version for the device giving you trouble [picking a version based on device height in inches or in pixels, not sure which applies here]. If you remove the banner completely, does the problem go away? If so, but you don't want to shrink it, you might need to override layout (measure?) method and do your own calculation.
Alternatively, change the two "Auto" heights to "NN*" or "NN" (NN = any specific number): anything with no "Auto"s will almost surely eliminate the problem.
If the resulting "non-Auto" layout isn't exactly what you want, at least it will give you a working starting point, from which to try slightly different variations on how to nest these elements, to get the desired spacing.
Try adding the color attribute and value for the first Gradient stop as well.
Maybe since only a single color is specified, it takes the same color and applies throught the button.
<Rectangle.Fill>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Offset="0"/> // add color attribute here
<GradientStop Color="#7F000000" Offset="1"/>
</LinearGradientBrush>
</Rectangle.Fill>

Categories

Resources