'WPF How do you get the correct canvas top and and left points to draw a circle at specific location on the image?
I have an Image on a Canvas that is on a Boarder.
I want to draw a circle at specific location on the image. I am able to get this to work when I have the Image set to fill, but it is off when the Image is set to Uniform. I tried to make an offset by doing this:
public BitmapImage ImageSource
{
get => (BitmapImage)GetValue( ImageSourceProperty);
set
{
if (_imageSource == value) return;
_imageSource = value;
SetValue( ImageSourceProperty, value);
OnPropertyChanged();
}
}
private Point GetCoordinates(double x, double y)
{
double sourceHeight = ImageSource.PixelHeight;
double sourceWidth = ImageSource.PixelWidth;
double DisplayHeight = Imagebox.Height;
double DisplayWidth = Imagebox.Width;
double Yoffset = Canvas.GetTop(Imagebox);
double Xoffset = Canvas.GetLeft(Imagebox);
double displayY = Yoffset- (DisplayHeight/ sourceHeight) * y;
double displayX = Xoffset- (DisplayWidth /sourceWidth) * x;
Point coordinates = new Point(displayX, displayY);
// Return the general transform for the specified visual object.
GeneralTransform generalTransform1 = ImageBorder.TransformToVisual(Imagebox);
// Retrieve the point value relative to the child.
Point currentPoint = generalTransform1.Transform(coordinates);
return currentPoint;
}
but somehow xoffset and yoffset are alway NanA.
here is my XAML
<Border x:Name="ImageBorder" ClipToBounds="True" Background="White">
<Canvas x:Name="ImageCanvas" >
<Image x:Name="ImageBox" RenderTransformOrigin="0.5,0.5" Width="{Binding Path=ActualWidth, ElementName=ImageCanvas}" Height="{Binding Path=ActualHeight, ElementName=ImageCanvas}" Stretch="Uniform" />
</Canvas>
</Border>
How do you get the correct canvas top and and left points to draw a circle at specific location on the image?
UPDATE:
<Grid x:Name="ImageBorder">
<Image x:Name="ImageBox" Stretch="Uniform" />
<Canvas x:Name="ImageCanvas" />
</Grid>
private Point GetCoordinates(double x, double y)
{
double sourceHeight = ImageSource.PixelHeight;
double sourceWidth = ImageSource.PixelWidth;
double DisplayHeight = ImageBorder.ActualHeight;
double DisplayWidth = ImageBorder.ActualWidth;
double displayY = (DisplayHeight/ sourceHeight) * y;
double displayX = (DisplayWidth /sourceWidth) * x;
Point coordinates = new Point(displayX, displayY);
GeneralTransform generalTransform1 = ImageBorder.TransformToVisual(Imagebox);
// Retrieve the point value relative to the child.
Point currentPoint = generalTransform1.Transform(coordinates);
return currentPoint;}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
