React Native - 使用变换矩阵将比例变换的原点从中心改为顶部

4

我正在使用以下代码进行转换动画:

transform: [
    // scaleX, scaleY, scale, theres plenty more options you can find online for this.
    {  scaleY: this.state.ViewScale } // this would be the result of the animation code below and is just a number.
]}}>

当前,transform-origin(<- 在react native中实际上不可用)是中心点。对于动画效果,组件从中心缩放,因此看起来像是从中心“扩展”出来。我希望它能够从顶部“扩展”出来(即使将变换原点设为组件的顶部...我想)。

我找到了一种模拟transform-origin CSS的方法:

transformOrigin(matrix, origin) {
    const { x, y, z } = origin;

    const translate = MatrixMath.createIdentityMatrix();
    MatrixMath.reuseTranslate3dCommand(translate, x, y, z);
    MatrixMath.multiplyInto(matrix, translate, matrix);

    const untranslate = MatrixMath.createIdentityMatrix();
    MatrixMath.reuseTranslate3dCommand(untranslate, -x, -y, -z);
    MatrixMath.multiplyInto(matrix, matrix, untranslate);
}

我不确定使用哪些矩阵才能以我想要的方式影响组件。我对变换矩阵有一定的理解,但只限于平移和旋转 - 我不知道如何影响缩放变换的原点。

对于任何想要深入了解的人,感谢您: https://en.wikipedia.org/wiki/Transformation_matrix

1个回答

1
你需要进行三次矩阵变换。1)将视图中心平移到所需的原点,2)应用缩放,3)应用负平移。
const matrix = MatrixMath.createIdentityMatrix();

// First translation, move view center to top left corner
const translate = MatrixMath.createIdentityMatrix();
MatrixMath.reuseTranslate3dCommand(translate, -viewWidth / 2, -viewHeight / 2, 0);
MatrixMath.multiplyInto(matrix, matrix, translate);

// Scale, center point and the top left corner are now overlapping so view will expand or shrink from the top left corner
const scale = MatrixMath.createIdentityMatrix();
MatrixMath.reuseScale3dCommand(scale, this.state.ScaleView, this.state.ScaleView, 1);
MatrixMath.multiplyInto(matrix, matrix, scale);

// Move your view's top left corner to it's original position
const untranslate = MatrixMath.createIdentityMatrix();
MatrixMath.reuseTranslate3dCommand(untranslate, viewWidth / 2, viewHeight / 2, 0);
MatrixMath.multiplyInto(matrix, matrix, untranslate);

// You need to set transform matrix somewhere in your JSX like this:
// <View style={{ transform: [ { matrix } ] }} />
// Or, you can call ref.setNativeProps().

我认为你可以使用矩阵来进行缩放,这样就不需要使用特定的变换函数,如scale/scaleX/scaleY。

你也可以手动计算平移值,并使用transform的translateX/translateY函数来实现相同的效果。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接