Skip to content

Keep the skew of a 2D matrix transform on Android - #60228

Open
bartlomiejbloniarz wants to merge 1 commit into
mainfrom
bb/android-matrix-skew
Open

bartlomiejbloniarz wants to merge 1 commit into
mainfrom
bb/android-matrix-skew

Conversation

@bartlomiejbloniarz

Copy link
Copy Markdown
Contributor

Summary:

On Android 10 and later, skewX and skewY are drawn through View.setAnimationMatrix (#56724). A matrix transform never takes that path: SkewMatrixHelper.isAffine2DTransformWithSkew and its C++ counterpart from #59461 reject every matrix. The matrix is then decomposed into the View's translation, rotation and scale, which cannot express skew. A skewed matrix therefore renders as a rotated, scaled rectangle, and touches hit that rectangle. iOS draws the same matrix correctly. Reanimated's shared element transitions animate views with a matrix, so on Android a skewed view loses its skew for the whole transition.

A 16-number matrix that is 2D affine, and whose X and Y axes are not perpendicular, now takes the same setAnimationMatrix path as skewX/skewY. Both the Kotlin check and the C++ check used for Fabric's arrays accept it, and buildAffine2DMatrix applies it around the transform origin. Hit testing follows the skewed shape through the existing R.id.skew_animation_matrix tag. These still decompose as before:

  • matrices with perspective, a Z axis or a Z translation;
  • matrices without skew;
  • 9-number matrices;
  • the raw matrix shorthand from Fabric LayoutAnimations, which already has the origin applied.

RNTester's Skew example gets a row with the same transforms written as matrices.

As with skewX today, View.getMatrix() does not include the animation matrix. Native child touch dispatch and accessibility bounds therefore still see the unskewed box.

Changelog:

[ANDROID] [FIXED] - Keep the skew of a 2D matrix transform

Test Plan:

  • ./gradlew :packages:react-native:ReactAndroid:testDebugUnitTest --tests '*SkewMatrixHelperTest*' passes. The new skewed-matrix tests fail without this change.
  • yarn flow-check, ESLint on TransformExample.js, yarn format-check-cpp and yarn format-check-kotlin pass.
  • The C++ check has no host test, because the jni/test tests are not built in open source. RNTester's props reach it as Fabric arrays, so the device runs below exercise it.
  • RNTester debug build, arm64, on API 35 and API 29 emulators, main vs this PR. In Transforms → Skew, the matrix row now matches the list rows above it. A tap inside the parallelogram but outside the square hits the box, and a tap inside the square but outside the parallelogram misses it. The rotation-only matrix renders the same as before.
  • The Playground screen below changes a skewed matrix every frame through React state, crossing zero skew. With this PR its outline matches the [rotate, skewX] list frame by frame. Its rotate+scale and perspective rows render the same as on main.

Android 15 (API 35)

BeforeAfter
before-api35-upload.mp4
after-api35-upload.mp4

Android 10 (API 29)

BeforeAfter
before-api29-upload.mp4
after-api29-upload.mp4
RNTesterPlayground.js: paste into packages/rn-tester/js/examples/Playground/RNTesterPlayground.js and open the Playground tab. Tap a cell in the last row to start or stop the animation.
/**
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow strict-local
 * @format
 */

import type {RNTesterModuleExample} from '../../types/RNTesterTypes';

import * as React from 'react';
import {useEffect, useState} from 'react';
import {Pressable, StyleSheet, Text, View} from 'react-native';

type Op =
  | {rotate: number}
  | {skewX: number}
  | {scaleX: number}
  | {scaleY: number}
  | {perspective: number}
  | {rotateY: number};

const DEG = Math.PI / 180;

function identity(): Array<number> {
  return [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
}

// Same layout and composition order as MatrixMathHelper / processTransform.
function multiply(a: Array<number>, b: Array<number>): Array<number> {
  const out = new Array<number>(16).fill(0);
  for (let i = 0; i < 4; i++) {
    for (let j = 0; j < 4; j++) {
      let sum = 0;
      for (let k = 0; k < 4; k++) {
        sum += b[i * 4 + k] * a[k * 4 + j];
      }
      out[i * 4 + j] = sum;
    }
  }
  return out;
}

function opMatrix(op: Op): Array<number> {
  const m = identity();
  if (op.rotate != null) {
    m[0] = Math.cos(op.rotate * DEG);
    m[1] = Math.sin(op.rotate * DEG);
    m[4] = -Math.sin(op.rotate * DEG);
    m[5] = Math.cos(op.rotate * DEG);
  } else if (op.skewX != null) {
    m[4] = Math.tan(op.skewX * DEG);
  } else if (op.scaleX != null) {
    m[0] = op.scaleX;
  } else if (op.scaleY != null) {
    m[5] = op.scaleY;
  } else if (op.perspective != null) {
    m[11] = -1 / op.perspective;
  } else if (op.rotateY != null) {
    m[0] = Math.cos(op.rotateY * DEG);
    m[2] = -Math.sin(op.rotateY * DEG);
    m[8] = Math.sin(op.rotateY * DEG);
    m[10] = Math.cos(op.rotateY * DEG);
  }
  return m;
}

function toMatrix(ops: Array<Op>): Array<number> {
  return ops.reduce((result, op) => multiply(result, opMatrix(op)), identity());
}

function toTransformList(ops: Array<Op>): $FlowFixMe {
  return ops.map(op => {
    const [key, value] = Object.entries(op)[0];
    const isAngle = key.startsWith('rotate') || key.startsWith('skew');
    return {[key]: isAngle ? `${String(value)}deg` : value};
  });
}

const CASES: Array<{name: string, ops: Array<Op>}> = [
  {name: 'skew', ops: [{rotate: 15}, {skewX: 35}]},
  {name: 'rotate+scale', ops: [{rotate: 15}, {scaleX: 1.3}, {scaleY: 0.7}]},
  {name: 'perspective', ops: [{perspective: 300}, {rotateY: 40}]},
];

function Cell({
  label,
  transform,
  onTap,
}: {
  label: string,
  transform: $FlowFixMe,
  onTap: (label: string) => void,
}): React.Node {
  return (
    <Pressable
      testID={`outside-${label}`}
      onPress={() => onTap(`outside ${label}`)}
      style={styles.cell}>
      <View style={styles.outline} />
      <Pressable
        testID={`box-${label}`}
        onPress={() => onTap(label)}
        style={({pressed}) => [
          styles.box,
          {transform},
          pressed && styles.pressed,
        ]}>
        <Text style={styles.boxText}>{label}</Text>
      </Pressable>
    </Pressable>
  );
}

function useSkewAngle(running: boolean): number {
  const [angle, setAngle] = useState(0);
  useEffect(() => {
    if (!running) {
      return;
    }
    const start = Date.now();
    let frame: number = requestAnimationFrame(function tick() {
      setAngle(40 * Math.sin((Date.now() - start) / 400));
      frame = requestAnimationFrame(tick);
    });
    return () => cancelAnimationFrame(frame);
  }, [running]);
  return angle;
}

function Playground(): React.Node {
  const [tapped, setTapped] = useState('(none)');
  const [running, setRunning] = useState(false);
  const angle = useSkewAngle(running);
  const animatedOps: Array<Op> = [{rotate: 15}, {skewX: angle}];
  return (
    <View style={styles.container}>
      <Text testID="last-tapped" style={styles.tapped}>
        Last tapped: {tapped}
      </Text>
      <View style={styles.row}>
        <Text style={styles.header}>{'{matrix}'}</Text>
        <Text style={styles.header}>transform list</Text>
      </View>
      {CASES.map(({name, ops}) => (
        <View key={name} style={styles.row}>
          <Cell
            label={`matrix ${name}`}
            transform={[{matrix: toMatrix(ops)}]}
            onTap={setTapped}
          />
          <Cell
            label={`list ${name}`}
            transform={toTransformList(ops)}
            onTap={setTapped}
          />
        </View>
      ))}
      <View style={styles.row}>
        <Cell
          label="matrix animated"
          transform={[{matrix: toMatrix(animatedOps)}]}
          onTap={() => setRunning(r => !r)}
        />
        <Cell
          label="list animated"
          transform={toTransformList(animatedOps)}
          onTap={() => setRunning(r => !r)}
        />
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  box: {
    alignItems: 'center',
    backgroundColor: '#3b6fd8',
    height: 70,
    justifyContent: 'center',
    width: 120,
  },
  boxText: {
    color: 'white',
    fontSize: 12,
  },
  cell: {
    alignItems: 'center',
    height: 150,
    justifyContent: 'center',
    width: 180,
  },
  container: {
    padding: 10,
  },
  header: {
    fontWeight: 'bold',
    textAlign: 'center',
    width: 180,
  },
  outline: {
    borderColor: '#e0457b',
    borderStyle: 'dashed',
    borderWidth: 1,
    height: 70,
    position: 'absolute',
    width: 120,
  },
  pressed: {
    backgroundColor: '#1b3f88',
  },
  row: {
    flexDirection: 'row',
    justifyContent: 'space-around',
  },
  tapped: {
    fontSize: 16,
    marginBottom: 8,
  },
});

export default {
  title: 'Playground',
  name: 'playground',
  description: 'Test out new features and ideas.',
  render: (): React.Node => <Playground />,
} as RNTesterModuleExample;

A transform: [{matrix}] that skews went through decomposition into View
properties, which have no skew, so Android drew it as a rotated and scaled
rectangle. A 16-element matrix that is 2D affine and whose axes are not
perpendicular now takes the setAnimationMatrix path that skewX/skewY already
use on Android 10+, including skewed hit testing.

The check accepts such a matrix in both SkewMatrixHelper (Kotlin) and
nativeIsAffine2DTransformWithSkew (C++, used for Fabric's arrays), and
buildAffine2DMatrix composes it around the transform origin. Matrices with
perspective, a Z axis or a Z translation, matrices without skew, 9-element
matrices and the raw matrix shorthand from Fabric LayoutAnimations still
decompose as before.

RNTester's Skew example gets a row of the same transforms written as matrices.
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. label Nov 23, 2026
@facebook-github-tools facebook-github-tools Bot added p: Software Mansion Partner: Software Mansion Partner p: Facebook Partner: Facebook labels Nov 23, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. p: Facebook Partner: Facebook p: Software Mansion Partner: Software Mansion Partner

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant