How to use a different coordinate system in WPF? (

2019-03-26 15:39发布

问题:

(Let me give you some context) I am currently designing an application that is supposed to generate a printable A4 page based on some data. Naturally, the device independent pixels of WPF (96 pixels/inch) are not a very natural unit of measurement in the paper world. Something like millimetres would be more appropriate. So I got my calculator out and arrived at a scaling factor of something around 3.779.

It turns out that simply slapping everything that's supposed to go on the page in a ScaleTransform has one nasty side effect: Font sizes are scaled too (naturally). This, however, is not what I intended. I would like 12pt Arial to render like 12pt Arial would render normally.

Is there any other way to change the coordinate system without having to call into extensions or whatever to convert each and every coordinate, length, thickness and so on? - or - Is there any way to map font sizes on-the-fly, being DependencyProperties? Via a custom control that wraps all the paper content, maybe?

回答1:

For the outlined requirements you do not need to do anything special at all, just go ahead and use centimeters as unit of measurement for the WPF elements themselves (i.e. without any transform) - the very nature of WPF device independence allows you to to the following:

<Window x:Class="WpfApplication1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="29.7cm" Width="21cm" FontSize="16pt">
    <Grid>
        <TextBlock Text="Sample" Height="1in" Width="1in" FontSize="12pt" 
            HorizontalAlignment="Center" VerticalAlignment="Center" 
            TextAlignment="Center"/>
    </Grid>
</Window>

That is: you'll get a A4 window specified in 'cm' with a centered square TextBox specified in 'in' and a font specified in 'pt'. All these will scale properly by whatever transform you might apply additionally, if need be (e.g. via a zoom slider for the users view port), respecting their relative sizes regardless of being specified with different units each (i.e. mixed usage at will).

Available units are px (default), in, cm and pt, see for example FrameworkElement.Height for details on their specification.



回答2:

You can also set sizes in points (FontSize="10pt"), in inches (FontSize="10in") or in centimeters (FontSize="10cm"). Of course the real size depends on the DPI setting of Windows and the DPI of your monitor or printer in this case.



回答3:

Just set the font size to 12 / 3.779 = 3.175, no? Assign it to the containing object and it should trickle down to all children.