我有一张图片(在 Canvas 内)。我需要在文本框中指定图像的坐标,并且我希望图像 center 位于这一点(而不是它的左上角)。我该怎么做?
更新:我不需要将图像放在 Canvas 的中央。我希望图像的位置由 image center 定义。例如,我有一个代码:<Image source"..." canvas.Left="0" canvas.Top="0">
, 而这个点(0,0)表示图像中心在 Canvas 的左上角。
最佳答案
使用附加属性设置位置:
- Canvas.Left
- Canvas.Top
如果要居中,设置
Canvas.SetLeft(image, (canva.Width - Image.Width) / 2);
Canvas.SetTop(image, (canva.Height- Image.Height) / 2);
另请参阅 Align images in WPF canvas in center
更新
Canvas.SetLeft(image, Image.Width / 2);
Canvas.SetTop(image, Image.Height / 2);
例如,您可以从行为中设置它
<Window x:Class="WpfSample.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity" xmlns:wpfSample="clr-namespace:WpfSample"
Title="MainWindow"
Width="800"
Height="800"
Background="Gray">
<Border Width="400"
Height="400"
HorizontalAlignment="Center"
VerticalAlignment="Center"
BorderBrush="Black"
BorderThickness="2">
<Canvas >
<Rectangle Fill="OrangeRed" Width="150" Height="150">
<i:Interaction.Behaviors>
<wpfSample:CenterBehavior/>
</i:Interaction.Behaviors>
</Rectangle>
</Canvas>
</Border>
</Window>
和行为(原始样本)
public class CenterBehavior : Behavior<FrameworkElement>
{
protected override void OnAttached()
{
base.OnAttached();
UpdatePosition();
AssociatedObject.SizeChanged += OnSizeChanged;
}
private void UpdatePosition()
{
Canvas.SetLeft(AssociatedObject, -AssociatedObject.Width/2);
Canvas.SetTop(AssociatedObject, -AssociatedObject.Height/2);
}
private void OnSizeChanged(object sender, SizeChangedEventArgs e)
{
UpdatePosition();
}
}
关于c# - 如何将图像放置在其中心而不是左上角?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20282325/