c# - 如何将图像放置在其中心而不是左上角?

标签 c# wpf xaml

我有一张图片(在 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/

相关文章:

c# - 将数据源动态绑定(bind)到 gridview

c# - C# 中的结构给出警告字段永远不会分配给,并且将始终具有其默认值 0

wpf - 如何从 View 模型打开新窗口并将参数传递给MVVM?

xaml - 有人可以向我解释 xamarin 形式中的约束、因素和常数吗?

c# - DRV_QUERYFUNCTIONINSTANCEID在哪里声明?

c# - 传递多个多字符分隔符时,String.Split 方法如何确定分隔符优先级?

.net - ListBox和ListView有什么区别

wpf - 如何在 WPF 中使用 Interaction.EventTrigger 和冒泡自定义事件

c# - TreeView,覆盖双击鼠标事件 WPF

c# - 在 C# 和 XAML 中提取 Key 的内容值