Skip to content

Instantly share code, notes, and snippets.

@rajivnarayana
Created March 6, 2019 11:26
Show Gist options
  • Save rajivnarayana/d60affcf25dc39315f8856432d0ad2c8 to your computer and use it in GitHub Desktop.
Save rajivnarayana/d60affcf25dc39315f8856432d0ad2c8 to your computer and use it in GitHub Desktop.
A React Native ART example to draw Smooth curve passing through a given set of points.
import React from 'react';
import { StyleSheet, View } from 'react-native';
import { ART } from "react-native";
const { Surface, Shape, Path } = ART;
const POINTS_SPACING = 40;
const path = (values, height) => {
const d = new Path();
for (var i = 0; i < values.length; i++) {
if (i == 0) {
d.moveTo(0, height - values[i])
// .moveTo(0, values[i]);
} else {
d.line(POINTS_SPACING, values[i-1] - values[i]);
}
}
return d;
}
cubicCurveTo = (d, x0, y0, x1, y1, x2, y2) => {
const cx1 = x0 + 2/3 * (x1 - x0);
const cy1 = y0 + 2/3 * (y1 - y0);
const cx2 = x2 + 2/3 * (x1 - x2);
const cy2 = y2 + 2/3 * (y1 - y2);
return d.curveTo(cx1, cy1, cx2, cy2, x2, y2);
}
const spline = (points, height) => {
const d = new Path();
points = points.map((point, index) => ({x : POINTS_SPACING * index, y : height - point}));
d.moveTo((points[0].x), points[0].y);
for(var i = 0; i < points.length-1; i ++) {
var x_mid = (points[i].x + points[i+1].x) / 2;
var y_mid = (points[i].y + points[i+1].y) / 2;
var cp_x1 = (x_mid + points[i].x) / 2;
// var cp_y1 = (y_mid + points[i].y) / 2;
var cp_x2 = (x_mid + points[i+1].x) / 2;
// var cp_y2 = (y_mid + points[i+1].y) / 2;
cubicCurveTo(d, points[i].x, points[i].y, cp_x1, points[i].y ,x_mid, y_mid);
cubicCurveTo(d, x_mid, y_mid, cp_x2, points[i+1].y ,points[i+1].x,points[i+1].y);
}
return d;
}
const points = (points, height, radius = 2) => {
const d = new Path();
points = points.map((point, index) => ({x : POINTS_SPACING * index, y : height - point}));
points.forEach(point => {
d.moveTo(point.x, point.y - radius).arc(0, radius * 2, radius)
.arc(0, radius * -2, radius);
})
return d;
}
export default class App extends React.Component {
render() {
const values = [10, 30, 40, 70, 12, 30, 80];
// const values = [ 20, 100, 75, 100, 50];
const height = 200;
return (
<View style={styles.container}>
<Surface height={height} width="300" style={{backgroundColor: 'lightgray'}}>
<Shape d={points(values, height)} strokeWidth={2} stroke="black"></Shape>
{/* <Shape d={path(values, height)} strokeWidth={2} stroke="black"></Shape> */}
<Shape d={spline(values, height)} strokeWidth={2} stroke="blue"></Shape>
</Surface>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
// backgroundColor: 'green',
alignItems: 'center',
justifyContent: 'center',
},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment