Created
August 5, 2009 00:07
-
-
Save RandomEtc/162391 to your computer and use it in GitHub Desktop.
simple C# Matrix manipulation for Silverlight transforms
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Windows.Media; | |
namespace Stamen | |
{ | |
/* | |
* Extension methods for Matrix manipulation in Silverlight. | |
* | |
* Note that by default C# passes structs by value (and | |
* extension functions can't pass by reference) so the matrix | |
* won't be modified unless you reassign the result. | |
* | |
* As a side-effect, since these methods return Matrix they | |
* can be chained neatly. | |
* | |
* e.g. to scale by 5x around point (1,2) | |
* | |
* Matrix m = new Matrix(); | |
* m = m.Translate(-1,-2).Scale(5).Translate(1,2); | |
* | |
* e.g. to rotate by pi radians around point (1,2) | |
* | |
* Matrix m = new Matrix(); | |
* m = m.Translate(-1,-2).Rotate(Math.PI).Translate(1,2); | |
* | |
* This is still less verbose than without the functions, | |
* especially for rotations. | |
* | |
*/ | |
public static class MatrixUtils | |
{ | |
public static Matrix Scale(this Matrix m, double sc) | |
{ | |
m.M11 *= sc; | |
m.M22 *= sc; | |
m.OffsetX *= sc; | |
m.OffsetY *= sc; | |
return m; | |
} | |
public static Matrix Translate(this Matrix m, double tx, double ty) | |
{ | |
m.OffsetX += tx; | |
m.OffsetY += ty; | |
return m; | |
} | |
public static Matrix Rotate(this Matrix m, double radians) | |
{ | |
double sin = Math.Sin(radians); | |
double cos = Math.Cos(radians); | |
double m11 = m.M11; | |
double m12 = m.M12; | |
double m21 = m.M21; | |
double m22 = m.M22; | |
double offsetX = m.OffsetX; | |
double offsetY = m.OffsetY; | |
m.M11 = m11 * cos - m12 * sin; | |
m.M12 = m11 * sin + m12 * cos; | |
m.M21 = m21 * cos - m22 * sin; | |
m.M22 = m21 * sin + m22 * cos; | |
m.OffsetX = offsetX * cos - offsetY * sin; | |
m.OffsetY = offsetX * sin + offsetY * cos; | |
return m; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment