tags:

views:

446

answers:

1

I'm trying to build a WPF DrawingBrush that will draw a hatch pattern using two 1px by 1px rectangles. The resulting pattern would look like the background on classic Macintosh apps.

Here's what I'm working with:

<Canvas SnapsToDevicePixels="True">
 <Canvas.Background>
  <DrawingBrush x:Name="gridBackgroundBrush" 
        Viewport="0,0,10,10"    
        ViewportUnits="Absolute"
        TileMode="Tile">
    <DrawingBrush.Drawing>
         <DrawingGroup>
           <DrawingGroup.Children>                 
    <GeometryDrawing Geometry="M0,0 L10,0 10,10, 0,10Z" Brush="Green"/>     
    <GeometryDrawing Geometry="M10,10 L20,10 20,20, 10,20Z" Brush="Green" />                 
           </DrawingGroup.Children>
         </DrawingGroup>
    </DrawingBrush.Drawing>
  </DrawingBrush>
 </Canvas.Background>
</Canvas>

Everything looks clear and sharp, except that the boxes are way too big. As I adjust the Viewport on the brush, things start to get blurry. It looks like the anti-aliasing is what is killing me; it wants to use 3px to fade from solid green to nothing, which doesn't work when I get to sizes below 3-4px. Is there anything I can do to totally disable the anti-aliasing and do pixel-precise drawing?

A: 

Offset the drawing with 0.5px and you'll get rid of the antialiasing effect. It happens because drawing is done on the edge of the pixel offset, rather than on the actual pixel offset that you have specified. By offset'ing X,Y with half a pixel, you tell the drawing engine to draw on the pixel itself, which eliminates the need of antialiasing.

For some reason this doesn't work with gradientbrushes though.

This behaviour is similar to what you have in Quarts drawing on Mac.

Note: It's not the viewport that you should offset, but the actual shape you're drawing when using the specified brush.

For a more complete answer, please read this article.

Ludvig A Norin