动画<Circle />的react-native-svg短划线长度

Ilj*_*lja 7 javascript animation svg reactjs react-native

嘿大家我试图达到类似的效果:https://kimmobrunfeldt.github.io/progressbar.js (圈一)

我在使用setNativeProps方法之前能够成功地为一些svg元素设置动画,但是这次使用短划线长度失败了,下面是一个演示当前行为的gif(圆圈在接收到新道具时从完全变为半满):

在此输入图像描述

本质上我试图动画这个变化而不是它只是轻弹,下面是这个矩形进度条的完整源,基本的想法是使用CirclestrokeDasharray为了显示循环进度,它接收currentExpnextExp作为字符值的经验,以便计算它们到达下一个lvl之前剩余的百分比.

组件使用非常标准的元素集,除了样式和样式styled-components库中的少量维度/动画和颜色道具.

注意:项目是从expo.io导入此库,但它本质上是react-native-svg

import React, { Component } from "react";
import PropTypes from "prop-types";
import styled from "styled-components/native";
import { Animated } from "react-native";
import { Svg } from "expo";
import { colour, dimension, animation } from "../Styles";

const { Circle, Defs, LinearGradient, Stop } = Svg;

const SSvg = styled(Svg)`
  transform: rotate(90deg);
  margin-left: ${dimension.ExperienceCircleMarginLeft};
  margin-top: ${dimension.ExperienceCircleMarginTop};
`;

class ExperienceCircle extends Component {
  // -- prop validation ----------------------------------------------------- //
  static propTypes = {
    nextExp: PropTypes.number.isRequired,
    currentExp: PropTypes.number.isRequired
  };

  // -- state --------------------------------------------------------------- //
  state = {
    percentage: new Animated.Value(0)
  };

  // -- methods ------------------------------------------------------------- //
  componentDidMount() {
    this.state.percentage.addListener(percentage => {
      const circumference = dimension.ExperienceCircleRadius * 2 * Math.PI;
      const dashLength = percentage.value * circumference;
      this.circle.setNativeProps({
        strokeDasharray: [dashLength, circumference]
      });
    });
    this._onAnimateExp(this.props.nextExp, this.props.currentExp);
  }

  componentWillReceiveProps({ nextExp, currentExp }) {
    this._onAnimateExp(currentExp, nextExp);
  }

  _onAnimateExp = (currentExp, nextExp) => {
    const percentage = currentExp / nextExp;
    Animated.timing(this.state.percentage, {
      toValue: percentage,
      duration: animation.duration.long,
      easing: animation.easeOut
    }).start();
  };

  // -- render -------------------------------------------------------------- //
  render() {
    const { ...props } = this.props;
    // const circumference = dimension.ExperienceCircleRadius * 2 * Math.PI;
    // const dashLength = this.state.percentage * circumference;
    return (
      <SSvg
        width={dimension.ExperienceCircleWidthHeight}
        height={dimension.ExperienceCircleWidthHeight}
        {...props}
      >
        <Defs>
          <LinearGradient
            id="ExperienceCircle-gradient"
            x1="0"
            y1="0"
            x2="0"
            y2={dimension.ExperienceCircleWidthHeight * 2}
          >
            <Stop
              offset="0"
              stopColor={`rgb(${colour.lightGreen})`}
              stopOpacity="1"
            />
            <Stop
              offset="0.5"
              stopColor={`rgb(${colour.green})`}
              stopOpacity="1"
            />
          </LinearGradient>
        </Defs>
        <Circle
          ref={x => (this.circle = x)}
          cx={dimension.ExperienceCircleWidthHeight / 2}
          cy={dimension.ExperienceCircleWidthHeight / 2}
          r={dimension.ExperienceCircleRadius}
          stroke="url(#ExperienceCircle-gradient)"
          strokeWidth={dimension.ExperienceCircleThickness}
          fill="transparent"
          strokeDasharray={[0, 0]}
          strokeLinecap="round"
        />
      </SSvg>
    );
  }
}

export default ExperienceCircle;
Run Code Online (Sandbox Code Playgroud)

更新:扩展讨论和更多示例(针对不同元素的类似方法)可通过发布到react-native-svgrepo的问题获得:https://github.com/react-native-community/react-native-svg/issues/451

Moj*_*ehr 13

当你知道SVG输入如何工作时,它实际上非常简单,反应本机SVG(或SVG输入,通常是它不能与角度一起工作)的问题之一,所以当你想要工作时圆形你需要将角度转换为它所需的输入,这可以通过简单地编写一个函数来完成(你必须记住或完全理解转换是如何工作的,这是标准):

结果

function polarToCartesian(centerX, centerY, radius, angleInDegrees) {
        var angleInRadians = (angleInDegrees-90) * Math.PI / 180.0;

        return {
            x: centerX + (radius * Math.cos(angleInRadians)),
            y: centerY + (radius * Math.sin(angleInRadians))
        };
    }
Run Code Online (Sandbox Code Playgroud)

然后你添加另一个函数,它可以以正确的格式给你道具:

function describeArc(x, y, radius, startAngle, endAngle){

        var start = polarToCartesian(x, y, radius, endAngle);
        var end = polarToCartesian(x, y, radius, startAngle);

        var largeArcFlag = endAngle - startAngle <= 180 ? "0" : "1";

        var d = [
            "M", start.x, start.y,
            "A", radius, radius, 0, largeArcFlag, 0, end.x, end.y
        ].join(" ");

        return d;
    }
Run Code Online (Sandbox Code Playgroud)

现在很棒,你有一个函数(describeArc),它为你提供描述你的路径所需的完美参数(一个圆弧):所以你可以定义PATH为:

<AnimatedPath d={_d} stroke="red" strokeWidth={5} fill="none"/>
Run Code Online (Sandbox Code Playgroud)

例如,如果您需要半径R为45度到90度的圆弧,只需定义_d为:

_d = describeArc(R, R, R, 45, 90);
Run Code Online (Sandbox Code Playgroud)

既然我们知道SVG PATH如何工作的一切,我们可以实现反应原生动画,并定义动画状态,例如progress:

import React, {Component} from 'react';
import {View, Animated, Easing} from 'react-native';
import Svg, {Circle, Path} from 'react-native-svg';

AnimatedPath = Animated.createAnimatedComponent(Path);

class App extends Component {
    constructor() {
        super();
        this.state = {
            progress: new Animated.Value(0),
        }
    }
componentDidMount(){
        Animated.timing(this.state.progress,{
            toValue:1,
            duration:1000,

        }).start()
}



    render() {
        function polarToCartesian(centerX, centerY, radius, angleInDegrees) {
            var angleInRadians = (angleInDegrees-90) * Math.PI / 180.0;

            return {
                x: centerX + (radius * Math.cos(angleInRadians)),
                y: centerY + (radius * Math.sin(angleInRadians))
            };
        }

        function describeArc(x, y, radius, startAngle, endAngle){

            var start = polarToCartesian(x, y, radius, endAngle);
            var end = polarToCartesian(x, y, radius, startAngle);

            var largeArcFlag = endAngle - startAngle <= 180 ? "0" : "1";

            var d = [
                "M", start.x, start.y,
                "A", radius, radius, 0, largeArcFlag, 0, end.x, end.y
            ].join(" ");

            return d;
        }

        let R = 160;
        let dRange = [];
        let iRange = [];
        let steps = 359;
        for (var i = 0; i<steps; i++){
            dRange.push(describeArc(160, 160, 160, 0, i));
            iRange.push(i/(steps-1));
        }


        var _d = this.state.progress.interpolate({
            inputRange: iRange,
            outputRange: dRange
        })

        return (
            <Svg style={{flex: 1}}>
                <Circle
                    cx={R}
                    cy={R}
                    r={R}
                    stroke="green"
                    strokeWidth="2.5"
                    fill="green"
                />
                {/*       X0  Y0               X1   Y1*/}
                <AnimatedPath d={_d}
                      stroke="red" strokeWidth={5} fill="none"/>

            </Svg>
        );
    }
    }

    export default App;
Run Code Online (Sandbox Code Playgroud)

这个简单的组件可以根据需要使用

  • 在组件的顶部,我们写道,

AnimatedPath = Animated.createAnimatedComponent(Path);

  因为Path哪个是从react-native-svg导入的,不是本机react-native组件,我们把它变成动画.

  • constructor我们定义为动画过程中应改变动画状态的进展.

  • componentDidMount动画过程中开始.

  • render方法开始时,d声明(polarToCartesiandescribeArc)声明定义SVG 参数所需的两个函数.

  • 然后反应天然interpolate上使用this.state.progress内插在变化this.state.progress从0到1,放入d参数变化.但是,这里有两点你应该记住:

       1-不同长度的两个弧之间的变化不是线性的,因此从角度0到360的线性插值不能按照您的意愿工作,因此,最好在n度的不同步骤中定义动画(我使用过1度,如果需要,你可以增加或减少它.).

       2弧不能继续高达360度(因为它等于0),所以最好以接近但不等于360的程度完成动画(例如359.9)

  • 在返回部分的末尾,描述了UI.

  • 这是 https://snack.expo.io/B1qSWJfvG 的小吃,有什么建议可以让动画路径看起来是 360%? (2认同)