Skip to content

Commit 13b288a

Browse files
niklasb-msachen144
andauthored
Improve text sharpness in DrawingIsland sample (#354)
* Snap pixels on text surface brush and visual. * Disable stretching and alignment in Text's surface brush * Set visual to size of text surface to disable stretch/alignment * Correctly set a text item visual's size to match the surface size. --------- Co-authored-by: achen144 <[email protected]>
1 parent eddebd6 commit 13b288a

File tree

1 file changed

+13
-6
lines changed

1 file changed

+13
-6
lines changed

Samples/Islands/DrawingIsland/DrawingIslandComponents/TextRenderer.cpp

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -126,20 +126,20 @@ namespace winrt::DrawingIslandComponents::implementation
126126
/*maxHeight*/ 0,
127127
/*out*/ textLayout.put()));
128128

129-
// Get the metrics from the text layout, and add the margins to compute the
130-
// width and height of the visual.
129+
// Get the metrics from the text layout.
131130
DWRITE_TEXT_METRICS textMetrics;
132131
winrt::check_hresult(textLayout->GetMetrics(/*out*/ &textMetrics));
133-
const float width = textMetrics.width + (marginLeft + marginRight);
134-
const float height = textMetrics.height + (marginTop + marginBottom);
135132

136-
visual.Size(float2(width, height));
133+
// Compute the size of the drawing surface in pixels.
134+
// This is the text size plus margins, multiplied by the DPI scale and rounded up.
135+
const float pixelWidth = ceilf((textMetrics.width + (marginLeft + marginRight)) * m_dpiScale);
136+
const float pixelHeight = ceilf((textMetrics.height + (marginTop + marginBottom)) * m_dpiScale);
137137

138138
try
139139
{
140140
// Create a composition surface to draw to.
141141
CompositionDrawingSurface drawingSurface = m_compositionGraphicsDevice.CreateDrawingSurface(
142-
winrt::Windows::Foundation::Size(width * m_dpiScale, height * m_dpiScale),
142+
Size(pixelWidth, pixelHeight),
143143
winrt::Microsoft::Graphics::DirectX::DirectXPixelFormat::B8G8R8A8UIntNormalized,
144144
winrt::Microsoft::Graphics::DirectX::DirectXAlphaMode::Premultiplied);
145145
auto drawingSurfaceInterop = drawingSurface.as<ICompositionDrawingSurfaceInterop>();
@@ -186,6 +186,13 @@ namespace winrt::DrawingIslandComponents::implementation
186186
auto surfaceBrush = m_compositor.CreateSurfaceBrush();
187187
surfaceBrush.Surface(drawingSurface);
188188
visual.Brush(surfaceBrush);
189+
190+
// Set the visual size to match the surface size (but in DIPs rather than pixels).
191+
// This ensures there is no scaling.
192+
visual.Size(Size(pixelWidth / m_dpiScale, pixelHeight / m_dpiScale));
193+
194+
// Ensure the visual is snapped to a pixel boundary.
195+
visual.IsPixelSnappingEnabled(true);
189196
}
190197
catch (winrt::hresult_error& e)
191198
{

0 commit comments

Comments
 (0)