Friday, May 8, 2009

WPF Canvas Coordinate System

I noticed that the Canvas class doesn’t use the Cartesian coordinate system for mapping points. For instance, here’s a list of points: 0, 0; 15, 5; 25, 18.  Here’s how these points look when drawn to a Canvas:


The above image is fine if that’s what you want to do with the points, but that isn’t the result I wanted.  I had to add a ScaleTransform to the Canvas for it to look the way I wanted.  This can be done in XAML:

<Canvas Name="MainCanvas" Background="AliceBlue" Width="400" Height="200" >
        <ScaleTransform CenterX="200" CenterY="100" ScaleX="1" ScaleY="-1" />

or programmatically (VB.NET here):

Dim YScale As New ScaleTransform

YScale.ScaleX = 1
YScale.ScaleY = -1
YScale.CenterX = MainCanvas.Width / 2
YScale.CenterY = MainCanvas.Height / 2

MainCanvas.RenderTransform = YScale

You’ll notice the CenterX and CenterY properties are set to the middle of the Canvas.  You can think of this as your pivot point when flipping the Canvas (The CenterX isn’t really needed here since we’re just flipping on the Y axis).The end result is what I was expecting: