画布内的中心图像

时间:2012-06-21 21:03:24

标签: c# wpf

我在Image内有Canvas

<Canvas>
    <Image HorizontalAlignment="Center" VerticalAlignment="Center" />
</Canvas>

我希望在Image的中心显示Canvas 始终(即使在可能的大小调整后),但是通过这种方式,图像会在左上角。我该怎么办?

2 个答案:

答案 0 :(得分:8)

这种方法最酷的事情是,如果你改变图像和画布的大小,它会起作用。 转换器代码:

internal sealed class CenterConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        double canvasWidth = System.Convert.ToDouble(values[0]);
        double canvasHeight = System.Convert.ToDouble(values[1]);
        double controlWidth = System.Convert.ToDouble(values[2]);
        double controlHeight = System.Convert.ToDouble(values[3]);
        switch ((string)parameter)
        {
            case "top":
                return (canvasHeight - controlHeight) / 2;
            case "bottom":
                return (canvasHeight + controlHeight) / 2;
            case "left":
                return (canvasWidth - controlWidth) / 2;
            case "right":
                return (canvasWidth + controlWidth) / 2;
            default:
                return 0;
        }
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

XAML,资源中的某个地方:

    <local:CenterConverter x:Key="CenterConverter" />

XAML:

<Canvas x:Name="superCoolCanvas">
    <Image x:Name="superCoolImage" >
        <Canvas.Top>
            <MultiBinding Converter="{StaticResource CenterConverter}" ConverterParameter="top">
                <Binding ElementName="superCoolCanvas" Path="ActualWidth" />
                <Binding ElementName="superCoolCanvas" Path="ActualHeight" />
                <Binding ElementName="superCoolImage" Path="ActualWidth" />
                <Binding ElementName="superCoolImage" Path="ActualHeight" />
            </MultiBinding>
        </Canvas.Top>
        <Canvas.Left>
            <MultiBinding Converter="{StaticResource CenterConverter}" ConverterParameter="left">
                <Binding ElementName="superCoolCanvas" Path="ActualWidth" />
                <Binding ElementName="superCoolCanvas" Path="ActualHeight" />
                <Binding ElementName="superCoolImage" Path="ActualWidth" />
                <Binding ElementName="superCoolImage" Path="ActualHeight" />
            </MultiBinding>
        </Canvas.Left>
    </Image>
</Canvas>

答案 1 :(得分:1)

Canvas旨在使用绝对坐标。您可以使用dwrd提供的解决方案,或者将Canvas和Image放在网格中,然后将Image放在此网格中。