资讯专栏INFORMATION COLUMN

探究 React Native 中 Props 驱动的 SVG 动画和 Value 驱动动画

Codeing_ls / 2623人阅读

摘要:再来看前端,前端的动画实现,经过多年的发展,已分为动画和动画。此外还探究了驱动动画在实现方法上的不同之处。驱动的动画接下来看驱动的动画。改造后的函数如下关键修改,强制刷新。对于,函数是可行的,然而对无效。

引言

一直以来,动画都是移动开发中极为特殊的一块。一方面,动画在交互体验上有着不可替代的优越处,然而另一方面,动画的开发又极为的耗时,需要消耗工程师大量的时间用于开发和调试。再来看前端,前端的动画实现,经过多年的发展,已分为 CSS3 动画和 JavaScript 动画。

React Native 作为一个复用前端思想的移动开发框架,并没有完整实现CSS,而是使用JavaScript来给应用添加样式。这是一个有争议的决定,可以参考这个幻灯片来了解 Facebook 做的理由。自然,在动画上,因为缺少大量的 CSS 属性,React Naive 中的动画均为 JavaScript 动画,即通过 JavaScript 代码控制图像的各种参数值的变化,从而产生时间轴上的动画效果。

React Native 的官方文档已经详细地介绍了 React Native 一般动画的使用方法和实例,在此不再赘述。然而阅读官方文档后可知,官方的动画往往是给一个完整的物体添加各种动画效果,如透明度,翻转,移动等等。但是对于物体的自身变化,比如如下这个进度条,明显是在旋转的同时也在伸缩,则缺乏必要的实现方法。这是因为,动画的本质既是图形的各种参数的数值变化的过程,文档中的 Animated.Value 就是用作被驱动的参数,可以,想要让一个圆环能够伸缩,就必须让数值变化的过程,深入到图形生成的过程中,而不是如官方文档的例子一样,仅仅是施加于图形生成完毕后的过程,那么也就无法实现改变图形自身的动画效果了。

拙作初窥基于 react-art 库的 React Native SVG已讨论了 React Native 中静态 SVG 的开发方法,本文则致力于探究 React Native 中 SVG 与 Animation 结合所实现的 SVG 动画。也就是可以改变图形自身的动画效果。此外还探究了 Value 驱动动画在实现方法上的不同之处。

Props 驱动的 SVG 动画

本节即以实现一个下图所示的旋转的进度条的例子,讲述 React Native SVG 动画的开发方法。

Wedge.art.js 位于 react-art 库下 lib/ 文件夹内,提供了 SVG 扇形的实现,然而缺乏对 cx, cy 属性的支持。另外拙作之前也提到了,Wedge中的扇形较为诡异,只有一条半径,为了实现进度条效果我把另一条半径也去掉了。我将 Wedge.art.js 拷贝到工程中,自行小修改后的代码如下。

</>复制代码

  1. // wedge.js
  2. /**
  3. * Copyright 2013-2014 Facebook, Inc.
  4. * All rights reserved.
  5. *
  6. * This source code is licensed under the BSD-style license found in the
  7. * LICENSE file in the root directory of this source tree. An additional grant
  8. * of patent rights can be found in the PATENTS file in the same directory.
  9. *
  10. * @providesModule Wedge.art
  11. * @typechecks
  12. *
  13. * Example usage:
  14. *
  15. *
  16. * Additional optional property:
  17. * (Int) innerRadius
  18. *
  19. */
  20. "use strict";
  21. var React = require("react-native");
  22. var ReactART = React.ART;
  23. var $__0 = React,PropTypes = $__0.PropTypes;
  24. var Shape = ReactART.Shape;
  25. var Path = ReactART.Path;
  26. /**
  27. * Wedge is a React component for drawing circles, wedges and arcs. Like other
  28. * ReactART components, it must be used in a .
  29. */
  30. var Wedge = React.createClass({displayName: "Wedge",
  31. propTypes: {
  32. outerRadius: PropTypes.number.isRequired,
  33. startAngle: PropTypes.number.isRequired,
  34. endAngle: PropTypes.number.isRequired,
  35. innerRadius: PropTypes.number,
  36. cx: PropTypes.number,
  37. cy: PropTypes.number
  38. },
  39. circleRadians: Math.PI * 2,
  40. radiansPerDegree: Math.PI / 180,
  41. /**
  42. * _degreesToRadians(degrees)
  43. *
  44. * Helper function to convert degrees to radians
  45. *
  46. * @param {number} degrees
  47. * @return {number}
  48. */
  49. _degreesToRadians: function(degrees) {
  50. if (degrees !== 0 && degrees % 360 === 0) { // 360, 720, etc.
  51. return this.circleRadians;
  52. } else {
  53. return degrees * this.radiansPerDegree % this.circleRadians;
  54. }
  55. },
  56. /**
  57. * _createCirclePath(or, ir)
  58. *
  59. * Creates the ReactART Path for a complete circle.
  60. *
  61. * @param {number} or The outer radius of the circle
  62. * @param {number} ir The inner radius, greater than zero for a ring
  63. * @return {object}
  64. */
  65. _createCirclePath: function(or, ir) {
  66. var path = Path();
  67. path.move(this.props.cx, or + this.props.cy)
  68. .arc(or * 2, 0, or)
  69. .arc(-or * 2, 0, or);
  70. if (ir) {
  71. path.move(this.props.cx + or - ir, this.props.cy)
  72. .counterArc(ir * 2, 0, ir)
  73. .counterArc(-ir * 2, 0, ir);
  74. }
  75. path.close();
  76. return path;
  77. },
  78. /**
  79. * _createArcPath(sa, ea, ca, or, ir)
  80. *
  81. * Creates the ReactART Path for an arc or wedge.
  82. *
  83. * @param {number} startAngle The starting degrees relative to 12 o"clock
  84. * @param {number} endAngle The ending degrees relative to 12 o"clock
  85. * @param {number} or The outer radius in pixels
  86. * @param {number} ir The inner radius in pixels, greater than zero for an arc
  87. * @return {object}
  88. */
  89. _createArcPath: function(startAngle, endAngle, or, ir) {
  90. var path = Path();
  91. // angles in radians
  92. var sa = this._degreesToRadians(startAngle);
  93. var ea = this._degreesToRadians(endAngle);
  94. // central arc angle in radians
  95. var ca = sa > ea ? this.circleRadians - sa + ea : ea - sa;
  96. // cached sine and cosine values
  97. var ss = Math.sin(sa);
  98. var es = Math.sin(ea);
  99. var sc = Math.cos(sa);
  100. var ec = Math.cos(ea);
  101. // cached differences
  102. var ds = es - ss;
  103. var dc = ec - sc;
  104. var dr = ir - or;
  105. // if the angle is over pi radians (180 degrees)
  106. // we will need to let the drawing method know.
  107. var large = ca > Math.PI;
  108. // TODO (sema) Please improve theses comments to make the math
  109. // more understandable.
  110. //
  111. // Formula for a point on a circle at a specific angle with a center
  112. // at (0, 0):
  113. // x = radius * Math.sin(radians)
  114. // y = radius * Math.cos(radians)
  115. //
  116. // For our starting point, we offset the formula using the outer
  117. // radius because our origin is at (top, left).
  118. // In typical web layout fashion, we are drawing in quadrant IV
  119. // (a.k.a. Southeast) where x is positive and y is negative.
  120. //
  121. // The arguments for path.arc and path.counterArc used below are:
  122. // (endX, endY, radiusX, radiusY, largeAngle)
  123. path.move(or + or * ss + this.props.cx, or - or * sc + this.props.cy) // move to starting point
  124. .arc(or * ds, or * -dc, or, or, large) // outer arc
  125. // .line(dr * es, dr * -ec); // width of arc or wedge
  126. if (ir) {
  127. path.counterArc(ir * -ds, ir * dc, ir, ir, large); // inner arc
  128. }
  129. return path;
  130. },
  131. render: function() {
  132. // angles are provided in degrees
  133. var startAngle = this.props.startAngle;
  134. var endAngle = this.props.endAngle;
  135. if (startAngle - endAngle === 0) {
  136. return;
  137. }
  138. // radii are provided in pixels
  139. var innerRadius = this.props.innerRadius || 0;
  140. var outerRadius = this.props.outerRadius;
  141. // sorted radii
  142. var ir = Math.min(innerRadius, outerRadius);
  143. var or = Math.max(innerRadius, outerRadius);
  144. var path;
  145. if (endAngle >= startAngle + 360) {
  146. path = this._createCirclePath(or, ir);
  147. } else {
  148. path = this._createArcPath(startAngle, endAngle, or, ir);
  149. }
  150. return React.createElement(Shape, React.__spread({}, this.props, {d: path}));
  151. }
  152. });
  153. module.exports = Wedge;

然后就是实现的主体。其中值得关注的点是:

并非任何 Component 都可以直接用 Animated.Value 去赋值 Props,而需要对 Component 做一定的改造。Animated.createAnimatedComponent(Component component),是 Animated 库提供的用于把普通 Component 改造为 AnimatedComponent 的函数。阅读 React Native 源代码会发现,Animated.Text, Animated.View, Animated.Image,都是直接调用了该函数去改造系统已有的组件,如Animated.createAnimatedComponent(React.Text)

Easing 库较为隐蔽,明明在react-native/Library/Animated/路径下,却又需要从React中直接引出。它为动画的实现提供了许多缓动函数,可根据实际需求选择。如 linear() 线性,quad() 二次(quad明明是四次方的意思,为毛代码实现是t*t....),cubic() 三次等等。官方文档中吹嘘 Easing 中提供了 tons of functions(成吨的函数),然而我数过了明明才14个,233333。

该动画由起始角度和终止角度两个变化的参数来控制,因此,两个Animated.Value需要同时启动,这涉及到了动画的组合问题。React Native 为此提供了 parallelsequencestaggerdelay 四个函数。其主要实现均可在react-native/Library/Animated/Animate中找到,官方文档中亦有说明。这里用的是Animated.parallel

开发中遇到的问题有:

该动画在 Android 上可以运行,但是刷新频率看上去只有两帧,无法形成一个自然过渡的动画,笔者怀疑是 React Native Android 对 SVG 的支持仍有缺陷。

SVG 图形和普通 React Native View 的叠加问题,目前我还没有找到解决方法。感觉只能等 React Native 开发组的进一步支持。

动画播放总会有一个莫名其妙的下拉回弹效果,然而代码上没有任何额外的控制。

</>复制代码

  1. // RotatingWedge.js
  2. "use strict";
  3. var React = require("react-native");
  4. var {
  5. ART,
  6. View,
  7. Animated,
  8. Easing,
  9. } = React;
  10. var Group = ART.Group;
  11. var Surface = ART.Surface;
  12. var Wedge = require("./Wedge");
  13. var AnimatedWedge = Animated.createAnimatedComponent(Wedge);
  14. var VectorWidget = React.createClass({
  15. getInitialState: function() {
  16. return {
  17. startAngle: new Animated.Value(90),
  18. endAngle: new Animated.Value(100),
  19. };
  20. },
  21. componentDidMount: function() {
  22. Animated.parallel([
  23. Animated.timing(
  24. this.state.endAngle,
  25. {
  26. toValue: 405,
  27. duration: 700,
  28. easing: Easing.linear,
  29. }
  30. ),
  31. Animated.timing(
  32. this.state.startAngle,
  33. {
  34. toValue: 135,
  35. duration: 700,
  36. easing: Easing.linear,
  37. })
  38. ]).start();
  39. },
  40. render: function() {
  41. return (
  42. {this.renderGraphic()}
  43. );
  44. },
  45. renderGraphic: function() {
  46. console.log(this.state.endAngle.__getValue());
  47. return (
  48. );
  49. }
  50. });
  51. module.exports = VectorWidget;
Value 驱动的动画

接下来看 Value 驱动的 SVG 动画。先解释一下 Value 和 Props 的区别。,这里的 color 就是 Props,black这里的 black 就是 value。

为什么要特意强调这一点呢,如果我们想要做一个如下图所示的从10到30变动的数字,按照上节所述的方法,直接调用 Animated.createAnimatedComponent(React.Text)所生成的 Component ,然后给 Value 赋值一个Animated.Value(),然后Animated.timing...,是无法产生这样的效果的。

必须要对库中的createAnimatedComponent()函数做一定的改造。改造后的函数如下:

</>复制代码

  1. var AnimatedProps = Animated.__PropsOnlyForTests;
  2. function createAnimatedTextComponent() {
  3. var refName = "node";
  4. class AnimatedComponent extends React.Component {
  5. _propsAnimated: AnimatedProps;
  6. componentWillUnmount() {
  7. this._propsAnimated && this._propsAnimated.__detach();
  8. }
  9. setNativeProps(props) {
  10. this.refs[refName].setNativeProps(props);
  11. }
  12. componentWillMount() {
  13. this.attachProps(this.props);
  14. }
  15. attachProps(nextProps) {
  16. var oldPropsAnimated = this._propsAnimated;
  17. /** 关键修改,强制刷新。
  18. 原来的代码是:
  19. var callback = () => {
  20. if (this.refs[refName].setNativeProps) {
  21. var value = this._propsAnimated.__getAnimatedValue();
  22. this.refs[refName].setNativeProps(value);
  23. } else {
  24. this.forceUpdate();
  25. }
  26. };
  27. **/
  28. var callback = () => {
  29. this.forceUpdate();
  30. };
  31. this._propsAnimated = new AnimatedProps(
  32. nextProps,
  33. callback,
  34. );
  35. oldPropsAnimated && oldPropsAnimated.__detach();
  36. }
  37. componentWillReceiveProps(nextProps) {
  38. this.attachProps(nextProps);
  39. }
  40. render() {
  41. var tmpText = this._propsAnimated.__getAnimatedValue().text;
  42. return (
  43. {Math.floor(tmpText)}
  44. );
  45. }
  46. }
  47. return AnimatedComponent;
  48. }

为了获取必须要用到的AnimatedProps,笔者甚至违背了道德的约束,访问了双下划线前缀的变量Animated.__PropsOnlyForTests,真是罪恶啊XD。

言归正传,重要的修改有:

修改了 attachProps 函数。对于任何变动的 props,原来的代码会试图使用 setNativeProps 函数进行更新,若 setNativeProps 函数为空,才会使用 forceUpdate() 函数。对于 props,setNativeProps 函数是可行的,然而对 value 无效。我猜测,setNativeProps 方法在 Android 底层可能就是 setColor() 类似的 Java 方法,然而并没有得到实证。目前这种 forceUpdate,由注释知,是彻底更新了整个 Component,相当于先从 DOM 树上取下一个旧节点,再放上一个新节点,在性能的利用上较为浪费。

使用 PropTypes.xxx.isRequired 来进行参数的类型检查。PropTypes 检查支持的类型可在 react-native/node_modules/react/lib/ReactPropTypes.js 中看到,在此不再赘述。

Animated.value() 从10到30变化的过程是一个随机采样的过程,并不一定会卡在整数值上,因此还需要做一些小处理。

值得注意的是,该动画在 Android 上虽然可以正常运行,但也存在丢帧的问题,远远不能如 iOS 上流畅自然。对于这一点,只能等待 Facebook 的进一步优化。

全部的代码如下:

</>复制代码

  1. // RisingNumber.js
  2. "use strict";
  3. var React = require("react-native");
  4. var {
  5. Text,
  6. Animated,
  7. Easing,
  8. PropTypes,
  9. View,
  10. StyleSheet,
  11. } = React;
  12. var AnimatedText = createAnimatedTextComponent();
  13. var AnimatedProps = Animated.__PropsOnlyForTests;
  14. function createAnimatedTextComponent() {
  15. var refName = "node";
  16. class AnimatedComponent extends React.Component {
  17. _propsAnimated: AnimatedProps;
  18. componentWillUnmount() {
  19. this._propsAnimated && this._propsAnimated.__detach();
  20. }
  21. setNativeProps(props) {
  22. this.refs[refName].setNativeProps(props);
  23. }
  24. componentWillMount() {
  25. this.attachProps(this.props);
  26. }
  27. attachProps(nextProps) {
  28. var oldPropsAnimated = this._propsAnimated;
  29. var callback = () => {
  30. this.forceUpdate();
  31. };
  32. this._propsAnimated = new AnimatedProps(
  33. nextProps,
  34. callback,
  35. );
  36. oldPropsAnimated && oldPropsAnimated.__detach();
  37. }
  38. componentWillReceiveProps(nextProps) {
  39. this.attachProps(nextProps);
  40. }
  41. render() {
  42. var tmpText = this._propsAnimated.__getAnimatedValue().text;
  43. return (
  44. {Math.floor(tmpText)}
  45. );
  46. }
  47. }
  48. return AnimatedComponent;
  49. }
  50. var RisingNumber = React.createClass({
  51. propTypes: {
  52. startNumber: PropTypes.number.isRequired,
  53. toNumber: PropTypes.number.isRequired,
  54. startFontSize: PropTypes.number.isRequired,
  55. toFontSize: PropTypes.number.isRequired,
  56. duration: PropTypes.number.isRequired,
  57. upperText: PropTypes.string.isRequired,
  58. },
  59. getInitialState: function() {
  60. return {
  61. number: new Animated.Value(this.props.startNumber),
  62. fontSize: new Animated.Value(this.props.startFontSize),
  63. };
  64. },
  65. componentDidMount: function() {
  66. Animated.parallel([
  67. Animated.timing(
  68. this.state.number,
  69. {
  70. toValue: this.props.toNumber,
  71. duration: this.props.duration,
  72. easing: Easing.linear,
  73. },
  74. ),
  75. Animated.timing(
  76. this.state.fontSize,
  77. {
  78. toValue: this.props.toFontSize,
  79. duration: this.props.duration,
  80. easing: Easing.linear,
  81. }
  82. )
  83. ]).start();
  84. },
  85. render: function() {
  86. return (
  87. {this.props.upperText}
  88. );
  89. },
  90. });
  91. var styles = StyleSheet.create({
  92. kind: {
  93. fontSize: 15,
  94. color: "#01A971",
  95. },
  96. number: {
  97. marginLeft: 15,
  98. },
  99. });
  100. module.exports = RisingNumber;

====================================
如果您觉得我的文章对您有所启迪,请点击文末的推荐按钮,您的鼓励将会成为我坚持写作的莫大激励。 by DesGemini

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/79036.html

相关文章

  • 11个React Native 组件库 Javascript 数据可视化库

    摘要:数据可视化库超过的的可能是最流行和最广泛的数据可视化库。是一组组件,用于高效地渲染大型列表和表格数据。一种优雅而灵活的方式,可以利用组件来支持实际的数据可视化。 想阅读更多优质文章请猛戳GitHub博客,一年百来篇优质文章等着你! React Native 组件库 1. NativeBase showImg(https://segmentfault.com/img/bVbrLHH?w=...

    tangr206 评论0 收藏0
  • 前端每周清单半年盘点之 ReactReactNative

    摘要:前端每周清单半年盘点之与篇前端每周清单专注前端领域内容,以对外文资料的搜集为主,帮助开发者了解一周前端热点分为新闻热点开发教程工程实践深度阅读开源项目巅峰人生等栏目。与求同存异近日,宣布将的构建工具由迁移到,引发了很多开发者的讨论。 前端每周清单半年盘点之 React 与 ReactNative 篇 前端每周清单专注前端领域内容,以对外文资料的搜集为主,帮助开发者了解一周前端热点;分为...

    Barry_Ng 评论0 收藏0
  • 初窥基于 react-art 库 React Native SVG

    摘要:语法更近似于移动端。当参数为两个时,等同于,绘制光滑二次贝塞尔曲线。有些精通的同学这时候可能就要问我了,不对啊,二次贝塞尔曲线和光滑三次贝塞尔曲线的参数都是个,你这里没有光滑三次啊因为开发的同学留坑没写了呀微笑。和则是用于指定旋转的原点。 技术背景 在移动应用的开发过程中,绘制基本的二维图形或动画是必不可少的。然而,考虑到Android和iOS均有一套各自的API方案,因此采用一种更普...

    xiaowugui666 评论0 收藏0
  • 前端动画调研-V1

    摘要:支持动画状态的,在动画开始,执行中,结束时提供回调函数支持动画可以自定义贝塞尔曲线任何包含数值的属性都可以设置动画仓库文档演示功能介绍一定程度上,也是一个动画库,适用所有的属性,并且实现的能更方便的实现帧动画,替代复杂的定义方式。 动画调研-V1 前言:动画从用途上可以分为两种,一种是展示型的动画,类似于一张GIF图,或者一段视频,另一种就是交互性的动画。这两种都有具体的应用场景,比如...

    ddongjian0000 评论0 收藏0
  • 14个最好 JavaScript 数据可视化库

    摘要:适用于,演示这是开发的一个简单的可视化库,它允许你创建所有常用的图表类型条形图,树形图,折线图,面积图等。可以轻松地对折线图和条形图进行混合和匹配以组合不同的数据集,这是非常棒的功能。 翻译:疯狂的技术宅原文:https://www.monterail.com/blo... 本文首发微信公众号:jingchengyideng欢迎关注,每天都给你推送新鲜的前端技术文章 你的程序有多...

    Mertens 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<