0
votes

I'm trying to rotate a view around a certain point not the center (just like transform-origin in css) in React Native. At this time elements can only be rotated around the center. The result should be two views/images containing a point laying upon each other at exactly this point, while one of the views is rotated at the desired point. React Native does not support this layout feature yet, so I have to calculate the offsets and then add them using translateX and translateY.

I've tried several approaches e.g. this but I'm not getting the desired result. Reacts matrix transform is deprecated, so better not use it. I know that it has to be simple trigonometry stuff but I don't have any idea.

I think at first I need to diff the position of the point from the center of the object, then apply a angle, and then? If I use the offset calculated before applying the rotation, i don't get the rotation at the desired point.

Thanks for answers!

here is an image of the problem

2

2 Answers

3
votes

I just made a withAnchorPoint function to make transform working with anchor point easier in react-native. https://github.com/sueLan/react-native-anchor-point.

You can use it like this:

import { withAnchorPoint } from 'react-native-anchor-point';

getTransform = () => {
    let transform = {
        transform: [{ perspective: 400 }, { rotateX: rotateValue }],
    };
    return withAnchorPoint(transform, { x: 0.5, y: 0 }, { width: CARD_WIDTH, height: CARD_HEIGHT });
};

<Animated.View style={[styles.blockBlue, this.getTransform()]} />

I also wrote an article for it. enter image description here

2
votes

So I finally found a way and formular to calculate the offset. The desired point of rotation gets obviously rotated as well, when applying an angle to the object. So what I had to do was getting the position of this point (lets call it pRotated) by using rotationmatrices with the position of both the center (m) of the object and the desired point of rotation (p) like this:

angle = alpha * (Math.PI / 180)
pRotated.x = m.x + (p.x - m.x) * Math.cos(angle) - (p.y - m.y) * Math.sin(angle)
pRotated.y = m.y + (p.x - m.x) * Math.sin(angle) + (p.y - m.y) * Math.cos(angle)

Then it was easy to get the offset using

translateX = pRotated.x - p.x
translateY = pRotated.y - p.y

which then can just be applied to the object, and then its rotated by alpha around point p.

I've attached a scribble for further explanation.