TextBlock inside a Viewbox - strange rendering - wpf

This is a question regarding a very simple construction - I have the following XAML:
<Viewbox Height="100" Stretch="Uniform">
<TextBlock FontFamily="Georgia">My Cool Text</TextBlock>
</Viewbox>
This is quite simple to understand. Yet when I start the program I get strange blurry text (there are no bitmap effects anywhere in my project).
(left side - the designer view in VS2010, right side - the running application)
Does anyone have ANY suggestions about why this is happening??

While Jefim has correctly answered his own question, I wanted to explain why you get this behaviour when using this particular set of features. Jefim suggests that this is a bug in WPF, but it's not. The problem arises as a result of asking for WPF to do something impossible. It has to pick a compromise when you've asked for this impossible thing, and the result is what you see above.
The explanation is a bit long for a comment, which is why I'm putting it in a separate answer.
This example uses two mutually contradictory features of WPF. Those features are:
The ability to render visuals consistently at any scale
The ability to render text in the same way GDI32 renders text
You can't use both features at once. GDI32 renders text in a way that cannot be scaled consistently: if a particular piece of text at a certain font size happens to be 200 pixels wide, if you multiply the font size by 3, and render the same text in the same font family at that new font size, in GDI32 it probably won't be 600 pixels - it'll be close, but it will typically not be quite right.
GDI32 messes with the shapes and widths of characters in order to enhance the clarity and sharpness of the text. Specifically, it bends letters out of shape so that their features align better with the pixels on your screen. And where necessary, it will adjust the width of individual characters to be an exact number of pixels wide. Since this letter bending is all based around actual pixels, it bends text in different ways at different font sizes.
While that gives you nice sharp looking text, it looks absolutely horrible if you try to change the scale gradually. If you try to animate the font size of some text rendered in this fashion, the thing will seem to shimmer and shudder, because the adjustments made in the name of clarity end up being slightly different at each font size. Even if you're not animating, it can still produce poor results - if you have a single typeface shown at a number of sizes, it can look quite different at each size; if your application has a zoom feature, the character of the text can seem to change significantly as you zoom in and out. (And so can the layout. If you use Microsoft Word, you may have noticed that you sometimes get odd-looking extra wide spaces between certain words. This is the result of Word fighting with GDI32 - Word attempts to keep the on-screen layout as close as possible to how things will look when printing, which means it sometimes clashes with GDI32's grid fitting.)
So WPF offers a different approach to text rendering: it can render text in a way that is as faithful as possible to the original design of the font. This distorts the text less, and it means that you don't get discontinuities as you scale.
The downside is that the text looks blurry, compared to how text rendered by GDI32 looks. (The distortions made by GDI32 are all aimed at improving clarity.)
So in WPF 4.0, Microsoft added the ability to render text in the way GDI32 would. That's what TextOptions.TextFormattingMode="Display" does.
By turning on that option, you are saying "I don't need consistent scaling, and I'd prefer clarity, so generate the same pixels you would have done in GDI32." If you then go on to apply scaling, having told WPF you didn't need scalability, you get crappy results. WPF carefully generated a bitmap representation of the text exactly to your specifications, and you then told it to render that text at a different scale. And so it looks like what it is: a scaled bitmap of some text that was generated for a different resolution.
You could argue that WPF could do something different here: if you apply a scale transform in GDI32 you'd see different behaviour - you'd see the inconsistency at different scales described earlier. If you really want that effect in WPF you can get it by modifying the font size directly. But WPF doesn't prioritise getting that same effect - its goals are to make it possible to get GDI32-style crisp text when you really need it, and to provide consistent scaling by default.
And what you're running into here is the "consistent scaling". Turning on GDI32-style text rendering doesn't break consistent scaling: applying a scale factor (either directly, via a ScaleTransform or indirectly via a Viewbox) will change the dimensions of the visual by exactly the specified scale factor. If it were to re-generate the text visuals by grid fitting to the newly scaled size, the text would come out at a different width. That would actually cause the Viewbox problems: it applies a scale factor based on the content's natural size, designed to make it fit the available space. But if it re-did the grid fit after scaling, that would actually change the width. Because of the inconsistencies inherent in how GDI32 text rendering works, it might not even be possible for the ViewBox to find a suitable scale - it's possible to come up with a piece of text which, when rendered in a particular font, will never come out at 200 pixels wide. For some font sizes, the rounding inherent in grid fitting might bump the size down to, say, 198, and it might stick at that as you make tiny increments in the font size, until you go past some threshold at which point it might jump to 202 pixels.
For a Viewbox attempting to force the text to fit into exactly 200 pixels, that would be a problem. But Viewbox doesn't work that way - it uses WPF's consistent scaling, downstream of the point at which you chose the font size to which GDI32-style text rendering is working. So Viewbox will always be able to do what it is designed to do, but that is task that's fundamentally incompatible with GDI32-style text rendering.
So in short, WPF renders the text for the font size you requested, and then scales the result.
So you have to pick just one feature - you can't have both because that's simply impossible. Either don't attempt to render text in a context in which an arbitrary scale factor may be applied (e.g. Viewbox) or don't turn on GDI32-style text rendering. Otherwise, you get that weird pixelated text that you've encountered.

Ok, bug found. My Window style has the following setter:
<Setter Property="TextOptions.TextFormattingMode" Value="Display"/>
If I set it back to "Ideal" (which is the default value) then it renders the text inside the viewbox correctly. I would say that this is a bug inside WPF. Basically, if you try this:
<Viewbox Height="100" Stretch="Uniform" TextOptions.TextFormattingMode="Display">
<TextBlock FontFamily="Georgia">My Cool Text</TextBlock>
</Viewbox>
You will get the same result as in my initial picture.

Related

WPF dynamically scale TextBlock Text without filling a container

I have a set of pages that look like this:
I have the content in grids with * Heights and Widths so the grid correctly scales when the entire window resizes. I would like the text to resize with the grid. Basically I would like the user to resize from this:
To this:
(preserving white space)
One way to do this would be to wrap the TextBlock in a ViewBox with margins on the right and bottom (for Grid.Row="3") to account for white space. But because I have several pages with different lengths and line counts I would have to set the margin specifically for each page otherwise the text sizes would differ on each page. Is there a better way to do this??
I don't think there is a better way to do this. There are different ways. But, I think it isn't just a matter of opinion that they would not be better.
Ways I can think of.
Render your text offscreen, rendertargetbitmap that so you've got a picture. Change your textblocks on screen to images and stretch them.
Or
Work out the size your text wants to be. Then do some calculation comes up with a different fontsize which is "better". This is a lot easier to write a description of than do.
In my opinion.
A viewbox is easier to implement. Way less error prone than calculations. Will give at least as good results as rendering to a picture.
I just want to add one more solution to the ones suggested by Andy, which is more of a scientific approach and takes a bit of practice to master.
Suppose you have to find a function F, which maps one or more variables to a desired single value. In your case that would be a function F, which takes aspect ratio of the window as input and outputs an appropriate font size.
How can you find such a function?
Well... you don't need to do any math yourself!
First, you need some data to begin with:
1. Resize the window randomly
2. Calculate aspect ration (X)
3. Pick an appropriate font size that looks good enough (Y)
4. Repeat the measurement 7 to 10 times (sorry data scientists)
5. Enter the data in Excel - one column for X and another one for Y
6. Insert a scatter chart
7. Choose the best trendline for your data, but avoid the polynomial one
8. Display the trendline equation and use the expression in your code
Now I should mention the pros and cons of this regression technique.
Pros:
1. It can solve a wide range of tricky problems:
"I use this 3rd party control, but when the text is too long it overlaps the title bar. How to trim it so it doesn't go beyond the top border?. Deadline is coming!"
2. Even if it doesn't solve the problem perfectly, the results are often acceptable
3. It takes minutes to try out unlike spending a day refreshing your math skills
Cons:
1. The biggest problem is that to keep it simple, you often lower the number of
variables by assuming some of them to be constant. In this post I've assumed that
the font family won't change for example, neither the font weight.
2. If any of the assumptions does not hold the final result could be even worse
This technique is fragile, but powerful. Use it as your last weapon and never leave magic expression like
fontSize = (int)(0.76 + 1.2 * aspectRation) without documenting how it came to be.

Distribute text top-to-bottom instead of left-to-right

I'm working on a view that's implementing a multi-column text layout using CoreText (using CTFramesetter).
CoreText usually fills each frame completely, so when I call CTFramesetterCreateFrame with three rects that make up my columns, I get a layout that's similar to the following image:
So the left column is filled completely, the middle column partially and the right column is empty. But instead, I'd like the text to distribute over the three columns so that they take up the least vertical space possible, like in this image:
How to achieve this with CoreText?
I don't mind going low-level here, even drawing each CTRun by hand is an option if necessary.
One idea I came up with would be to create a large frame with the width of a column and then figure out which CTLine to draw in which column. But this has a few limitations:
It would only work if all columns had the same width.
It does not work with clipping paths.
Unfortunately, I'll need to use clipping paths (as in kCTFrameClippingPathsAttributeName) so this idea is out. I could live the fixed column width limitation, though.
Another idea would be to reduce the height until the last frame overflows but that's a pretty brute-force way that surely wastes resources.
(BTW, due to compability requirements the use of TextKit classes like NSTextStorage isn't possible; the resulting view is intended to be used on Mac and iOS, but it needs to work on iOS < 7)
Since there doesn't seem to be a non-expensive way to solve this, here's how I've done it:
I did go with the "reduce the height until the last frame overflows" approach. To reduce the height, I simply have another clipping path (kCTFrameClippingPathsAttributeName) which is a rectangle that fills the bottom of the view to the required height.
The probably most expensive but simple way would have been to increase the rectangle height until finally the text doesn't fit inside the last frame any more.
Instead I've implemented a binary search for that. For my demo app, I usually find the correct height after 8-10 recursions which still is expensive but at least it's pixel-perfect and doesn't rely on any other information other than "did the last frame overflow".

Scale all screen elements with window vb.net wpf

First time working on a GUI project.. and first time doing work on Windows so apologies in advance if this is a really noob question.
I'm taking baby steps into windows programming starting with vb.net WPF. Working in Visual Studio Express 2012.
I'm trying to work out how I can scale all the elements in a window with the window itself.
So for example, I'd create a window, say 1280x720, and place some images in the window. Say one at the top and one in the corner. (this is a basic media based application)
When I resize that window, I want the entire window to scale with it, so image 1 & 2 will get larger if the window gets larger, however this has to happen proportionally so that if I make the window a lot bigger in one direction one image can't overlap the other. Imagine the window is an image and I'm trying to resize it. (The overlap thing is the closest I've gotten to getting this working in my current attempts).
The layout in produciton will be more complex, comprising of mediaelements (video), images, text etc and all must scale accordingly.
This isn't something the user interacts with and so there are no form elements etc, and so I don't need form fields etc to stay the same size throughout scaling. I just need everything to scale like I'm scaling a picture. If for example I displayed this 1280x720 (16:9) layout on a 1920x1080 screen, maximised it should look identical only larger.
Hoping someone can point me in the right direction with this.
What I've tried so far- the few articles I did find on google relating to this (I may well be searching the wrong things) lead me to put all the elements in a viewbox, this lead to the overlap I mentioned earlier.
Ideas ?
I think you could use ViewBox container. The basic idea is as follows: ViewBox scales its content just as if it was an image scaled. This seems to be the closest result to what you've described in your question. Just put a Grid with absolutely-sized columns and rows into the ViewBox and set its Stretch to be Uniform:
<Viewbox Stretch="Uniform">
<Grid>
<..>Your controls, MediaElements, etc
<Grid>
</Viewbox>
You could also combine it (or entirely replace) with (e.g.) Grid Container : it gives you an ability to specify cell width and size usign star-syntax which is similair to html's percent syntax.
Another way is to use the DockPanel.
All-in-all there are plenty ways to achieve something similair and the way to go largely depends on the nuances of your particulair requirements.
Have a look at This tutorial to see a good overview of WPF containers and how to use them.

WPF font quality

I'm developing a WPF app but I've noticed that at certain font sizes the text doesn't render as nicely as the samples you see in Control Panel -> Fonts. I'm using large Segoe UI fonts (FontSize="36"), and the effect is more noticeable on the upright lines, e.g. a letter "U" might be slightly thicker on one side than the other.
).
The font quality improves at certain font sizes, e.g. FontSize="48" (which I believe is the equivalent of 36pt), but using a limited number of font sizes isn't always practical.
I can improve the font quality by applying the following properties to the TextBlock:-
TextOptions.TextFormattingMode="Display" TextOptions.TextRenderingMode="ClearType"
Given the improvement in quality I'm curious to know why WPF doesn't do this for all text, or is it down to performance? I was thinking of creating a global style to apply this to all controls, or will this cause a problem?
(I tried uploading a screenshot but SO must store images at a low quality, and you couldn't really make out the font problem).
Here is the blog post that the WPF Text team wrote about this feature.
Note for the TextFormattingMode:
Ideal Ideal text metrics are the metrics which have been used to
format text since the introduction of WPF. These metrics result in
glyphs’ shapes maintaining high fidelity with their outlines from the
font file. The glyphs’ final placement is not taken into account when
creating glyph bitmaps or positioning the glyphs relative to each
other.
Display In this new formatting mode, WPF uses GDI
compatible text metrics. This ensures that every glyph has a width of
multiple whole pixels and is positioned on whole pixels. The use of
GDI compatible text metrics also means that glyph sizes and line
breaking is similar to GDI based frameworks. That said, glyph sizes
are not the only input into the line breaking algorithm used by WPF.
Even though we use the same metrics as GDI, our line breaking will not
be exactly the same.
Since these properties are new in .NET 4.0, they kept the original WPF algorithm as default, which is Ideal mode.
For the TextRenderingMode
Auto This mode will use ClearType unless system settings have been
set to specifically disable ClearType on the machine.
Aliased No antialiasing will be used to draw text.
Grayscale Grayscale antialiasing will be used to draw
text.
ClearType ClearType antialising will be used to draw text.
Since Auto is default, you will generally get ClearType rendering.
Now, because these are attached properties, and they inherit, you can just set them at the root Window. No need to create a bunch of Styles.
I have noticed small performance issues when dealing with large amounts of data (upwards of 10,000 items) when ClearType is turned on. Changing TextFormattingMode to Display has no visible performance impact.
This said, in all of my WPF apps I use global styles to improve text rendering, unless the performance impact is large enough to make the UI feel sticky.

WPF: System.Windows.Int32Rect ---> System.Windows.Int32Point?

You know how System.Drawing.Rectangle was replaced by System.Windows.Int32Rect? (As far as non-floating-point shapes are concerned ...)
Is there a similar new object for an integer point or size? If not, I'll just use System.Drawing - but that kinda seems like a minor mix of two platforms that ought not to me mixed.
Anyway, what do you think about this?
The drawing primitives in WPF store all measurements/locations values in doubles - apparently all except Int32Rect, as you pointed out. The reasoning behind this design is due to how WPF is not bound directly from pixel-to-display - it uses "device independent pixels" (DIPs) which can be scaled for whatever device on which it is being rendered. This gives WPF the ability to scale and translate everything that it is displaying very easily.
As for System.Windows.Int32Rect, the only place I see it being used inside the API is for capturing and cropping pixels. This makes sense - when doing a screen capture, you're wanting to get exactly the pixels that are currently displayed on the device.

Resources