Carlo
Carlo

Reputation: 25969

Border keep ratio when using scale transform

I might've dreamed it, but I remember somewhere I read that it was possible to use a scale transform to change the size of a border, and that there's a property that will keep the border width to what it was before using the scale (what I might've dreamed is this property, not the scale transform =P).

So, normally, if I have a border with BorderWidth of 1, and I scale it to make it bigger, the BorderWidth will look like it is 10 or something. I want the control itself to be bigger, but the its border to keep the 1 pixel width.

Anyone know how to do this?

Thanks!

Upvotes: 2

Views: 3363

Answers (1)

Rick Sladkey
Rick Sladkey

Reputation: 34250

Sure, just layout-transform scale a zero-width border to any size you like and wrap it in one-pixel width border.

<Grid>
    <Border BorderThickness="1" BorderBrush="Black" HorizontalAlignment="Left" VerticalAlignment="Top">
        <Border Height="100" Width="100">
            <Border.LayoutTransform>
                <ScaleTransform ScaleX="2" ScaleY="2"/>
            </Border.LayoutTransform>
            <TextBlock Text="Some text"/>
        </Border>
    </Border>
</Grid>

Edit:

OK, take two for when the scaling is coming in externally.

Here is a little markup demo with a canvas being transformed and containing a border:

<Grid>
    <Grid.Resources>
        <local:DescalingConverter x:Key="descalingConverter"/>
    </Grid.Resources>
    <Canvas Name="canvas">
        <Canvas.LayoutTransform>
            <ScaleTransform ScaleX="2" ScaleY="2"/>
        </Canvas.LayoutTransform>
        <Border BorderThickness="{Binding ElementName=canvas, Converter={StaticResource descalingConverter}}"
                BorderBrush="Black" Width="100" Height="100">
            <TextBlock Text="Some text"/>
        </Border>
    </Canvas>
</Grid>

and here is the de-scaling converter:

public class DescalingConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var element = value as FrameworkElement;
        var transform = element.LayoutTransform as ScaleTransform;
        if (transform == null) return 1.0;
        return 1.0 / transform.ScaleX;
    }

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

Note that the converter is not robust and is only from demonstration purposes.

Upvotes: 4

Related Questions