PreviewLeftButtonUp fires too late - c#

I'm making a simple program, where I can drag and drop elements to the grid, but their position depends on the particular column and row. So I tried to use PreviewLeftButtonUp event to find out the position, that is pointed with cursor, but it fires after Drop event and elements are placed in the wrong position.
XAML:
<Window x:Class="Pazzles.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:Pazzles"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Menu x:Name="menu" VerticalAlignment="Top" Grid.Row="0">
<MenuItem Header="Розбити зображення">
<MenuItem Header="Відкрити" Click="OpenImage_Click"/>
<MenuItem Header="Розрізати зображення" Click="CutImage_Click"/>
</MenuItem>
<MenuItem Header="Зібрати пазл" Click ="OpenCatalog_Click">
</MenuItem>
</Menu>
<Grid Grid.Row="1" Name="layout">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<ScrollViewer>
<StackPanel x:Name="stackPanel" Width="150" Grid.Column="0"/>
</ScrollViewer>
<GridSplitter Grid.Column="1" ShowsPreview="False" Width="3" VerticalAlignment="Stretch" HorizontalAlignment="Center"/>
<Grid x:Name="grid" Background="Transparent" Grid.Column="2" ShowGridLines="True" AllowDrop="True" PreviewMouseLeftButtonUp="grid_MouseMove" Drop ="grid_Drop">
</Grid>
</Grid>
</Grid>
</Window>
C# :
private void img_MouseDown(object sender, MouseButtonEventArgs e)
{
Image img = (Image)sender;
DataObject dataObject = new DataObject(typeof(ImageSource), img.Source);
DragDrop.DoDragDrop(img, dataObject, DragDropEffects.All);
}
private void grid_MouseMove(object sender, MouseEventArgs e)
{
double y = e.GetPosition(grid).Y;
double start = 0.0;
row = 0;
foreach (RowDefinition rd in grid.RowDefinitions)
{
start += rd.ActualHeight;
if (y < start)
{
break;
}
row++;
}
double x = e.GetPosition(grid).X;
start = 0.0;
col = 0;
foreach (ColumnDefinition cd in grid.ColumnDefinitions)
{
start += cd.ActualWidth;
if (x < start)
{
break;
}
col++;
}
}
private void grid_Drop(object sender, DragEventArgs e)
{
Image imageControl = new Image { Stretch = Stretch.Fill };
if ((e.Data.GetData(typeof(ImageSource)) != null))
{
ImageSource image = e.Data.GetData(typeof(ImageSource)) as ImageSource;
imageControl = new Image() { Stretch = Stretch.Fill, Source = image };
}
else
{
if ((e.Data.GetData(typeof(Image)) != null))
{
Image image = e.Data.GetData(typeof(Image)) as Image;
imageControl = image;
if (((Grid)sender).Children.Contains(image))
{
((Grid)sender).Children.Remove(image);
}
}
}
Grid.SetColumn(imageControl, col);
Grid.SetRow(imageControl, row);
((Grid)sender).Children.Add(imageControl);
}

you can get the position in the grid_Drop method using Mouse.GetPosition()like this:
private void grid_Drop(object sender, DragEventArgs e)
{
Point location = Mouse.GetPosition(grid);
//do calculation from mouse_move method to get the col and row
Image imageControl = new Image { Stretch = Stretch.Fill};
if ((e.Data.GetData(typeof(ImageSource)) != null))
{
ImageSource image = e.Data.GetData(typeof(ImageSource)) as ImageSource;
imageControl = new Image() { Stretch = Stretch.Fill, Source = image };
}
else
{
if ((e.Data.GetData(typeof(Image)) != null))
{
Image image = e.Data.GetData(typeof(Image)) as Image;
imageControl = image;
if (((Grid)sender).Children.Contains(image))
{
((Grid)sender).Children.Remove(image);
}
}
}
Grid.SetColumn(imageControl, col);
Grid.SetRow(imageControl, row);
((Grid)sender).Children.Add(imageControl);
}

Related

UWP: Adjusting InkCanvas size when writing/drawing

I'm learning how to develop UWP apps and I'm using Microsoft's documentation as tutorials/research.
I want to have an InkCanvas design similar to OneNote where the InkCanvas height and width can expand (as you're writing/drawing and reach the end of the window size) and can shrink (when you erase ink strokes and the extra size can decrease based on the position of the ink strokes until you get back to the original size).
I'm able to increase the InkCanvas width and height, but can't decrease when erasing ink strokes.
Here is a MainPage.xaml code:
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<TextBlock Text="Heading"
FontSize="36"
FontWeight="Bold"
Margin="10"
Grid.Column="0"
Grid.Row="0"/>
<Grid BorderBrush="Red"
BorderThickness="2"
Margin="10"
Grid.Column="0"
Grid.Row="1">
<ScrollViewer HorizontalScrollBarVisibility="Auto"
HorizontalScrollMode="Enabled"
VerticalScrollBarVisibility="Auto"
VerticalScrollMode="Enabled" >
<Grid BorderBrush="Blue"
BorderThickness="2"
Margin="1">
<InkCanvas Name="inkCanvas"/>
</Grid>
</ScrollViewer>
</Grid>
And the MainPage.cs code:
public MainPage()
{
this.InitializeComponent();
nkCanvas.InkPresenter.StrokeInput.StrokeEnded += adjustInkCanvasSize;
}
private async void adjustInkCanvasSize(InkStrokeInput sender, PointerEventArgs args)
{
await Task.Delay(100);
var XBound = inkCanvas.InkPresenter.StrokeContainer.BoundingRect.Bottom;
if (XBound > inkCanvas.ActualHeight - 200)
inkCanvas.Height = XBound + 200;
var YBound = inkCanvas.InkPresenter.StrokeContainer.BoundingRect.Right;
if (YBound > inkCanvas.ActualWidth - 200)
inkCanvas.Width = YBound + 200;
}
The c# code also came from another stackoverflow solution, but not able to figure out the "decrease" part.
Any help would be much appreciated. Thanks
If you want the InkCanvas control to shrink when you erase ink strokes and the extra size can decrease based on the position of the ink strokes until the original size, you need to add the InkPresenter.StrokesErased event to manage the size of the InkCanvas control. For example:
Here is a MainPage.xaml code( To facilitate testing, I added the mouse support):
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<TextBlock Text="Heading"
FontSize="36"
FontWeight="Bold"
Margin="10"
Grid.Column="0"
Grid.Row="0"/>
<Grid BorderBrush="Red"
BorderThickness="2"
Margin="10"
Grid.Column="0"
Grid.Row="1">
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<InkToolbar x:Name="inkToolbar" VerticalAlignment="Top" Margin="10,0,10,0"
TargetInkCanvas="{x:Bind inkCanvas}" Grid.Row="0"/>
<ScrollViewer HorizontalScrollBarVisibility="Auto"
HorizontalScrollMode="Enabled" Grid.Row="1"
VerticalScrollBarVisibility="Auto"
VerticalScrollMode="Enabled" >
<Grid BorderBrush="Blue"
BorderThickness="2"
Margin="1">
<InkCanvas Name="inkCanvas" />
</Grid>
</ScrollViewer>
</Grid>
</Grid>
And the MainPage.cs code:
public sealed partial class MainPage : Page
{
private double originalX; //The original size
private double originalY;
private double maxX=0.0;
private double maxY=0.0;
private bool flag = true;
public MainPage()
{
this.InitializeComponent();
inkCanvas.InkPresenter.InputDeviceTypes = CoreInputDeviceTypes.Mouse | CoreInputDeviceTypes.Touch |
CoreInputDeviceTypes.Pen;
inkCanvas.InkPresenter.StrokeInput.StrokeEnded += adjustInkCanvasSize;
inkCanvas.InkPresenter.StrokesErased += InkPresenter_StrokesErased;
}
private async void InkPresenter_StrokesErased(InkPresenter sender, InkStrokesErasedEventArgs args)
{
await Task.Delay(100);
//The coordinate of the lower right corner of the erased ink stoke
var erasedInkX= args.Strokes.ElementAt(0).BoundingRect.Bottom;
var erasedInkY = args.Strokes.ElementAt(0).BoundingRect.Right;
var XBound = inkCanvas.InkPresenter.StrokeContainer.BoundingRect.Bottom;
if (erasedInkX >=maxX&&XBound < inkCanvas.ActualHeight + 100)
{
if (XBound - 100 > originalX)
inkCanvas.Height = XBound - 100;
else
inkCanvas.Height = originalX; //The size of InkCanvas shrinks to the original size.
maxX = inkCanvas.Height;
}
var YBound = inkCanvas.InkPresenter.StrokeContainer.BoundingRect.Right;
if (erasedInkY>=maxY&&YBound < inkCanvas.ActualWidth + 100)
{
if (YBound - 100 > originalY)
{
inkCanvas.Width = YBound - 100;
}
else
inkCanvas.Width = originalY;
maxY = inkCanvas.Width;
}
}
private async void adjustInkCanvasSize(InkStrokeInput sender, PointerEventArgs args)
{
await Task.Delay(100);
if(flag)
{
flag = false;
originalX = inkCanvas.ActualHeight; //Get the original size
originalY = inkCanvas.ActualWidth;
}
var XBound = inkCanvas.InkPresenter.StrokeContainer.BoundingRect.Bottom;
if (XBound > maxX)
maxX = XBound; //maxX and maxY always hold the maximum size of StrokeContainer
if (XBound > inkCanvas.ActualHeight - 200)
inkCanvas.Height = XBound + 200;
var YBound = inkCanvas.InkPresenter.StrokeContainer.BoundingRect.Right;
if (YBound > maxY)
maxY = YBound;
if (YBound > inkCanvas.ActualWidth - 200)
inkCanvas.Width = YBound + 200;
}
}

2nd Legend canvas not showing in wpf chart

I've been struggling with this for some time now. The problem relates to adding a second legend canvas in a wpf chart. I'm referencing Jack Yu's book Practical WPF Charts and Graphics LineChartWithLegend.xaml file. In the xaml file, I added the new legend canvas named "legendCanvas2". I've changed the code behind to add a second instance of the legend in the AddChart() method. The problem is the second legend does not show inside chartCanvas. I suspect this issue has to do with multiple canvas containers inside chartCanvas but not sure. Any help with alternative ways I can display two legends inside chartCanvas would be appreciated.
XAML
<Window x:Class="LineCharts.LineChartWithLegend"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Line Chart with Legend" Height="400" Width="500">
<Grid Name="grid1" Margin="10">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Name="column1" Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Name="row1" Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<TextBlock Margin="2" x:Name="tbTitle" Grid.Column="1" Grid.Row="0"
RenderTransformOrigin="0.5,0.5" FontSize="14" FontWeight="Bold"
HorizontalAlignment="Stretch" VerticalAlignment="Stretch" TextAlignment="Center"
Text="Title"/>
<TextBlock Margin="2" x:Name="tbXLabel" Grid.Column="1" Grid.Row="2"
RenderTransformOrigin="0.5,0.5" TextAlignment="Center"
Text="X Axis"/>
<TextBlock Margin="2" Name="tbYLabel" Grid.Column="0" Grid.Row="1"
RenderTransformOrigin="0.5,0.5" TextAlignment="Center"
Text="Y Axis">
<TextBlock.LayoutTransform>
<RotateTransform Angle="-90"/>
</TextBlock.LayoutTransform>
</TextBlock>
<Grid Margin="0" x:Name ="chartGrid" Grid.Column="1" Grid.Row="1"
ClipToBounds="True" Background="Transparent" SizeChanged="chartGrid_SizeChanged" />
<Canvas Margin="2" Name="textCanvas" ClipToBounds="True" Grid.Column="1" Grid.Row="1">
<Canvas Name="chartCanvas" ClipToBounds="True">
<Canvas Name="legendCanvas" Background="Transparent" />
<Canvas Name="legendCanvas2" Background="Transparent" />
</Canvas>
</Canvas>
</Grid>
</Window>
Code-Behind
private void AddChart()
{
cs = new ChartStyleGridlines();
lg = new Legend();
lg2 = new Legend();
dc = new DataCollection();
ds = new DataSeries();
cs.ChartCanvas = chartCanvas;
cs.TextCanvas = textCanvas;
cs.Title = "Sine and Cosine Chart";
cs.Xmin = 0;
cs.Xmax = 7;
cs.Ymin = -1.5;
cs.Ymax = 1.5;
cs.YTick = 0.5;
cs.GridlinePattern = ChartStyleGridlines.GridlinePatternEnum.Dot;
cs.GridlineColor = Brushes.Black;
cs.AddChartStyle(tbTitle, tbXLabel, tbYLabel);
// Draw Sine curve:
ds.LineColor = Brushes.Blue;
ds.LineThickness = 1;
ds.SeriesName = "Sine";
for (int i = 0; i < 70; i++)
{
double x = i / 5.0;
double y = Math.Sin(x);
ds.LineSeries.Points.Add(new Point(x, y));
}
dc.DataList.Add(ds);
// Draw cosine curve:
ds = new DataSeries();
ds.LineColor = Brushes.Red;
ds.SeriesName = "Cosine";
ds.LinePattern = DataSeries.LinePatternEnum.DashDot;
ds.LineThickness = 2;
for (int i = 0; i < 70; i++)
{
double x = i / 5.0;
double y = Math.Cos(x);
ds.LineSeries.Points.Add(new Point(x, y));
}
dc.DataList.Add(ds);
// Draw sine^2 curve:
ds = new DataSeries();
ds.LineColor = Brushes.DarkGreen;
ds.SeriesName = "Sine^2";
ds.LinePattern = DataSeries.LinePatternEnum.Dot;
ds.LineThickness = 2;
for (int i = 0; i < 70; i++)
{
double x = i / 5.0;
double y = Math.Sin(x) * Math.Sin(x);
ds.LineSeries.Points.Add(new Point(x, y));
}
dc.DataList.Add(ds);
dc.AddLines(cs);
lg.LegendCanvas = legendCanvas;
lg.IsLegend = true;
lg.IsBorder = true;
lg.LegendPosition = Legend.LegendPositionEnum.NorthWest;
lg.AddLegend(cs.ChartCanvas, dc);
lg2 = new Legend();
lg2.LegendCanvas = legendCanvas2;
lg2.IsLegend = true;
lg2.IsBorder = true;
lg2.LegendPosition = Legend.LegendPositionEnum.NorthEast;
lg2.AddLegend(cs.ChartCanvas, dc);
}
private void chartGrid_SizeChanged(object sender, SizeChangedEventArgs e)
{
textCanvas.Width = chartGrid.ActualWidth;
textCanvas.Height = chartGrid.ActualHeight;
legendCanvas.Children.Clear();
legendCanvas2.Children.Clear();
chartCanvas.Children.RemoveRange(2, chartCanvas.Children.Count - 1); // changed index from 1 to 2
textCanvas.Children.RemoveRange(1, textCanvas.Children.Count - 1);
AddChart();
}

EllipseGeometry Shrink & Fade Without Exceeding Canvas Bounds in C# WPF

How to make animation stay within the canvas at bigger sizes when the user clicks around the edge of the canvas? Currently, if sizes are too big and if user clicks near the edge of the canvas, the ellipse will grow outside of the canvas to cover the buttons. I need the animation to stay within the canvas to make it look like a slice of pizza essentially.
Should look like this:
Size 50 where user clicks near top left of canvas
Currently looks like this:
Size 50 where user clicks near top left of canvas
Xaml:
<Window.Resources>
<Storyboard x:Key="anim">
<DoubleAnimation
Storyboard.TargetName="myCircle"
Storyboard.TargetProperty="RadiusX"
AutoReverse="True"/>
<DoubleAnimation
Storyboard.TargetName="myCircle"
Storyboard.TargetProperty="RadiusY"
AutoReverse="True"/>
<DoubleAnimation
Storyboard.TargetName="path"
Storyboard.TargetProperty="Opacity"
AutoReverse="True"/>
</Storyboard>
</Window.Resources>
<Grid HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
<Grid.RowDefinitions>
<RowDefinition Height="23"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<DockPanel HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Grid.Row="0" Margin="0,0,0,1">
<Menu DockPanel.Dock="Top" Height="23">
<MenuItem Header="Main" RenderTransformOrigin="-1.896,0.643" HorizontalAlignment="Left" Width="39" Height="23">
<MenuItem Header="Exit, Esc" Click="MenuItem_Click_Exit"/>
</MenuItem>
</Menu>
</DockPanel>
<Grid HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Grid.Row="1" Name="pane">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="150"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Grid.Column="0" Name="pane2">
<Grid.RowDefinitions>
<RowDefinition Height="35"/>
<RowDefinition Height="35"/>
<RowDefinition Height="35"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="50"/>
</Grid.ColumnDefinitions>
<Label Content="Size" Grid.Row="0" Grid.Column="0" Height="25" VerticalAlignment="Stretch"/>
<Label Content="Fill Color" Grid.Row="1" Grid.Column="0" Height="25" VerticalAlignment="Stretch"/>
<Label Content="Stroke Thickness" Grid.Row="2" Grid.Column="0" Height="25" VerticalAlignment="Stretch"/>
<Label Content="Stroke Color" Grid.Row="3" Grid.Column="0" VerticalAlignment="Top" Height="25"/>
<Slider x:Name="Slider_Size" Grid.Row="0" Grid.Column="1" Height="20" Width="45"
Minimum="5" Maximum="50"
AutoToolTipPlacement="BottomRight"
TickFrequency="1"
IsSnapToTickEnabled="True"
PreviewMouseUp="Slider_Size_PreviewMouseUp"/>
<Label Name="tempSize" Content="{Binding Path=Value, ElementName=Slider_Size}" Margin="0,25,0,131" Grid.Row="3" Visibility="Hidden"/>
<ComboBox Name="ComboBox_FillColor" Grid.Row="1" Grid.Column="1" Height="20" Width="45" SelectionChanged="ComboBox_FillColor_Selected"/>
<TextBox Name="textBox" Grid.Row="2" Grid.Column="1" Height="20" Width="45" TextChanged="textBox_TextChanged"/>
<ComboBox Name="ComboBox_StrokeColor" Grid.Row="3" Grid.Column="1" VerticalAlignment="Top" Height="20" Width="45" SelectionChanged="ComboBox_StrokeColor_Selected"/>
</Grid>
<Border Name ="border" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" BorderBrush="Black" Grid.Column="1" BorderThickness="2">
<Canvas Name="canvas" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" MouseDown="Canvas_MouseDown">
<Path x:Name="path">
<Path.Data>
<EllipseGeometry x:Name="myCircle"/>
</Path.Data>
</Path>
<Canvas.Background>
<SolidColorBrush Color="White" Opacity="0"/>
</Canvas.Background>
</Canvas>
</Border>
</Grid>
</Grid>
C#:
public partial class MainWindow : Window
{
private int size;
private SolidColorBrush fillColor;
private SolidColorBrush strokeColor;
private List<SolidColorBrush> colors;
private int fillIndex;
private int strokeIndex;
private int strokeThickness = 1;
private int fillColorDefault;
private int strokeColorDefault;
private Point? _start = null;
public MainWindow()
{
InitializeComponent();
addColors();
textBox.Text = strokeThickness.ToString();
parse();
}
private void MenuItem_Click_Exit(object sender, RoutedEventArgs e) { Environment.Exit(1); }
private void Window_KeyUp_ESC(object sender, KeyEventArgs e)
{
if (Key.Escape == e.Key)
MenuItem_Click_Exit(sender, e);
}
private void addColors()
{
colors = typeof(Brushes).GetProperties().Select(p => p.GetValue(null, null) as SolidColorBrush).ToList();
int count = 0;
foreach (SolidColorBrush color in colors)
{
ComboBox_FillColor.Items.Add(new Rectangle() { Height = 12, Width = 17.5, Fill = color });
ComboBox_StrokeColor.Items.Add(new Rectangle() { Height = 12, Width = 17.5, Fill = color });
if (color.Color == Colors.Red)
{
fillIndex = count;
fillColor = colors[fillIndex];
ComboBox_FillColor.SelectedIndex = count;
fillColorDefault = count;
}
if (color.Color == Colors.Black)
{
strokeIndex = count;
strokeColor = colors[strokeIndex];
ComboBox_StrokeColor.SelectedIndex = count;
strokeColorDefault = count;
}
count++;
}
}
private void ComboBox_FillColor_Selected(object sender, RoutedEventArgs e) { fillIndex = ComboBox_FillColor.SelectedIndex; fillColor = colors[fillIndex]; }
private void ComboBox_StrokeColor_Selected(object sender, RoutedEventArgs e) { strokeIndex = ComboBox_StrokeColor.SelectedIndex; strokeColor = colors[strokeIndex]; }
private void Canvas_MouseDown(object sender, MouseButtonEventArgs e)
{
path.Stroke = strokeColor;
path.StrokeThickness = strokeThickness;
path.Fill = fillColor;
path.HorizontalAlignment = HorizontalAlignment.Stretch;
path.VerticalAlignment = VerticalAlignment.Stretch;
path.Stretch = Stretch.None;
path.SetValue(Grid.ColumnProperty, 1);
_start = Mouse.GetPosition((UIElement)sender);
myCircle.Center = (Point)_start;
var sb = FindResource("anim") as Storyboard;
var x = sb.Children.First() as DoubleAnimation;
x.To = 2 * size;
x.Duration = new Duration(TimeSpan.FromSeconds(0.5));
var y = sb.Children.ElementAt(1) as DoubleAnimation;
y.To = 2 * size;
y.Duration = new Duration(TimeSpan.FromSeconds(0.5));
var z = sb.Children.Last() as DoubleAnimation;
z.From = 0.0;
z.To = 1.0;
z.Duration = new Duration(TimeSpan.FromSeconds(0.5));
sb.Begin(path);
}
private void textBox_TextChanged(object sender, TextChangedEventArgs e)
{
//regex where any string of chars besides numbers
Regex pattern = new Regex(#"^([^0-9]*)$", RegexOptions.Compiled);
Match result = pattern.Match(textBox.Text);
if (textBox.Text.ToString() == string.Empty)
return;
else if (result.Success)
{
MessageBox.Show("Invalid character entered. Integer numbers only. Stroke Thickness will be reseted to a default of 1.");
strokeThickness = 1;
textBox.Text = strokeThickness.ToString();
textBox.SelectAll();
}
else
{
int x;
if (int.TryParse(textBox.Text, out x))
strokeThickness = int.Parse(textBox.Text);
}
}
private void Slider_Size_PreviewMouseUp(object sender, MouseButtonEventArgs e)
{
parse();
}
private void parse()
{
int x;
if (int.TryParse(tempSize.Content.ToString(), out x))
size = x;
}
}
}
So you don't need the ellipse to stay within the Canvas, but you want to clip away the parts leaving it, right? Just set ClipToBounds (of Canvas) to true (can be done in Xaml).

Image control and Image resizing when Stretch is set to Uniform

I have this peculiar problem. I am having a user control . I am making an app for Windows 8.1 where I would choose an image from my Picture gallery. The image would open in my app with Stretch is Uniform and Horizontal And vertical alignment to center.
My user control will appear where I tap on the image. Now the problem is , when the image Stretch was none , I was able to magnify the correct region (around my click) , but now when I make it Stretch to Uniform and Set the horizontal and vertical Alignment to Center , I am getting other pixel information in my user control.
I want to know how to fix it.Any how , the images can be of 2*Full HD also or they can be HD or even less.
Secondly , I want to know the boundaries of the image . With boundaries I want to say that , my user control shouldnt go above the boundaries of the image .
How to implement that. If my code is needed , I would paste it , If required.
Have this video for reference . This is what I have to develop ! I have the user control ready and I am getting exact pixels for Stretch=NONE , and no Horizontal And Vertical Alignment set.
This is my code for my app
I believe the issue is with how you use the control, rather than the image. If you avoid doing the bitmap cropping and replacing, it would speed up dramatically and likely work for all stretch types.
I've modified the source to show this - removing the Cropping completely. If you need cropping for other reasons, you should consider using the unsafe keyword (and property setting to allow) in order to dramatically speed up its use.
Also, to avoid the lagging/jumping upward, I added IsHitTestVisible="False" so that your delta wouldn't be interrupted by hovering over your image.
I see you have the 45-degree code already - since it wasn't in your source, I only added an example of 90 degree rotation when you get to the sides - so you can see how to set a RenderTransformOrigin point.
MainPage.xaml:
<Page x:Name="page1"
x:Class="controlMagnifier.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:controlMagnifier"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Grid x:Name="ParentGrid" Background="{ThemeResource ApplicationPageBackgroundThemeBrush}" PointerReleased="ParentGrid_OnPointerReleased" >
<Canvas x:Name="InkPresenter" Height="auto" Width="auto">
<Image Stretch="Uniform" x:Name="image2" >
<Image.Source >
<BitmapImage UriSource="/Assets/wallpaper.jpg" />
</Image.Source>
</Image>
</Canvas>
<local:MagnifierUsercontrol x:Name="MagnifyTip" Visibility="Collapsed" ManipulationMode="All"
IsHitTestVisible="False" Height="227" Width="171"
VerticalContentAlignment="Bottom" HorizontalContentAlignment="Center">
</local:MagnifierUsercontrol>
</Grid>
</Page>
MainPage.xaml.cs:
using System;
using Windows.Foundation;
using Windows.Storage;
using Windows.UI.Input;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;
namespace controlMagnifier
{
public sealed partial class MainPage : Page
{
public const int XAxis = 200;
public const int YAxis = 435;
private readonly RotateTransform myRotateTransform = new RotateTransform {CenterX = 0.5, CenterY = 1};
private readonly ScaleTransform myScaleTransform = new ScaleTransform {ScaleX = 1, ScaleY = 1};
private readonly TransformGroup myTransformGroup = new TransformGroup();
private readonly TranslateTransform myTranslateTransform = new TranslateTransform();
public WriteableBitmap CurrentBitmapObj, CurrentCroppedImage = null;
public Point currentContactPt, GridPoint;
public Thickness margin;
public PointerPoint pt;
public double xValue, yValue;
public MainPage()
{
InitializeComponent();
ParentGrid.Holding += Grid_Holding;
image2.PointerMoved += InkCanvas_PointerMoved;
image2.PointerReleased += ParentGrid_OnPointerReleased;
margin = MagnifyTip.Margin;
image2.CacheMode = new BitmapCache();
myTransformGroup.Children.Add(myScaleTransform);
myTransformGroup.Children.Add(myRotateTransform);
myTransformGroup.Children.Add(myTranslateTransform);
MagnifyTip.RenderTransformOrigin = new Point(0.5, 1);
MagnifyTip.RenderTransform = myTransformGroup;
}
private void Grid_Holding(object sender, HoldingRoutedEventArgs e)
{
try
{
GridPoint = e.GetPosition(image2);
myTranslateTransform.X = xValue - XAxis;
myTranslateTransform.Y = yValue - YAxis;
MagnifyTip.RenderTransform = myTransformGroup;
MagnifyTip.Visibility = Visibility.Visible;
}
catch (Exception)
{
throw;
}
}
private void InkCanvas_PointerMoved(object sender, PointerRoutedEventArgs e)
{
try
{
pt = e.GetCurrentPoint(image2);
currentContactPt = pt.Position;
xValue = currentContactPt.X;
yValue = currentContactPt.Y;
if (xValue > 300)
{
myRotateTransform.Angle = -90;
}
else if (xValue < 100)
{
myRotateTransform.Angle = 90;
}
else
{
myRotateTransform.Angle = 0;
}
MagnifyTip.RenderTransform = myRotateTransform;
myTranslateTransform.X = xValue - XAxis;
myTranslateTransform.Y = yValue - YAxis;
MagnifyTip.RenderTransform = myTransformGroup;
}
catch (Exception)
{
throw;
}
finally
{
e.Handled = true;
}
}
private async void StoreCrrentImage()
{
try
{
var storageFile =
await
StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/wallpaper.jpg",
UriKind.RelativeOrAbsolute));
using (
var fileStream =
await storageFile.OpenAsync(FileAccessMode.Read))
{
var bitmapImage = new BitmapImage();
await bitmapImage.SetSourceAsync(fileStream);
var writeableBitmap =
new WriteableBitmap(bitmapImage.PixelWidth, bitmapImage.PixelHeight);
fileStream.Seek(0);
await writeableBitmap.SetSourceAsync(fileStream);
CurrentBitmapObj = writeableBitmap;
writeableBitmap.Invalidate();
}
}
catch (Exception)
{
// Graphics g=new Graphics();
throw;
}
finally
{
}
}
private void ParentGrid_OnPointerReleased(object sender, PointerRoutedEventArgs e)
{
MagnifyTip.Visibility = Visibility.Collapsed;
}
}
}
MagnifierUsercontrol.xaml:
<UserControl
x:Class="controlMagnifier.MagnifierUsercontrol"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:controlMagnifier"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" Height="227" Width="171">
<Canvas x:Name="controlCanvas" x:FieldModifier="public" Height="Auto" Width="Auto" >
<Grid Height="227" Width="171" HorizontalAlignment="Center" Canvas.Left="0" Canvas.Top="0">
<Border x:FieldModifier="public" x:Name="imgBorder" Width="150" CornerRadius="50,50,50,50" Margin="13,25,13,97">
<Border.Background>
<ImageBrush x:FieldModifier="public" x:Name="image1" />
</Border.Background>
</Border>
<TextBlock x:Name="txtreading" Height="30" Width="80" Margin="0,-145,0,0" FontWeight="Bold" Foreground="Red" FontSize="20" Text="ABC" TextAlignment="Center" />
<!--<Image Height="120" Width="150" Margin="0,-50,0,0" Source="Assets/SmallLogo.scale-100.png" ></Image>-->
<Path x:Name="MagnifyTip" Data="M25.533,0C15.457,0,7.262,8.199,7.262,18.271c0,9.461,13.676,19.698,17.63,32.338 c0.085,0.273,0.34,0.459,0.626,0.457c0.287-0.004,0.538-0.192,0.619-0.467c3.836-12.951,17.666-22.856,17.667-32.33 C43.803,8.199,35.607,0,25.533,0z M25.533,32.131c-7.9,0-14.328-6.429-14.328-14.328c0-7.9,6.428-14.328,14.328-14.328 c7.898,0,14.327,6.428,14.327,14.328C39.86,25.702,33.431,32.131,25.533,32.131z" Fill="#FFF4F4F5" Stretch="Fill" Stroke="Black" UseLayoutRounding="False" Height="227" Width="171" />
</Grid>
</Canvas>
</UserControl>
Let me know if this helps or if there is further toward your specific question.

How to find element in visual tree in wp7?

I need to find element in visual tree. For example I have a grid and I need to set my own text in tbox:WatermarkTextBox when ExpanderView expands.
xaml
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="280"/>
<ColumnDefinition Width="100"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid Grid.Row="0" Grid.Column="0" >
<Border/>
</Grid>
<Grid Grid.Row="0" />
<Grid Grid.Row="0" Grid.Column="2" />
<toolkit:ExpanderView Expanded="setText" Collapsed="hideAppBar">
<Image Height="100" Margin="-53,0,0,0"/>
</toolkit:ExpanderView>
<toolkit:ExpanderView x:Name="expText" IsExpanded="False" Tag="{Binding}" Grid.Row="1" Grid.Column="1" VerticalContentAlignment="Stretch" Grid.ColumnSpan="2" Background="White" Foreground="Black" BorderBrush="White">
<tbox:WatermarkTextBox TextChanged="DisableOrEnable" TextWrapping="Wrap" AcceptsReturn="True" WatermarkText="Введите комментарий" BorderThickness="0" InputScope="Chat" Margin="-51,0,0,0" Padding="0" Background="White" BorderBrush="White"/>
</toolkit:ExpanderView>
...many elements
</Grid>
c#
public string message="my message";
private void setText(object sender, RoutedEventArgs e)
{
setMessage(((sender as ExpanderView).Parent as Grid));
}
Function that recursively searching through visual tree and set value to the element that you need:
public void setMessage(DependencyObject parent)
{
if (parent == null)
{
return;
}
int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < childrenCount; i++)
{
DependencyObject child = VisualTreeHelper.GetChild(parent, i);
var frameworkElement = child as FrameworkElement;
if (frameworkElement != null && frameworkElement is WatermarkTextBox/*Type of element that you need*/)
{
(frameworkElement as WatermarkTextBox).Text = message;/*Value that you need*/
break;
}else
if (frameworkElement != null)
{
int CountInChildren = VisualTreeHelper.GetChildrenCount(frameworkElement);
for (int z = 0; z < CountInChildren; z++)
{
DependencyObject child1 = VisualTreeHelper.GetChild(frameworkElement, z);
setMessage(frameworkElement);
}
}
}
}

Categories

Resources