【问题标题】:How to animate fontWeight in React Native如何在 React Native 中为 fontWeight 设置动画
【发布时间】:2018-05-07 20:58:33
【问题描述】:

我正在尝试为 Animated.Text 的 fontWeight 设置动画,但无法正常工作。

1.插值

const titleFontWeight = this.positionTitle1.x.interpolate({
  inputRange: [-0.3 * SCREEN_WIDTH, 0],
  outputRange: ['400', '600']
});

render() {
 return (
 <Animated.Text style={{ fontWeight: titleFontWeight }}>
 Title
 </Animated.Text>
 );
}

使用此解决方案,直到整个动画(即 this.positionTitle1 的动画)完成并且我得到一个 警告:道具类型失败:提供给文本 [...] 的道具“fontWeight”的值为“377.333”无效。

2。动画时间

constructor() {
 super();
 this.fontWeight = new Animated.Value(400);
}

animateFontWeight() {
 Animated.timing(this.fontWeight, {
 toValue: 600,
 duration: 500
 }).start();
}

render() {
 return (
  <Animated.Text style={{ fontWeight: `${this.fontWeight._value}` }}>
  Title
  </Animated.Text>
 );
}

对于此解决方案,效果在动画完成之前也不会显示。

有什么解决办法吗?

【问题讨论】:

  • fontWeight 为字符串类型的固定值,不能为浮点数。我认为您只能在这些值之间设置动画。 facebook.github.io/react-native/releases/0.39/docs/…
  • 在这两种情况下,您都返回 int,应该是字符串
  • 好吧,${this.fontWeight._value} 获取值并将其转换为字符串。有没有办法将 fontWeight 设置为固定的字符串值,例如动画期间的“400”、“600”、“800”?

标签: animation react-native text


【解决方案1】:

如上所述,fontWeight 只接受固定的字符串值,例如:'400'、'800' 或 'normal'、'bold'。为了实现您的目标,您可以在动画开始的同时简单地使用 setState。

startAnimation() {
Animated.parallel([
  Animated.timing(this.state.translate, {
    toValue: -27,
    duration: 200,
  }),

  Animated.timing(this.state.color, {
    toValue: 1,
    duration: 300,
  }),
]).start();

this.setState({
  fontWeight: '800'
});};

stopAnimation() {
this.state.translate.setValue(0);
this.state.color.setValue(0);

this.setState({
  fontWeight: '400'
});};

【讨论】:

    【解决方案2】:

    试试这个

    设置文本

    <Animated.Text
            style={{fontWeight: this.fontWeightAnimation.interpolate({
               inputRange: [300, 900],
               outputRange: ['300', '900'],
               easing: value => {
                   const thousandRounded = value * 1000;
                   if (thousandRounded < 300) {
                       return 0;
                   }
    
                   if (thousandRounded < 600) {
                       return 0.5;
                   }
    
                   return 1;
               }
           })}}> Sample Text </Animated.Text>
    

    初始化动画:this.fontWeightAnimation = new Animated.Value(300);

    开始动画:

    Animated.timing(this.fontWeightAnimation, {
                    toValue: 900,
                    duration: 3000
                }).start();
    

    【讨论】:

      猜你喜欢
      • 2017-10-08
      • 2018-10-25
      • 2016-05-04
      • 1970-01-01
      • 1970-01-01
      • 2016-09-23
      • 1970-01-01
      • 1970-01-01
      • 2019-11-28
      相关资源
      最近更新 更多