How to rotate, translate and scale a control object around an specific point in WPF

jpnavarini picture jpnavarini · May 29, 2012 · Viewed 16k times · Source

I have a custom built control, which is a rectangle with a few details inside it, but it is a rectangle.

I have a center point (X,Y), which I call "Center of Gravity", which "represents" the point. This means that when I set a new position to the object, I want this point to be in the set position. When I rotate the object, I need it to rotate around this point. And when I scale the object, the point must remain in the position set before. Only the size of the object must change.

For example, to have an easy picture of the problem, let's say I have a 10X10 square. I set the center of the gravity in the exact center of the square: (5,5). Then I set the objects position to (100, 100). Then, the square would be in:

(95,95), (105,95), (105,105), (95,105), which means its center would be in the desired position.

In case I scale the square with value 2, the new 4 points positions would be:

(90,90), (110,90), (110,110), (90,110), which means its center would remain in the desired position.

In case I rotate it 45 degrees, it would rotate around its center with positions:

(92.93,92.93),(107.07,92.93),(107.07,107.07),(92.93,107.07)

How is it possible to do this, with its center fully configurable and all this transforms to be transparent for the program in WPF? I would like only to set Scale, Position, Rotation Angle and center to have it drawn properly.

Thank you!

Answer

sharoz picture sharoz · May 29, 2012

You can set the center point of a transform relative to the size of the object. If you want to rotate around the top left corner of the object, the value would be 0, 0. To rotate around a location 10% past the bottom right, you'd use 1.1, 1.1.

The property is called RenderTransformOrigin for RotationTranforms. In Blend, there's a "Transform" group in the properties. If you expand it, the RenderTransform has a set of tabs. The 5th one is the Center Point.

Here's some example XAML:

<TextBlock Text="TextBlock" RenderTransformOrigin="-0.5,-0.5" Background="#FFA1BBF9" Margin="50" Width="100" Height="100">
    <TextBlock.RenderTransform>
        <TransformGroup>
            <ScaleTransform ScaleX="2"/>
            <SkewTransform/>
            <RotateTransform Angle="30"/>
            <TranslateTransform/>
         </TransformGroup>
     </TextBlock.RenderTransform>
</TextBlock>