Image added to canvas is bigger than the canvas - c#

<Grid Name="PlotGrid" Margin="50,50,50,50">
<Grid.RowDefinitions>
<RowDefinition Height="50" />
<RowDefinition Height="500" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100" />
<ColumnDefinition Width="100" />
</Grid.ColumnDefinitions>
<Canvas Name="canvas" Grid.Row="0" Grid.Column="0" />
<Border Name="firstborder"
Grid.Column="0"
Grid.Row="0"
BorderBrush="Black"
BorderThickness="1">
</Border>
<Border Name="secondborder"
Grid.Column="1"
Grid.Row="0"
BorderBrush="Black"
BorderThickness="1">
</Border>
<Border Name="thirdborder"
Grid.Column="0"
Grid.Row="1"
BorderBrush="Black"
BorderThickness="1">
</Border>
<Border Name="fourthborder"
Grid.Column="1"
Grid.Row="1"
BorderBrush="Black"
BorderThickness="1">
</Border>
</Grid>
I am dynamically adding an image to the canvas above, which is inside a grid cell:
try
{
if ((myStream = openFileDialog.OpenFile()) != null)
{
using (myStream)
{
// Insert code to read the stream here.
image1.Source = new BitmapImage(new Uri( openFileDialog.FileName));
canvas.Children.Add(image1);
}
}
}
My expectation is that the imported image will remain inside the canvas and inside the grid cell that contains the canvas. But it occupies a huge space well beyond the grid cell. How can I keep the imported image within the confines of the grid cell?

You need to set the image size, otherwise it will be full size
image1.Stretch = Stretch.Uniform;
image1.StretchDirection = StretchDirection.Both;
image1.BeginInit();
image1.Source = new BitmapImage(new Uri( openFileDialog.FileName));
image1.Width = canvas.ActualWidth;
image1.Height = canvas.ActualHeight;
image1.EndInit();
You may also need to add code to handle resizing of the grid.

Perhaps this might work:
...
image1.Stretch = Stretch.Uniform;
image1.StretchDirection = StretchDirection.Both;
image1.BeginInit();
image1.Source = new BitmapImage(new Uri( openFileDialog.FileName));
image1.EndInit();
canvas.Children.Add(image1);

Related

Process Memory increase WPF application

I'm creating a WPF program for editing PowerPoint presentation using Syncfusion library but whenever I run the program I see the memory increase when navigating from a page to another. I'm using WPF Application with a window that navigates between multiple pages.
How to encounter this problem actually?
Thank you.
These photos show where the leak is located :
PS: Please focus on the InitializeNonUITasks method in home.cs because that's where the leak is.
Home Page XAML:
<Page x:Class="ProjectSABX.Pages.Home"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:ProjectSABX.Pages"
xmlns:syncfusion="clr-namespace:Syncfusion.Windows;assembly=Syncfusion.Shared.Wpf"
xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
mc:Ignorable="d"
Width="1175" Height="660" KeyDown="Window_KeyDown"
Title="Home">
<Grid ShowGridLines="False" Margin="2,-2,-2,2">
<Grid Grid.Row="0" ShowGridLines="False">
<Grid.Background>
<SolidColorBrush Color="White" Opacity="0.5" />
</Grid.Background>
<Grid.RowDefinitions>
<RowDefinition Height="2.5*"></RowDefinition>
</Grid.RowDefinitions>
<Rectangle Height="52" Grid.Row="0" VerticalAlignment="Top" Fill="#FF80A20D"></Rectangle>
<TextBlock Name="titleBarTextBlock" Text="Aperçu" Height="40" Foreground="White" FontFamily="Segoe UI" FontWeight="Normal" Padding="15" FontSize="17.75" VerticalAlignment="Top" Grid.Row="0" HorizontalAlignment="Center"></TextBlock>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" VerticalAlignment="Top" Margin="0 15 10 0" Grid.Column="3" Grid.Row="0">
</StackPanel>
<Image Source="/Images/ViewerIcons/ppt__logo for header.png" Grid.Column="0" HorizontalAlignment="Left" Margin="15" VerticalAlignment="Top" Height="30"></Image>
</Grid>
<Grid Grid.Row="1" ShowGridLines="False">
<Grid.RowDefinitions>
<RowDefinition Height="0*" />
<RowDefinition Height="445*" />
<RowDefinition Height="Auto" />
<RowDefinition Height="59*"></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="2*" />
<ColumnDefinition Width="8*" />
</Grid.ColumnDefinitions>
<Border ClipToBounds="True" BorderBrush="Black" BorderThickness=".7" Grid.Row="1" Grid.Column="0" Grid.RowSpan ="3" Margin="0,51,3,0">
<ScrollViewer Name="scrollViewer" Focusable="False" CanContentScroll="False" BorderBrush="Black" BorderThickness="1" HorizontalScrollBarVisibility="Auto" Grid.Row="1" Grid.Column="0" Grid.RowSpan ="3">
<Grid ShowGridLines="False">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*" />
<ColumnDefinition Width="9*" />
</Grid.ColumnDefinitions>
<StackPanel Name="stackpanel" Grid.Column="1" Width="170" />
</Grid>
</ScrollViewer>
</Border>
<Image Name ="centerSlideImage" Grid.Row="1" Grid.Column="1" Margin="0,57,5,19" />
<Canvas Name="loadingIndicatorCanvas" Visibility="Collapsed" HorizontalAlignment="Center" VerticalAlignment="Center" Grid.Row="1" Grid.Column="1" Margin="-250,-100,0,0">
<Canvas Canvas.Left="21.75" Canvas.Top="14" Height="81.302" Width="80.197">
<Canvas.Resources>
<Style TargetType="Ellipse">
<Setter Property="Width" Value="5" />
<Setter Property="Height" Value="5" />
<Setter Property="Fill" Value="#FF9BD226" />
</Style>
</Canvas.Resources>
<Ellipse x:Name="_00" Canvas.Left="24.75" Canvas.Top="50" />
<Ellipse x:Name="_01" Canvas.Top="36" Canvas.Left="29.5" />
<Ellipse x:Name="_02" Canvas.Left="43.5" Canvas.Top="29.75" />
<Ellipse x:Name="_03" Canvas.Left="57.75" Canvas.Top="35.75" />
<Ellipse x:Name="_04" Canvas.Left="63.5" Canvas.Top="49.75" />
<Ellipse x:Name="_05" Canvas.Left="57.75" Canvas.Top="63.5" />
<Ellipse x:Name="_06" Canvas.Left="43.75" Canvas.Top="68.75" />
<Ellipse x:Name="_07" Canvas.Top="63.25" Canvas.Left="30" />
<Ellipse Stroke="{x:Null}" Width="39.5" Height="39.5" Canvas.Left="31.75" Canvas.Top="37" Fill="{x:Null}" />
</Canvas>
</Canvas>
<Grid Grid.Row="3" Grid.Column="1" ShowGridLines="False" Margin="0, -10">
<Grid.RowDefinitions>
<RowDefinition Height="0.5*" />
<RowDefinition Height="20*" />
<RowDefinition Height="10*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="42*" />
<ColumnDefinition Width="45*" />
<ColumnDefinition Width="44*" />
<ColumnDefinition Width="45*" />
<ColumnDefinition Width="238*" />
<ColumnDefinition Width="30*" />
<ColumnDefinition Width="40*" />
<ColumnDefinition Width="46*" />
<ColumnDefinition Width="30*" />
<ColumnDefinition Width="45*" />
</Grid.ColumnDefinitions>
<Image Name="openDocument" Grid.Row="1" Grid.Column="1" Height="30" Width="30" Source="/Images/ViewerIcons/ppt__open.png" MouseDown="openDocument_MouseDown" MouseEnter="openDocument_MouseEnter" MouseLeave="openDocument_MouseLeave" Margin="0,5,7,4"></Image>
<Image Name="createPdfDocument" Grid.Row="1" Grid.Column="3" Height="30" Width="30" Source="/Images/ViewerIcons/ppt_pdf.png" MouseDown="createPdfDocument_MouseDown" MouseEnter="createPdfDocument_MouseEnter" MouseLeave="createPdfDocument_MouseLeave" Margin="0,5,8,4"></Image>
<DockPanel Grid.Row="1" Grid.Column="6" Grid.ColumnSpan="3">
<Image Name="prevDocument" Height="30" Width="30" Source="/Images/ViewerIcons/ppt__back.png" MouseDown="prevDocument_MouseDown" MouseEnter="prevDocument_MouseEnter" MouseLeave="prevDocument_MouseLeave"></Image>
<Label Name="lblPageDisplay" Height="30" MinWidth="30" FontFamily="Segoe UI" FontWeight="Bold" FontSize="18" VerticalAlignment="Center" VerticalContentAlignment="Center" Padding="35,0,0,0" Foreground="#646464" />
<Image Name="NextDocumentIconImage" Height="30" Width="30" Source="/Images/ViewerIcons/ppt__for.png" MouseDown="NextDocument_MouseDown" MouseEnter="NextDocument_MouseEnter" MouseLeave="NextDocument_MouseLeave" Margin="-10,0"></Image>
</DockPanel>
</Grid>
</Grid>
</Grid>
Home Page C#:
public Home()
{
InitializeComponent();
pdfBackroundWorker.DoWork += pdfBackroundWorker_DoWork;
pdfBackroundWorker.RunWorkerCompleted += pdfBackroundWorker_RunWorkerCompleted;
this.Background = new SolidColorBrush(Color.FromRgb(244, 244, 244));
filePath = "/Data/Template.pptx";
InitializeNonUITasks();
InitializeUITasks(filePath);
}
private void openDocument_MouseDown(object sender, MouseButtonEventArgs e)
{
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
dlg.Filter = "PowerPoint Presentations|*.pptx";
Nullable<bool> result = dlg.ShowDialog();
if (result == true)
{
string filename = dlg.FileName;
filePath = filename;
slideNumber = 1;
displayBackroundWorker.RunWorkerAsync();
}
}
private void InitializeNonUITasks()
{
try
{
presentation = Presentation.Open(filePath);
}
catch (Exception exp)
{
MessageBox.Show("This PowerPoint Presentation cannot be opened properly, please contact support");
return;
}
slideImageSources.Clear();
thumbnailImageSource.Clear();
printImages.Clear();
currentSlideNumber = 0;
presentation.ChartToImageConverter = new ChartToImageConverter();
presentation.ChartToImageConverter.ScalingMode = Syncfusion.OfficeChart.ScalingMode.Best;
try
{
foreach (ISlide slide in presentation.Slides)
{
using (System.Drawing.Image image = slide.ConvertToImage(Syncfusion.Drawing.ImageType.Bitmap))
{
System.Drawing.Image.GetThumbnailImageAbort myCallback = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
printImages.Add(image.Clone() as System.Drawing.Image);
System.Drawing.Image newImage = image.GetThumbnailImage(170, 100, myCallback, System.IntPtr.Zero);
using (Stream ms = new MemoryStream())
{
newImage.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
var decoder = BitmapDecoder.Create(ms, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);
thumbnailImageSource.Add(decoder.Frames[0]);
}
using (Stream ms = new MemoryStream())
{
image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
var decoder = BitmapDecoder.Create(ms, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);
slideImageSources.Add(decoder.Frames[0]);
}
}
}
}
catch (Exception)
{
MessageBox.Show("This PowerPoint Presentation cannot be converted to images properly, please contact support");
return;
}
}
MainWindow XAML:
<Frame Grid.Column="1" Grid.Row="1" NavigationUIVisibility="Hidden" x:Name="Main" Source="./Pages/Home.xaml">
<Frame.Background>
<SolidColorBrush Color="#FFB0B0B0" Opacity="0.49" />
</Frame.Background>
</Frame>
MainWindow.cs:
public partial class MainWindow : Window
{
public MainWindow()
{
DataContext = this;
InitializeComponent();
}
private void ButtonClickHomePage(object sender, RoutedEventArgs e)
{
Main.Content = new Home();
}
}
Edit1: I tried to use the dispose() method for each object that implemented IDisposable, When navigating at first, the memory process decreases. then when I navigate from page to page it increases again.
It is hard to pinpoint the issue like this, but I do have some suggestions:
Usually it's about calling Dispose on all objects that implement the IDisposable interface.
check all object for the IDisposable interface and call Dispose() if it's available. E.g.: newImage.Dispose() (or use using)
Also, all the disposable objects in the lists printImages, thumbnailImageSource etc, should be disposed as well.
Also, I believe the decoder should be disposed as well, as well as the presentation, although I can be mistaken.
This will give you a good starting point - there might be more, but you should rule out and fix this first.
The loop is a likely suspect to be causing the memory increase.
Here's more info on IDisposable. Also, if you have implemented the IDisposable interface yourself - it's prety common to make a mistake with that as well. In that case you should double check it.

How to dynamically change grid rows and columns according to window size in WPF

I'm making an image gallery of sorts, and I'm currently loading the images into a grid dynamically via C#. If I shouldn't be using a grid to display the images, I'm more than willing to change it to a better-suited control, but it needs to be window-resizing-friendly.
When I resize the window, I want the following things to happen:
The images all stay the exact same size. They already fit into the grid slots while maintaining their aspect ratio
The grid spaces themselves are also not resized at all
The grid contains more or less rows/columns depending on how many can fit into the window.
This would mean that, if the window was resized to be very thin and very high, the grid would contain one column (or two, or however many are needed) and many rows to display the images in.
If it was very wide, but not high, then it would only have one (or two, or however many are needed) row(s) and many columns. Etc.
Not sure if it's needed but my code to display the images is:
for (int i = 0; i < ImageGrid.RowDefinitions.Count; i++)
{
for (int j = 0; j < ImageGrid.ColumnDefinitions.Count; j++)
{
Image img = new Image();
BitmapImage bitmap = new BitmapImage();
using (var fs = new FileStream(path, FileMode.Open)) // open the image
{
bitmap.BeginInit();
bitmap.StreamSource = fs;
bitmap.CacheOption = BitmapCacheOption.OnLoad;
bitmap.EndInit();
}
bitmap.Freeze(); // bitmap isn't properly cleaned up and memory leaks can occur if this isn't here
img.Source = bitmap;
img.Margin = new Thickness(10);
img.Stretch = Stretch.Uniform;
Grid.SetRow(img, i);
Grid.SetColumn(img, j);
ImageGrid.Children.Add(img);
}
}
And my XAML for the grid is:
<Grid ShowGridLines="True" Background="DimGray">
<Grid.ColumnDefinitions>
<ColumnDefinition MinWidth="175" Width="0"/>
<ColumnDefinition MinWidth="755" Width="Auto"/>
</Grid.ColumnDefinitions>
<Label Name="lblWinSize" Content="Width, Height"
HorizontalAlignment="Left" VerticalAlignment="Bottom"/>
<TextBox Name="txtnbox" Style="{StaticResource CustomTxtBox}"
TextWrapping="NoWrap" Width="Auto" Height="25" VerticalAlignment="Top"
Margin="10, 20, 10, 0"/>
<Separator Style="{StaticResource VerticalSeparator}"
HorizontalAlignment="Right" Height="Auto" Width="2" Margin="0,10,0,10"/>
<CheckBox Style="{StaticResource CustomCheckBox}"
HorizontalAlignment="Left" Margin="10,50,0,0" VerticalAlignment="Top"/>
<Grid Name="ImageGrid" Grid.Column="1" Margin="10,10,0,10"
ShowGridLines="True" Background="Gray">
<!--this is the grid where the images would go-->
</Grid>
</Grid>
Sorry about the indentation with that XAML, I couldn't get it to format right.
The rows/columns are defined elsewhere in the code, but I don't think I need to paste that considering it'll be replaced.
Again, if some other control is better suited, I can change to that.
You will want to use a wrap panel.
<WrapPanel Orientation="Horizontal">
<Image Width="50" Height="50" Source="bla.png" />
<Image Width="50" Height="50" Source="bla.png" />
<Image Width="50" Height="50" Source="bla.png" />
<Image Width="50" Height="50" Source="bla.png" />
</WrapPanel>
Use a WrapPanel to make layout of items fill the width of the window before adding a new row, inside of a ScrollViewer to allow scrolling vertically so the contents don't run out of viewable area.
<ScrollViewer>
<WrapPanel HorizontalAlignment="Center">
<!-- your items go here -->
</WrapPanel>
</ScrollViewer>
If your images are being added dynamically, hopefully you're adding them to a collection that your view can bind to instead of directly adding them to the view in your codebehind... Use an ItemsControl and define your own template for items and container:
<ScrollViewer>
<ItemsControl ItemsSource="{Binding Images}" HorizontalAlignment="Center">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Image Source="{Binding ...}" Height="150" Width="150"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</ScrollViewer>
c# :
// here set number of images you want to parse
int qtyOfImages = 10;
for (int i = 0; i < qtyOfImages; i++) {
Image img = new Image();
BitmapImage bitmap = new BitmapImage();
using (var fs = new FileStream(path, FileMode.Open)) // open the image
{
bitmap.BeginInit();
bitmap.StreamSource = fs;
bitmap.CacheOption = BitmapCacheOption.OnLoad;
bitmap.EndInit();
}
bitmap.Freeze(); // bitmap isn't properly cleaned up and memory leaks can occur if this isn't here
img.Source = bitmap;
img.Margin = new Thickness(10);
img.Stretch = Stretch.Uniform;
//Grid.SetRow(img, i);
//Grid.SetColumn(img, j);
// set width and height so the images stay at the same size
img.Width = 300;
img.Height = 300;
ImageGrid.Children.Add(img);
}
while your xaml would be like:
<Grid ShowGridLines="True" Background="DimGray">
<Grid.ColumnDefinitions>
<ColumnDefinition MinWidth="175" Width="0"/>
<ColumnDefinition MinWidth="755" Width="Auto"/>
</Grid.ColumnDefinitions>
<Label Name="lblWinSize" Content="Width, Height"
HorizontalAlignment="Left" VerticalAlignment="Bottom"/>
<TextBox Name="txtnbox" Style="{StaticResource CustomTxtBox}"
TextWrapping="NoWrap" Width="Auto" Height="25" VerticalAlignment="Top"
Margin="10, 20, 10, 0"/>
<Separator Style="{StaticResource VerticalSeparator}"
HorizontalAlignment="Right" Height="Auto" Width="2" Margin="0,10,0,10"/>
<CheckBox Style="{StaticResource CustomCheckBox}"
HorizontalAlignment="Left" Margin="10,50,0,0" VerticalAlignment="Top"/>
<!--<Grid Name="ImageGrid" Grid.Column="1" Margin="10,10,0,10"
ShowGridLines="True" Background="Gray">
--><!--this is the grid where the images would go--><!--
</Grid>-->
<!-- set size of wrap panel to your window acutal width -->
<WrapPanel Orientation="Horizontal" Name="ImageGrid" Width="{Binding ElementName=Window, Path=ActualWidth}">
</WrapPanel>
</Grid>
dont forget to put Name="Window" at your window for this code to work
Hope that helps

Converting FrameworkElement to Jpeg in UWP

At the past, I can convert and save an usercontrol to an JPEG image with this code:
private string CreateBitmapImage(FrameworkElement usefulData, string name) // Tekli görev kartını masaüstünde oluşturmak için, resim yaratma fonksiyonu.
{
try
{
string fullFileName = string.Empty;
Size size = new Size(642, 416);
usefulData.Measure(size);
usefulData.Arrange(new Rect(size));
var rtb = new RenderTargetBitmap((int)usefulData.ActualWidth, (int)usefulData.ActualHeight, 96, 96, PixelFormats.Pbgra32);
rtb.Render(usefulData);
var encoder = new JpegBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(rtb));
SaveFileDialog dlg = new SaveFileDialog();
dlg.Title = "Görev kartını nereye kaydetmek istersiniz ?";
dlg.FileName = name; // Default file name
dlg.DefaultExt = ".jpg"; // Default file extension
dlg.Filter = "Resim Dosyası (.jpg)|*.jpg"; // Filter files by extension
dlg.OverwritePrompt = true;
var result = dlg.ShowDialog();
if (result == true && dlg.CheckPathExists == true)
{
fullFileName = System.IO.Path.Combine(dlg.FileName);
using (var filestream = new FileStream(fullFileName, FileMode.Create))
{
encoder.Save(filestream);
}
}
return fullFileName;
}
catch
{
MessageBox.Show("Tek görev kartını yaratırken bir hata oluştu.Lütfen yeniden deneyin.", "Hata", MessageBoxButton.OK, MessageBoxImage.Error);
return "";
}
}
Now, I'm converting my WPF project to UWP. However, I cannot find how I convert and save an usercontrol to an Jpeg image in UWP. Can you help me please ?
Thanks.
Update: My UserControl in UWP. As I explained at bottom, I got an exception if I try render the user control:
<UserControl
x:Class="AYOS_IDPrinter_UWP.TaskCard"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:AYOS_IDPrinter_UWP"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="416"
d:DesignWidth="642" HorizontalAlignment="Center" VerticalAlignment="Center" RequestedTheme="Default">
<UserControl.Resources>
<SolidColorBrush x:Key="AuSupportColor" Color="#FFE5C97C"/>
</UserControl.Resources>
<Border x:Name="OutSketch" BorderThickness="2" BorderBrush="{StaticResource AuSupportColor}">
<Grid x:Name="MainGrid" Background="White">
<Grid.RowDefinitions>
<RowDefinition Height="30"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Border x:Name="NeedleArea" BorderThickness="0,0,0,2" Background="{StaticResource AUColor}" BorderBrush="{StaticResource AuSupportColor}">
<TextBlock x:Name="Label" TextWrapping="Wrap" Text="İğne Alanı / Needle Area" Foreground="White" TextAlignment="Center" Margin="0" VerticalAlignment="Center" FontFamily="Noto Sans" FontWeight="Normal"/>
</Border>
<Grid x:Name="Values" HorizontalAlignment="Stretch" Margin="10,10,10,10" VerticalAlignment="Stretch" Grid.Row="2">
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid x:Name="Header" Margin="0">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="128"/>
<ColumnDefinition/>
<ColumnDefinition Width="128"/>
</Grid.ColumnDefinitions>
<Image x:Name="Logo1" Source="Images/AULogo.png" Margin="0" Grid.RowSpan="4" HorizontalAlignment="Center" VerticalAlignment="Center" Width="100" Height="100"/>
<Image x:Name="Logo2" Source="Images/AnkudemLogo.png" Margin="0" Grid.RowSpan="4" Grid.Column="2" HorizontalAlignment="Center" VerticalAlignment="Center" Width="100" Height="100"/>
<TextBlock x:Name="Header_1" Grid.Column="1" Margin="0" TextWrapping="Wrap" Text="AYÖS" FontSize="28" TextAlignment="Center" FontWeight="Bold" Foreground="#FF284985" FontFamily="Noto Sans"/>
<TextBlock x:Name="Header_2" Grid.Column="1" Margin="0" TextWrapping="Wrap" Text="SINAV GÖREV KARTI" FontSize="24" TextAlignment="Center" Grid.Row="1" Foreground="#FF284985" FontFamily="Noto Sans"/>
<TextBlock x:Name="Header_3" Grid.Column="1" Margin="0" TextWrapping="Wrap" Text="EXAMINATION TASK CARD" FontSize="24" TextAlignment="Center" Grid.Row="2" Foreground="#FF284985" FontFamily="Noto Sans"/>
<TextBlock x:Name="DateText" Grid.Column="1" Margin="0" TextWrapping="Wrap" FontSize="22" TextAlignment="Center" Grid.Row="3" Foreground="#FF284985" Text="28 Mayıs 2016 – May 28, 2016" FontFamily="Noto Sans"/>
</Grid>
<Grid x:Name="Data" Grid.Row="1" Margin="0,18,0,-17">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<TextBlock x:Name="NameText" Margin="0,10,0,0" TextWrapping="Wrap" FontSize="32" TextAlignment="Center" Foreground="Red" Text="BERK BABADOĞAN" FontWeight="Bold" FontFamily="Noto Sans"/>
<TextBlock x:Name="TaskText" Margin="0,0,0,10" TextWrapping="Wrap" Text="Salon Başkanı" FontSize="28" TextAlignment="Center" Foreground="Black" Grid.Row="1" FontFamily="Noto Sans"/>
</Grid>
<Grid x:Name="Specs" Margin="10" Grid.Row="2">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<TextBlock x:Name="SpecsH_1" Margin="0,0,5,0" TextWrapping="Wrap" Text="Sınav Yeri / Exam Area: " FontSize="20" Foreground="#FF343434" FontStyle="Italic" FontWeight="Bold" VerticalAlignment="Center" FontFamily="Noto Sans"/>
<TextBlock x:Name="SpecsH_2" Margin="0,0,5,0" TextWrapping="Wrap" Text="Salon Adı / Hall Name:" FontSize="20" Foreground="#FF343434" Grid.Row="1" FontStyle="Italic" FontWeight="Bold" VerticalAlignment="Center" FontFamily="Noto Sans"/>
<TextBlock x:Name="SpecsH_3" Margin="0,0,5,0" TextWrapping="Wrap" Text="Salon No / Hall Number:" FontSize="20" Foreground="#FF343434" Grid.Row="2" FontStyle="Italic" FontWeight="Bold" VerticalAlignment="Center" FontFamily="Noto Sans"/>
<TextBlock x:Name="AreaText" Margin="5,0,0,0" TextWrapping="Wrap" Text="İstanbul" FontSize="20" Foreground="#FF343434" FontStyle="Italic" Grid.Column="1" VerticalAlignment="Center" FontFamily="Noto Sans"/>
<TextBlock x:Name="HallNameText" Margin="5,0,0,0" TextWrapping="Wrap" Text="A Blok 3. Kat Derslik 316" FontSize="20" Foreground="#FF343434" Grid.Row="1" FontStyle="Italic" Grid.Column="1" VerticalAlignment="Center" FontFamily="Noto Sans"/>
<TextBlock x:Name="HallNoText" Margin="5,0,0,0" TextWrapping="Wrap" Text="340111" FontSize="20" Foreground="#FF343434" Grid.Row="2" FontStyle="Italic" Grid.Column="1" VerticalAlignment="Center" FontFamily="Noto Sans"/>
</Grid>
</Grid>
</Grid>
</Border>
It is the code how I create an instance from my user control:
var item = new TaskCard(Name_TextBox.Text.ToUpper() + " " + Surname_TextBox.Text.ToUpper(), Task_TextBox.Text, ExamArea_TextBox.Text, HallName_TextBox.Text,HallNumber_TextBox.Text,DateConverter.Get(Date_Picker.Date.ToString())); // Creating card.
RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap();
await renderTargetBitmap.RenderAsync(item); // Gives error here.
var pixelBuffer = await renderTargetBitmap.GetPixelsAsync();
For converting, UWP app also has RenderTargetBitmap class for capturing a UIElement as an image source. For file saving, you could reference this turtorial. In UWP app we have FileSavePicker which is similar to SaveFileDialog. For example, a completed demo as follows:
RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap();
await renderTargetBitmap.RenderAsync(elementToRender, 642,416);
var pixelBuffer = await renderTargetBitmap.GetPixelsAsync();
var savePicker = new FileSavePicker();
savePicker.DefaultFileExtension = ".png";
savePicker.FileTypeChoices.Add(".png", new List<string> { ".png" });
savePicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
savePicker.SuggestedFileName = "snapshot.png";
// Prompt the user to select a file
var saveFile = await savePicker.PickSaveFileAsync();
// Verify the user selected a file
if (saveFile == null)
return;
// Encode the image to the selected file on disk
using (var fileStream = await saveFile.OpenAsync(FileAccessMode.ReadWrite))
{
var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, fileStream);
encoder.SetPixelData(
BitmapPixelFormat.Bgra8,
BitmapAlphaMode.Ignore,
(uint)renderTargetBitmap.PixelWidth,
(uint)renderTargetBitmap.PixelHeight,
DisplayInformation.GetForCurrentView().LogicalDpi,
DisplayInformation.GetForCurrentView().LogicalDpi,
pixelBuffer.ToArray());
await encoder.FlushAsync();
}
More details you could reference the official XAML render to bitmap sample.
Update:
Also add the XAML code section which use a UserControl for testing. What pass to the RenderAsync method should be the name of the Element you want to render.
<local:MyUserControl
x:Name="elementToRender"
Width="100"
Height="150" />
I did some researches why I can't render a TargetBitmap from code. I found a reason at this link:
You cannot save visual element which in code (offscreen) to image.
So, I foluna a new way to render my code based user control. I created my user control via code like this:
//Initializing task card.
var item = new TaskCard(Name_TextBox.Text.ToUpper() + " " + Surname_TextBox.Text.ToUpper(), Task_TextBox.Text, ExamArea_TextBox.Text, HallName_TextBox.Text, HallNumber_TextBox.Text, DateConverter.Get(Date_Picker.Date.ToString())); // Creating card.
After this, I added a custom popup-like element with this:
<Border x:Name="RingBorder" Margin="0,0,0,0" HorizontalAlignment="Center" VerticalAlignment="Center" BorderBrush="{ThemeResource SystemControlBackgroundBaseHighRevealBorderBrush}" BorderThickness="2,2,2,2" RequestedTheme="Default" Visibility="Collapsed" >
<Grid x:Name="InnerGrid_Ring" Background="{ThemeResource ApplicationPageBackgroundThemeBrush}" RequestedTheme="Default" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="auto"/>
</Grid.RowDefinitions>
<Grid x:Name="WaiterRing_SecondRow" HorizontalAlignment="Stretch" Margin="0,0,0,0" VerticalAlignment="Stretch" Grid.Row="2">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"></ColumnDefinition>
<ColumnDefinition Width="Auto"></ColumnDefinition>
</Grid.ColumnDefinitions>
<TextBlock x:Name="LoadValue_Ring" Text="Lütfen bekleyin..." TextWrapping="Wrap" FontWeight="Normal" Margin="10,0,10,0" TextAlignment="Center" VerticalAlignment="Center" HorizontalAlignment="Stretch" Grid.Column="1" Style="{StaticResource TitleTextBlockStyle}" />
<ProgressRing x:Name="Waiter_Ring" HorizontalAlignment="Center" Margin="10,10,10,10" VerticalAlignment="Center" Foreground="{StaticResource AndroidGreen}" IsActive="True" Width="40" Height="40"/>
</Grid>
<Grid x:Name="CardViewerGrid_Ring" HorizontalAlignment="Center" Height="416" Margin="0,0,0,0" VerticalAlignment="Center" Width="642"/>
</Grid>
</Border>
Lastly, I'm rendering the user control like this:
//Converting UIelement to Rendered Bitmap
CardViewerGrid_Ring.Children.Add(item); // Adding card to canvas.
RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap();
await renderTargetBitmap.RenderAsync(CardViewerGrid_Ring); // Render canvas.
var pixelBuffer = await renderTargetBitmap.GetPixelsAsync();
And, voila :)

WPF how to cut stackpanel content?

I need to print some informations, and I have print preview page which contains:
<Grid Name="pageGrid" Width="Auto" Height="Auto" Margin="70">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid Grid.Column="0" Grid.Row="0" Name="headerGrid" Margin="0,0,0,5" />
<Grid Grid.Column="0" Grid.Row="1" Name="pageSummaryGrid" Margin="0" />
<Grid Grid.Column="0" Grid.Row="2" Name="dataGrid" Margin="0" />
<Grid Grid.Column="0" Grid.Row="3" Name="footerGrid" Margin="0,5,0,0" VerticalAlignment="Bottom" />
</Grid>
The header and footer exists on every page. pageSummaryGrid and dataGrid may be populated. Also I have this code which populate print details:
pageCount = pages.Count;
for (int i = 0; i < pageCount; i++)
{
myPage = new PrintPreviewPage();
header = new PrintPageHeader();
footer = new PrintPageFooter();
CreateHeaderAndFooter(i + 1, pageCount, header, footer);
myPage.SetHeader(header);
myPage.SetTableData(pages[i]);
myPage.SetFooter(footer);
pageList.Add(myPage);
}
Methods:
public void SetTableData(Panel panel)
{
dataGridGrid.Children.Add(panel);
}
public void SetHeader(FrameworkElement header)
{
headerGrid.Children.Add(header);
}
public void SetFooter(FrameworkElement footer)
{
footerGrid.Children.Add(footer);
}
pages is list of StackPanel(represent print details, for example some pictures,list etc.) When some pages[i] is larger than real page height then the footer becomes invisible and print details(list,pictures etc.) is cutted(footer is pushed).
I want that footer is always visible, and if I need to cut just print details. I tried to set MaxHeight, Height, ActualHeight and ClipToBounds properties of StackPanel, but nothing works. Any idea?

Silverlight: Add border around grid

I have a grid that I need to put into a border, doing this via XAML is easy
but how do I do this via C#?
everything that I have found thus far wants to add the border around each cell.
I need it to come out looking the same way XAML does it, please help!
I can not get the XAML to post correctly here:
<Border Grid.Column="1"
Grid.Row="0"
Background="AliceBlue"
BorderBrush="Black"
BorderThickness="4"
x:Name="Side6"
Visibility="Collapsed">
<UIElement.Projection>
<PlaneProjection RotationY="-90" />
</UIElement.Projection>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100"></ColumnDefinition>
<ColumnDefinition Width="100"></ColumnDefinition>
<ColumnDefinition Width="100"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="100"></RowDefinition>
<RowDefinition Height="100"></RowDefinition>
<RowDefinition Height="100"></RowDefinition>
</Grid.RowDefinitions>
<Button Grid.Column="2" Grid.Row="1" Click="RotateRight_Click">
<Button.Content>
<StackPanel>
<TextBlock HorizontalAlignment="Center">Rotate Right</TextBlock>
<TextBlock HorizontalAlignment="Center">To</TextBlock>
<TextBlock HorizontalAlignment="Center">Side 4</TextBlock>
</StackPanel>
</Button.Content>
</Button>
<Button Grid.Column="0" Grid.Row="1" Click="RotateLeft_Click">
<Button.Content>
<StackPanel>
<TextBlock HorizontalAlignment="Center">Rotate Left</TextBlock>
<TextBlock HorizontalAlignment="Center">To</TextBlock>
<TextBlock HorizontalAlignment="Center">Side 2</TextBlock>
</StackPanel>
</Button.Content>
</Button>
<TextBlock HorizontalAlignment="Center"
VerticalAlignment="Center"
Grid.Column="1"
Grid.Row="1"
Text="Side 6">
</TextBlock>
</Grid>
</Border>
Here is the C# code that I'm using, maybe you can see what I am doing wrong?
public static void panelMain(string strPassGridName, System.Windows.Media.Color mcPassColor,
int intRowProperty, int intColumnProperty, Visibility vVisibility,
string[] strButtonTitles, Grid passLayoutRoot, Canvas passCanvas)
{
Grid panelGrid = new Grid();
panelGrid.Name = strPassGridName;
panelGrid.Background = new SolidColorBrush(mcPassColor);
panelGrid.SetValue(Grid.RowProperty, intRowProperty);
panelGrid.SetValue(Grid.ColumnProperty, intColumnProperty);
panelGrid.Visibility = vVisibility;
RowDefinition row1 = new RowDefinition();
row1.Height = new GridLength(100, GridUnitType.Auto);
panelGrid.RowDefinitions.Add(row1);
ColumnDefinition column1 = new ColumnDefinition();
column1.Width = new GridLength(100);
panelGrid.ColumnDefinitions.Add(column1);
passLayoutRoot.Children.Add(panelGrid);
}
I figured it out, I needed to create the border first then add the grid to the border.
One major difference is that I could not reference the border object directly, I needed to "find it"
Border findBorder = passLayoutRoot.FindName("bd" + strPassGridName) as Border;
if (findBorder == null)
{ }
else
{
findBorder.Child = panelGrid;
}
This worked perfectly....
Thanks to all that attempted to help
You can do it as below,
Border gridBorder = new Border();
gridBorder.BorderBrush = new SolidColorBrush(Colors.Black);
gridBorder.BorderThickness = new Thickness(4);
gridBorder.Child = new Grid(); //Your grid here
LayoutRoot.Children.Add(border); // ParentGrid(layout) holding the border

Categories