How to shrink font size in Textblock to fit width of content AND maintain font aspect ratio

烂漫一生 提交于 2019-12-10 22:38:55

问题


Here's the deal: I have this line of XAML

<Viewbox Canvas.Left="27" Canvas.Top="479" Width="377" Height="21" Stretch="Fill" 
       StretchDirection="DownOnly" VerticalAlignment="Top" HorizontalAlignment="Left">
  <TextBlock Name="TitleText" TextWrapping="Wrap" TextAlignment="Left" FontSize="14" 
           FontStretch="Normal"  FontStyle="Normal" Foreground="White" Width="377" >some long text here
  </TextBlock>
</Viewbox>

I want the font to scale down to fit the contents height and width. What happens now is that the font scales down, but the Viewbox also scales the content horizontally, making the width of the textbox smaller. Here's an example

Example image

If I set Stretch="Fill" the text will fill the widht, but shrinks only font-size in heigth, making the font look horribly ugly Like this.

Is it possible to shrink the text to fit inside a frame so that it uses the whole width and height of the container?


回答1:


You may not set the StretchDirection property of your viewbox to "DownOnly". This setting leads to the effect that the content only gets stretched vertical.




回答2:


Is this what you want?

<Viewbox Stretch="Uniform">
    <TextBlock Name="TitleText" TextWrapping="Wrap" TextAlignment="Left" FontSize="14" 
       FontStretch="Normal"  FontStyle="Normal" Foreground="White" Width="377">
       some long text here
    </TextBlock>
</Viewbox>



回答3:


Here there is a possible solution using a second ViewBox:

<Viewbox Canvas.Left="27" Canvas.Top="479" Width="377" Height="21" Stretch="Fill" 
        StretchDirection="DownOnly" VerticalAlignment="Top" HorizontalAlignment="Left">
   <Viewbox Stretch="Fill" Width="Auto" Height="Auto">
       <TextBlock Name="TitleText" TextWrapping="Wrap" TextAlignment="Left" FontSize="14" 
            FontStretch="Normal"  FontStyle="Normal" Foreground="White" Width="377" >some long  text here
       </TextBlock>
   </Viewbox>
 </Viewbox>


来源:https://stackoverflow.com/questions/18638968/how-to-shrink-font-size-in-textblock-to-fit-width-of-content-and-maintain-font-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!