react-native支持transform-origin探索

14345次浏览

前言

最近我在项目中用到了react-native,当使用view根据屏幕自适应缩放功能的时候,我用到了自己熟悉的css transform,当想指定中线点缩放的时候,发现react-native不支持transform-origin,可能官方后面会支持吧,目前用下来还是不支持的。 报了如下错误:

enter image description here

react-native使用了阉割版的css,不是所有的css属性都支持的,默认是不支持transform-origin的,项目中真的要用怎么办? 查阅了react-native官方issue transform-origin support 然并没有找到我需要的解决方案。

探索我的项目

我用的是缩放,大体分析如下图:

enter image description here

因此,我trasnform scale之后,我再增加一个transformX 和transformY就可以了

代码如下:

let transformx=haoroomsViewWidth*(1-scaleRadio),transformy=haoroomsViewHeight*(1-scaleRadio)
transform: [{scale(scaleRadio)},{translateX:-transformx},{translateY:-transformy}]

还有一种方法推荐一下,就是在width,和height上面scale,参考代码如下:

width:width*scaleRadio,
height:height:scaleRadio

这种方式简单快捷。

关于旋转

关于transForm旋转rotate的中心点定位就麻烦一些了。当然网上有些用transformMatrix的方式。我这里也提供了一种方式, 思路和我上面一样,

rad = angle * Math.PI / 180
transformX(Math.cos(angle) * haoroomsx - Math.sin(angle) * haoroomsy)
transformY(Math.sin(angle) * haoroomsx + Math.cos(angle) * haoroomsy)
rotate(angle+"deg")

源码如下:仅供参考:

import { responsiveHeight, responsiveWidth, responsiveFontSize } from 'react-native-responsive-dimensions';
import BackgroundTimer from 'react-native-background-timer';

class Haorooms extend component{
constructor(props) {
     super(props)
     this.state = {
          angle: 0
     }
}

componentDidMount() {
    this.progress()
}

progress(){
     intervalId = BackgroundTimer.setInterval(() => {      
         this.setState({angle: this.state.angle +1})   
     }, (1000); // 1000 milliseconds
}



render () {
        const dx = responsiveHeight(9.5);
        const dy = responsiveHeight(9.5);

        const position= {
            transform: [
              {
                translateX: Math.cos((360 - this.state.angle)  * Math.PI / 180) * dx - Math.sin((360 - this.state.angle) * Math.PI / 180) * dy
              },
              {
                translateY:  Math.sin((360 - this.state.angle)  * Math.PI / 180) * dx + Math.cos((360 - this.state.angle) * Math.PI / 180) * dy
              }
            ]
          };

        return(
            <Animated.View style={position}>
                <Text>Text move</Text>
            </Animated.View>

        );
}
}

Tags: reactreact-native

相关文章: