Matrix主要用于对平面进行平移(Translate),缩放(Scale),旋转(Rotate)以及斜切(Skew)操作。
为简化矩阵变换,Android封装了一系列方法来进行矩阵变换;其中包括:
set系列方法:setTranslate,setScale,setRotate,setSkew;设置,会覆盖之前的参数。
pre系列方法:preTranslate,preScale,preRotate,preSkew;矩阵先乘,如M' = M * T(dx, dy)。
post系列方法:postTranslate,postScale,postRotate,postSkew;矩阵后乘,如M' = T(dx, dy) * M。
通过将变换矩阵与原始矩阵相乘来达到变换的目的,例如:
平移(x'=x+tx;y'=y+ty):
缩放(x'=sx*x;y'=sy*y):
旋转(x'=cosβ*x-sinβ*y;y'=sinβ*x+cosβ*y):
选择需要用到如下的三角函数的公式:
①sin(α+β)=sinαcosβ+cosαsinβ
②cos(α+β)=cosαcosβ-sinαsinβ
公式①可以由单位圆方法或托勒密定理推导出来。
推导过程参见:http://blog.sina.com.cn/s/blog_58260f420100c03j.html
//源码文件:external\skia\legacy\src\core\SkMatrix.cpp
#define SK_Scalar1 (1.0f)
#define kMatrix22Elem SK_Scalar1
typedef float SkScalar;
#define SkScalarMul(a, b) ((float)(a) * (b))
enum {
kMScaleX, kMSkewX, kMTransX,
kMSkewY, kMScaleY, kMTransY,
kMPersp0, kMPersp1, kMPersp2
};
void SkMatrix::reset() {
fMat[kMScaleX] = fMat[kMScaleY] = SK_Scalar1; //其值为1
fMat[kMSkewX] = fMat[kMSkewY] =
fMat[kMTransX] = fMat[kMTransY] =
fMat[kMPersp0] = fMat[kMPersp1] = 0; //其值,全为0
fMat[kMPersp2] = kMatrix22Elem; //其值为1
this->setTypeMask(kIdentity_Mask | kRectStaysRect_Mask);
}
void SkMatrix::setTranslate(SkScalar dx, SkScalar dy) {
if (SkScalarToCompareType(dx) || SkScalarToCompareType(dy)) {
fMat[kMTransX] = dx; //以新值dx覆盖原值,原值无效了
fMat[kMTransY] = dy;
fMat[kMScaleX] = fMat[kMScaleY] = SK_Scalar1; //其值为1
fMat[kMSkewX] = fMat[kMSkewY] =
fMat[kMPersp0] = fMat[kMPersp1] = 0; //其值,全为0
fMat[kMPersp2] = kMatrix22Elem; //其值为1
this->setTypeMask(kTranslate_Mask | kRectStaysRect_Mask);
} else {
this->reset();
}
}
bool SkMatrix::preTranslate(SkScalar dx, SkScalar dy) {
if (this->hasPerspective()) {
SkMatrix m;
m.setTranslate(dx, dy);
return this->preConcat(m); //矩阵的先乘运算
}
if (SkScalarToCompareType(dx) || SkScalarToCompareType(dy)) {
fMat[kMTransX] += SkScalarMul(fMat[kMScaleX], dx) +
SkScalarMul(fMat[kMSkewX], dy); //先乘,需要矩阵运算过
fMat[kMTransY] += SkScalarMul(fMat[kMSkewY], dx) +
SkScalarMul(fMat[kMScaleY], dy);
this->setTypeMask(kUnknown_Mask | kOnlyPerspectiveValid_Mask);
}
return true;
}
bool SkMatrix::postTranslate(SkScalar dx, SkScalar dy) {
if (this->hasPerspective()) {
SkMatrix m;
m.setTranslate(dx, dy);
return this->postConcat(m); //矩阵的后乘运算
}
if (SkScalarToCompareType(dx) || SkScalarToCompareType(dy)) {
fMat[kMTransX] += dx; //后乘,直接加新值dx即可
fMat[kMTransY] += dy;
this->setTypeMask(kUnknown_Mask | kOnlyPerspectiveValid_Mask);
}
return true;
}
bool SkMatrix::preConcat(const SkMatrix& mat) { //矩阵的先乘运算(this在前)
// check for identity first, so we don't do a needless copy of ourselves
// to ourselves inside setConcat()
return mat.isIdentity() || this->setConcat(*this, mat); //矩阵运算
}
bool SkMatrix::postConcat(const SkMatrix& mat) { //矩阵的后乘运算(this在后)
// check for identity first, so we don't do a needless copy of ourselves
// to ourselves inside setConcat()
return mat.isIdentity() || this->setConcat(mat, *this); //矩阵运算
}
Matrix的初始值: