Click here to Skip to main content
15,900,258 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
I was developing a CAD-like application recently with WPF. The panning and dragging are implemented in a scrollviewer which contains a canvas. All the shapes are drew in the canvas. Now I want to scale the shape in canvas but the point under the cursor has a offset after scaled.I just want the shape can scale around the mouse cursor location and can be written in C# code-only without xaml. Here is my code:
XML
<local:sc x:Name="sc1" Height="263" HorizontalAlignment="Left"  Margin="51,34,0,0" VerticalAlignment="Top" Width="477" HorizontalScrollBarVisibility="Visible" VerticalScrollBarVisibility="Visible" Grid.ColumnSpan="2">
            <Canvas Name="canvas2" Height="337" Width="632" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
                <Canvas.Background>
                    <LinearGradientBrush EndPoint="1,0.5" StartPoint="0,0.5">
                        <GradientStop Color="Black" Offset="0" />
                        <GradientStop Color="White" Offset="1" />
                    </LinearGradientBrush>
                </Canvas.Background>
                <Canvas.RenderTransform>
                    <TransformGroup>
                        <ScaleTransform ScaleY="-1"/>
                        <TranslateTransform Y="{Binding ElementName=canvas2,Path=Height}"/>
                    </TransformGroup>
                </Canvas.RenderTransform>
                <Label Content="duancong" Foreground="White" Canvas.Top="200">
                    <Label.RenderTransform>
                        <ScaleTransform ScaleY="-1"/>
                    </Label.RenderTransform>
                </Label>
            </Canvas>
        </local:sc>

And here is the behind code:
C#
void canvas2_MouseWheel(object sender, MouseWheelEventArgs e)
        {

            if (e.Delta > 0)
                this.scale *= 1.1;
            if (e.Delta < 0)
                this.scale *= 0.9;

            label2.Content = scale;
            scaler();
        }

    void scaler()
        {
            canvas2.Width = sc1.Width * scale;
            canvas2.Height = sc1.Height * scale;
            l1.Scale = scale;
        }
Posted
Updated 14-Jul-12 2:43am
v2

1 solution

I would use the scale transform in both X and Y direction, together with the offset (also in scale transform) and you should be good to go.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900