【问题标题】:How to place an image by its center, not top-left corner?如何按中心放置图像,而不是左上角?
【发布时间】:2013-11-29 09:28:10
【问题描述】:

我有一张图片(在画布内)。我需要在文本框中指定图像的坐标,并且我希望图像 center 位于该点(而不是其左上角)。我该怎么做?

更新:我不需要将我的图像放在画布的中心。我希望图像的位置由 image 中心定义。例如,我有一个代码:<Image source"..." canvas.Left="0" canvas.Top="0">,这个点(0,0)表示图像中心在画布的左上角。

【问题讨论】:

  • 为什么不将图像的RenderTransform 设置为它的高度/宽度的一半?要么,要么使用Converter。我在我的博客上发布了一个简单的Math Converter,我通常使用它,并且很容易将其扩展为接受多个绑定值的MultiConverter(例如TextBox.TextImage.Height/Width

标签: c# wpf xaml


【解决方案1】:

使用附加属性设置位置:

  • 画布.左
  • 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();
    }
}

【讨论】:

  • 我不需要将图像放在画布的中心。我希望图像的位置由其中心定义。例如,我有一个代码:,这个点(0,0)表示图片中心 位于 canvas 的左上角。
  • 只是为了澄清,您希望您的图像位置相对于画布中心设置?所以如果你设置 Canvas.Left="-12" 这意味着它将是 Canvas.Width/2-12?
【解决方案2】:

只需减去您当前Canvas.Left 值的一半Image.Width 值并减去您当前Canvas.Top 值的一半Image.Height 值。

【讨论】:

    猜你喜欢
    • 2015-04-27
    • 1970-01-01
    • 2016-08-28
    • 1970-01-01
    • 2015-11-22
    • 1970-01-01
    • 2016-07-12
    • 2019-06-04
    • 2017-11-30
    相关资源
    最近更新 更多