0
0
0
1. 云栖社区>
2. 博客>
3. 正文

## 二维图形的矩阵变换（二）——WPF中的矩阵变换基础

Matrix结构

• Rotate
• RotateAt
• Scale
• ScaleAt
• Skew
• Translate

Matrix matrix = Matrix.Identity;
matrix.Translate(10, 20);
matrix.Rotate(30);

• HasInverse 属性    用于检查该矩阵是否可以反转。
• Invert()    用于获取反转矩阵

var transForm = Matrix.Identity;
transForm.Scale(2, 3);

var point = new Point(1, 1);
var newPoint = transForm.Transform(point);

Console.WriteLine(newPoint);            //

var newPoint = point * transForm;

Matrix scale = Matrix.Identity;
scale.Scale(2, 2);

Matrix transLate = Matrix.Identity;
transLate.Translate(10, 20);

var transForm = scale * transLate;

Matrix transForm2 = Matrix.Identity;
transForm2.Scale(2, 2);
transForm2.Translate(10, 20);

Contract.Assert(transForm == transForm2);

Contract.Assert((transLate * scale) != (scale * transLate));

```    public class GeometryTransForm
{
Matrix _matrix;
public Matrix Matrix
{
get { return _matrix; }
private set { _matrix = value; }
}

/// <summary>
///  获取一个恒等变换
/// </summary>
public static GeometryTransForm Identity
{
get { return new GeometryTransForm(); }
}

/// <summary>
/// 以指定点为中心旋转指定的角度。
/// </summary>
/// <param name="angle">要旋转的角度（单位为度）。</param>
/// <param name="centerX">要围绕其旋转的点的 x 坐标。</param>
/// <param name="centerY">要围绕其旋转的点的 y 坐标。</param>
public GeometryTransForm Rotate(double angle, double centerX = 0, double centerY = 0)
{
_matrix.RotateAt(angle, centerX, centerY);
return this;
}

/// <summary>
/// 围绕指定的点按指定的量缩放
/// </summary>
/// <param name="scaleX">沿 x 轴的缩放量</param>
/// <param name="scaleY">沿 y 轴的缩放量</param>
/// <param name="centerX">缩放操作中心点的 x 坐标</param>
/// <param name="centerY">缩放操作中心点的 y 坐标</param>
public GeometryTransForm Scale(double scaleX, double scaleY, double centerX = 0, double centerY = 0)
{
_matrix.ScaleAt(scaleX, scaleY, centerX, centerY);

return this;
}

/// <summary>
/// 在 x 和 y 维中指定角度的扭曲。
/// </summary>
/// <param name="skewX">用于扭曲此的 x 维角度</param>
/// <param name="skewY">用于扭曲此的 y 维角度</param>
public GeometryTransForm Skew(double skewX, double skewY)
{
_matrix.Skew(skewX, skewY);
return this;
}

/// <summary>
/// 按指定偏移量的平移
/// </summary>
/// <param name="offsetX">沿 x 轴的偏移量</param>
/// <param name="offsetY">沿 y 轴的偏移量</param>
public GeometryTransForm Translate(double offsetX, double offsetY)
{
_matrix.Translate(offsetX, offsetY);
return this;
}

public GeometryTransForm Transfrom(GeometryTransForm transform)
{
return Transfrom(transform.Matrix);
}

public GeometryTransForm Transfrom(Matrix transform)
{
_matrix = _matrix * transform;
return this;
}

/// <summary>
/// 反转变换
/// </summary>
public GeometryTransForm Invert()
{
_matrix.Invert();
return this;
}

public static Point operator *(Point point, GeometryTransForm transform)
{
return point * transform.Matrix;
}

//如果是struct就用不着这个了，每一次 = 都是Clone
public GeometryTransForm Clone()
{
return new GeometryTransForm() { Matrix = this.Matrix };
}
}```
View Code

var transForm = GeometryTransForm.Identity.Scale(2, 2).Translate(10, 20);

UI的矩阵变换

+ 关注