Search code examples
wpfwpf-controlstextblock

WPF, TextBlock Rotation, Alignment Issues


enter image description hereI would like to rotate the TextBlock based on the text's center point [Horizontal and vertical). I have tried the following code. it is always taking topleft corner of the textblock. How to change it to center of the text itself.

<TextBlock Name="textBlock1"  TextWrapping="Wrap" FontSize="25" Foreground="#FFF63AFF" FontWeight="Bold"> 
TextBlock 
   <TextBlock.RenderTransform>
       <TransformGroup>
           <RotateTransform Angle="45" /> 
       </TransformGroup>   
   </TextBlock.RenderTransform>  
</TextBlock>

Image Description: Textblock is part of canvas and textblock should rotate based on the intersection as shown in the image

I have tried HorizontalAlignment as well as VerticalAlignment too, actually it is taking parent's alignment details.

Do I need to get the actual width and actual height, then based on that details calculate the center point?


Solution

  • You need to use RenderTransformOrigin=".5,.5"

       <Grid>
            <TextBlock Name="textBlock1" RenderTransformOrigin=".5,.5"  HorizontalAlignment="Center" VerticalAlignment="Center" TextWrapping="Wrap" FontSize="25" Foreground="#FFF63AFF" FontWeight="Bold"> 
                TextBlock
                <TextBlock.RenderTransform>
                    <TransformGroup>
                        <RotateTransform Angle="45" />
                    </TransformGroup>
                </TextBlock.RenderTransform>
            </TextBlock>
        </Grid>
    

    Output

    enter image description here