javascript - React Native - 使用转换矩阵将缩放转换的原点从中心更改为顶部

标签 javascript css react-native matrix transform

我正在使用下面的代码来制作变换动画:

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);
}

但我不确定使用什么矩阵来按照我想要的方式影响组件。我对变换矩阵有一些了解,但仅适用于平移和旋转 - 我不确定如何影响 scale 变换的原点。

对于任何想要进行挖掘的人,谢谢:https://en.wikipedia.org/wiki/Transformation_matrix

最佳答案

您需要 3 个矩阵变换。 1) 将 View 中心平移到所需的原点,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。

您也可以手动计算翻译值并使用转换的 translateX/translateY 函数来实现相同的效果。

关于javascript - React Native - 使用转换矩阵将缩放转换的原点从中心更改为顶部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52384333/

相关文章:

java - 如何在jsp中预先填充复选框

javascript - 如何阻止 ColdFusion 目标在 Safari 中打开?

css - 媒体查询和转换的问题

javascript - 一次两个对象的 JQuery 淡入淡出循环

javascript - 使用 JQuery + React 使 HTML Bootstrap 元素动态化?

android - ToolbarAndroid 标志边框半径

ios - Expo React iOS 构建在 iPad 中无法正常运行

javascript - 当单击事件发生在除定义的选择器之外的任何选择器上时调用 JavaScript 函数?

javascript - 从 JavaScript/React.js 中的 setInterval 返回

css - 如何在一个元素上渲染多个阴影?