Save didnt work the drawing WinRT - c#

The application is running all good but when i'll go to save is like the margin move the picture and the drawing i do move too. What i'm doing wrong or what i need to do to fix that. I think is a geometry problem.
Xaml Code:
<Page
x:Class="DrawingWithMe.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:DrawingWithMe"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Viewbox>
<Grid x:Name="Grid1" Height="768" Width="1366">
<Canvas x:Name="funnyCanvas" Background="White" Margin="162,10,254,42">
<Rectangle x:Name="Rectangle1" Fill="#FFF4F4F5" Stroke="Black"></Rectangle>
<Image x:Name="image" Source="Assets/Test.gif" Stretch="UniformToFill"/>
</Canvas>
</Grid>
</Viewbox>
<Page.BottomAppBar>
<AppBar x:Name="AppBar" Padding="10,0,10,0">
<Grid>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Left">
<Button Name="Save" Content="Save" VerticalAlignment="Top" Click="Save_Click_1" Grid.Column="1"></Button>
<Button Name="Erase" Content="Erase All" VerticalAlignment="Top" Click="Erase_Click_1" Grid.Column="2"></Button>
<Button x:Name="Copytoclipboard" Content="Copy To ClipBoard" VerticalAlignment="Top" Click="Copytoclipboard_Click_1"></Button>
<Button x:Name="Pastefrom" Content="Paste From ClipBoard" VerticalAlignment="Top" Click="Pastefrom_Click_1"></Button>
<Button x:Name="Recognizeword" Content="Recognize" VerticalAlignment="Top" Click="Recognizeword_Click_1"></Button>
</StackPanel>
</Grid>
</AppBar>
</Page.BottomAppBar>
</Page>
C# Code:
public async void TestingBlit()
{
var backgroundBmp = await BitmapFactory.New(1, 1).FromContent(new Uri(BaseUri, #"///Assets/Test.gif"));
//Image foreground
WriteableBitmap foregroundBmp;
using (InMemoryRandomAccessStream a = new InMemoryRandomAccessStream())
{
await _inkManager.SaveAsync(a);
a.Seek(0);
foregroundBmp = await new WriteableBitmap(1,1).FromStream(a);
}
// Combined
backgroundBmp.Blit(new Rect(0, 0, foregroundBmp.PixelWidth, foregroundBmp.PixelHeight), foregroundBmp,new Rect(0, 0, foregroundBmp.PixelWidth, foregroundBmp.PixelHeight), WriteableBitmapExtensions.BlendMode.ColorKeying);
// Save
Windows.Storage.Pickers.FileSavePicker save = new Windows.Storage.Pickers.FileSavePicker();
save.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Desktop;
save.DefaultFileExtension = ".gif";
save.FileTypeChoices.Add("GIF", new string[] { ".gif" });
StorageFile filesave = await save.PickSaveFileAsync();
Guid encoderId = Windows.Graphics.Imaging.BitmapEncoder.PngEncoderId;
await WinRTXamlToolkit.Imaging.WriteableBitmapSaveExtensions.SaveToFile(backgroundBmp, filesave, encoderId);
//List<InkStroke> tmp = _inkManager.GetStrokes().ToList();
//tmp.RemoveAt(0);
//RenderStroke(tmp.ElementAt(0), Colors.SkyBlue, 10, 1);
SurfaceImageSource surfaceImageSource = new SurfaceImageSource((int)Rectangle1.ActualWidth, (int)Rectangle1.ActualHeight, true);
ImageBrush brush = new ImageBrush();
brush.ImageSource = image.Source;
Rectangle1.Fill = brush;
}
private void RenderStroke(InkStroke stroke, Color color, double width, double opacity = 1)
{
// Each stroke might have more than one segments
var renderingStrokes = stroke.GetRenderingSegments();
//
// Set up the Path to insert the segments
var path = new Windows.UI.Xaml.Shapes.Path();
path.Data = new PathGeometry();
((PathGeometry)path.Data).Figures = new PathFigureCollection();
var pathFigure = new PathFigure();
pathFigure.StartPoint = renderingStrokes.First().Position;
((PathGeometry)path.Data).Figures.Add(pathFigure);
//
// Foreach segment, we add a BezierSegment
foreach (var renderStroke in renderingStrokes)
{
pathFigure.Segments.Add(new BezierSegment()
{
Point1 = renderStroke.BezierControlPoint1,
Point2 = renderStroke.BezierControlPoint2,
Point3 = renderStroke.Position
});
}
// Set the general options (i.e. Width and Color)
path.StrokeThickness = width;
path.Stroke = new SolidColorBrush(color);
// Opacity is used for highlighter
path.Opacity = opacity;
funnyCanvas.Children.Add(path);
}
}
}

You put the content in a Viewbox, which will stretch it. You need to calculate the on-screen coordinates of your rectangle.
Give this a try.
var scalex = MyViewbox.GetScaleChildX();
var scaley = MyViewbox.GetScaleChildY();
SurfaceImageSource surfaceImageSource = new SurfaceImageSource((int)(scalex * Rectangle1.ActualWidth), (int)(scaley * Rectangle1.ActualHeight), true);
public static double GetChildScaleX(this Viewbox viewbox)
{
if (viewbox.Child == null)
throw new InvalidOperationException("Can't tell effective scale of a Viewbox child for a Viewbox with no child.");
var fe = viewbox.Child as FrameworkElement;
if (fe == null)
throw new InvalidOperationException("Can't tell effective scale of a Viewbox child for a Viewbox with a child that is not a FrameworkElement.");
if (fe.ActualWidth == 0)
throw new InvalidOperationException("Can't tell effective scale of a Viewbox child for a Viewbox with a child that is not laid out.");
return viewbox.ActualWidth / fe.ActualWidth;
}
GetChildScaleY is the same, but with Heights (taken from here).
(Make sure you name your Viewbox)
<Viewbox x:Name="MyViewbox">

Related

Why window smaller than actualwidth?

I want capture window but The actual window size seems to be smaller than the figure.
this is code
<Window x:Class="FileRead.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Width="620" Height="340" >
<Grid>
<StackPanel>
<StackPanel Orientation="Horizontal">
<Button x:Name="ReadImageButton" Width="100" Height="30" Margin="10" Click="ReadImage_Click">
LoadImage
</Button>
<Button x:Name="ReadTextButton" Width="100" Height="30" Margin="10" Click="ReadText_Click">
LoadText
</Button>
<Button x:Name="CaptueScreenButton" Width="80" Height="30" Margin="10" Click="CaptueScreenButton_Click">
ScreenCapture
</Button>
<Button x:Name="CaptuerWindowButton" Width="80" Height="30" Margin="10" Click="CaptuerWindowButton_Click">
WindowCapture
</Button>
I couldn't find a problem.
private void CaptuerWindowButton_Click(object sender, RoutedEventArgs e)
{
int width = (int)this.ActualWidth;
int height = (int)this.ActualHeight;
Point point = this.PointToScreen(new Point(0, 0));
CheckLable.Content = string.Format("{0} / {1}", this.Width, this.ActualWidth);
using (Bitmap bmp = new Bitmap(width, height))
{
using (Graphics gr = Graphics.FromImage(bmp))
{
gr.CopyFromScreen( (int)point.X, (int)this.Top, 0, 0, bmp.Size);
}
bmp.Save(ImagePath + "/WindowCapture.png", ImageFormat.Png);
}
}
result image
There is always a difference of about 15 points.:
help me please.
enter image description here
The cause of your problem is that size of a window include the area that draw by OS, which was called "non-client area", usually include frame, border, drop show effect. And your calculation didn't consider that. The right code will like
var clientTopLeft = this.PointToScreen(new System.Windows.Point(0, 0));
// calculate the drop show effect offset.
var shadowOffset = SystemParameters.DropShadow ? clientTopLeft.X - Left -
((WindowStyle == WindowStyle.None && ResizeMode < ResizeMode.CanResize) ? 0 : SystemParameters.BorderWidth) : 0;
// exclude left and right drop shadow area
int width = (int)(Width - 2 * shadowOffset);
// exclude bottom drop shadow area
int height = (int)(Height - shadowOffset);
using (Bitmap bmp = new Bitmap(width, height))
{
using (Graphics gr = Graphics.FromImage(bmp))
{
gr.CopyFromScreen((int)(Left + shadowOffset),
(int)Top, 0, 0, bmp.Size);
}
bmp.Save("WindowCapture.png");
}

Need to draw rectangles on top of image in FlipView, but FlipView loads 3 images at a time

I have a collection of images i want to show with FlipView. On each image I want to draw multiple rectangles, but to do this I need the current dimensions for the image after it has been rendered. I have the coordinates for the rectangles in the same list as my images. I get the dimensions from the images via ImageOpened event, but the problem is the FlipView event loads three images at the same time causing the different rectangles all to be drawn on the first image. Any suggestions?
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
itemList = e.Parameter as List<TableData>;
foreach (var blobImage in itemList)
{
var request = (HttpWebRequest)WebRequest.Create($"http://localhost:58941/api/image?id={blobImage.ImageBlobName}");
request.Method = "GET";
request.ContentType = "application/json";
WebResponse response = await request.GetResponseAsync();
if (response != null)
{
string responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
var myDict = JsonConvert.DeserializeObject<BlobImage>(responseString);
var jj = new MyImage(blobImage.ImageDescription, myDict.Uri, blobImage.GpsLatitude, blobImage.GpsLongitude, blobImage.GpsAltitude, blobImage.DateTime, blobImage.ObjectsDetected);
MyImages.Add(jj);
}
}
MyFlipView.ItemsSource = MyImages;
}
private void Image_ImageOpened(object sender, RoutedEventArgs e)
{
Image currentImageDimensions = sender as Image;
currentWidth = currentImageDimensions.ActualWidth;
currentHeight = currentImageDimensions.ActualHeight;
foreach (var imageRectangle in itemList)
{
for (int i = 0; i < imageRectangle.ObjectsDetected.Count; i++)
{
rectangle = new Rectangle();
var xMinConvert = Convert.ToDouble(imageRectangle.ObjectsDetected[i].xMin);
var yMinConvert = Convert.ToDouble(imageRectangle.ObjectsDetected[i].yMin);
var xMaxConvert = Convert.ToDouble(imageRectangle.ObjectsDetected[i].xMax);
var yMaxConvert = Convert.ToDouble(imageRectangle.ObjectsDetected[i].yMax);
var xMin = xMinConvert * currentWidth;
var yMin = yMinConvert * currentHeight;
var xMax = xMaxConvert * currentWidth;
var yMax = yMaxConvert * currentHeight;
rectangle.Height = yMax - yMin;
rectangle.Width = xMax - xMin;
var left = ((bgWidth - currentWidth) / 2) + xMin;
var top = ((bgHeight - currentHeight) / 2) + yMin;
rectangle.Margin = new Thickness(left, top, 0, 0);
rectangle.Stroke = new SolidColorBrush(Windows.UI.Colors.Red);
rectangle.StrokeThickness = 1;
layoutRoot.Children.Add(rectangle);
}
}
}
Xaml:
<ScrollViewer DoubleTapped="scrollViewer_DoubleTapped" MinZoomFactor="1" ZoomMode="Enabled" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto">
<Grid x:Name="cGrid" Width="{Binding ElementName=gridbg, Path=ActualWidth}" Height="{Binding ElementName=gridbg, Path=ActualHeight}">
<FlipView SelectionChanged="MyFlipView_SelectionChanged" Name="MyFlipView" Width="{Binding ElementName=gridbg, Path=ActualWidth}" Height="{Binding ElementName=gridbg, Path=ActualHeight}">
<FlipView.ItemTemplate>
<DataTemplate x:DataType="local:MyImage">
<Image Source="{Binding Image}" Stretch="Uniform" Height="{Binding ElementName=gridbg, Path=ActualHeight}" ImageOpened="Image_ImageOpened" />
</DataTemplate>
</FlipView.ItemTemplate>
</FlipView>
</Border>
<Canvas x:Name="layoutRoot">
</Canvas>
</Grid>
</ScrollViewer>
but FlipView loads 3 images at a time
FlipView control supports virtualization at default, load three items at one time is as expected. If disabled the virtualization, all the items will be loaded into the FlipView at one time.
You have several ways to resolve your issue. Since you only need the Rectangle drawing when one FlipViewItem selected, you could put the drawing relative code snippet inside SelectionChanged event handle of FlipView. By doing this you may encounter the issue for getting the Image height and width. Actually you should be able to know the image metadata by getting StorageFile object from uri of the image. If you just want to get the Image control for getting the Height and Width, you may use VisualTreeHelper to get the Image control from FlipView.
Or you could consider to force load only one item to the FlipView each time. For this you could use ISupportIncrementalLoading for incremental loading.
I'm not sure what you are drawing these rectangles for, consider to draw these rectangles to the image before you binding the images to the FlipView if possible.

How to use a DX Compositor to blur part of the image?

How can I blur rectangular part of the image (Windows.UI.Xaml.Controls.Image) in UWP app using DX Compositor?
XAML
<Grid>
<Image Name="image" Width="100" Height="200" />
<Grid Name="rectangle" Widht="100" Height="100" />
</Grid>
C#
var blurEffect = new GaussianBlurEffect {
Name = "Blur",
BlurAmount = 2f,
Source = new CompositionEffectSourceParameter("source"),
};
var visual = ElementCompositionPreview.GetElementVisual(rectangle);
var compositor = visual.Compositor;
var effectFactory = compositor.CreateEffectFactory(blurEffect, new[] { "Blur.BlurAmount" });
var effectBrush = effectFactory.CreateBrush();
effectBrush.SetSourceParameter("source", compositor.CreateBackdropBrush());
var blurSprite = compositor.CreateSpriteVisual();
blurSprite.Size = new Vector2((float)rectangle.Width, (float)rectangle.Height);
blurSprite.Brush = effectBrush;
blurSprite.Offset = new Vector3(0, (float)((image.Height - rectangle.Height) / 2), 0);
ElementCompositionPreview.SetElementChildVisual(image, blurSprite);

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.

SetView in Windows Phone map with desired locations, margin and center point

I have added a map in my Windows Phone 8 application. Now I want is to view one desired point with a center point on the map.
XAML:
<Grid x:Name="ContentPanel" Grid.RowSpan="2">
<Grid.RowDefinitions>
<RowDefinition Height="68" />
<RowDefinition Height="1" />
<RowDefinition Height="65" />
<RowDefinition Height="1" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<maps:Map x:Name="map"
Grid.RowSpan="5"
Height="800" />
<Image Source="/Assets/Images/Pin.png" Width="35" Height="55"
VerticalAlignment="Center" HorizontalAlignment="Center"
Grid.RowSpan="5"
Canvas.ZIndex="15"/>
<Button Grid.Row="0" Content="Search" />
<Button Grid.Row="4" Content="Check" />
</Grid>
View Model C#
MapRectLocation zoomLocation = new MapRectLocation();
zoomLocation.CenterPoint = new Location() { lat = CenterLocation.Latitude, lng = CenterLocation.Longitude };
zoomLocation.Locationx = new Location();
zoomLocation.Locationx.Latitude = FirstLocation.Latitude;
zoomLocation.Locationx.Longitude= FirstLocation.Longitude;
// Calculate the other point for boundary
zoomLocation.Locationy= GetEqivalentPoint(CenterLocation, FirstLocation);
public Location GetEqivalentPoint(System.Device.Location.GeoCoordinate CenterLocation, Location location)
{
var dlat = CenterLocation.Latitude - location.lat;
var dlng = CenterLocation.Longitude - location.lng;
Location equiPoint = new Location();
equiPoint.lat = CenterLocation.Latitude + dlat;
equiPoint.lng = CenterLocation.Longitude + dlng;
return equiPoint;
}
XAML.cs Code:
List<GeoCoordinate> zoomBoundaries = new List<GeoCoordinate>();
zoomBoundaries.Add(new GeoCoordinate(mapViewLocation.Locationx.lat, mapViewLocation.Locationx.lng));
zoomBoundaries.Add(new GeoCoordinate(mapViewLocation.Locationy.lat, mapViewLocation.Locationy.lng));
map.SetView(LocationRectangle.CreateBoundingRectangle(zoomBoundaries), new Thickness(0, 150, 0, 300));
The map sets to desired zoom level to display that point but the problem is it does not keep the same centerpoint as earlier. I want to keep the Centerlocation as same and display FirstLocation point on the map. I am also setting margin in Setview as to keep that First location point above the 2 buttons that I have in my XAML code overlaying map.
Please let me know how to rectify this problem?
Try this:
void SetLoc()
{
MyMap.Layers.Clear();
try
{
// ... get the coordinates "myGeoCoordinate"
// Make my current location the center of the Map.
this.MyMap.Center = myGeoCoordinate;
this.MyMap.ZoomLevel = 12;
// Create a small circle to mark the current location.
Ellipse myCircle = new Ellipse();
myCircle.Fill = new SolidColorBrush(Colors.Blue);
myCircle.Height = 20;
myCircle.Width = 20;
myCircle.Opacity = 50;
// Create a MapOverlay to contain the circle.
MapOverlay myLocationOverlay = new MapOverlay();
myLocationOverlay.Content = myCircle;
myLocationOverlay.PositionOrigin = new Point(0.5, 0.5);
myLocationOverlay.GeoCoordinate = myGeoCoordinate;
// Create a MapLayer to contain the MapOverlay.
MapLayer myLocationLayer = new MapLayer();
myLocationLayer.Add(myLocationOverlay);
// Add the MapLayer to the Map.
MyMap.Layers.Add(myLocationLayer);
}
catch
{
}
}

Categories

Resources