rn_view_gradient
Version:
A simple react native component for creating a gradient colour view using only View components no native code.
105 lines (88 loc) • 2.74 kB
JavaScript
import React, { Component } from 'react';
import { Text, View, StyleSheet } from 'react-native';
const startColor = "#DF9191";
const endColor = "#ff0000";
function colToNum (color) {
const red = color.substr(1, 2);
const green = color.substr(3, 2);
const blue = color.substr(5, 2);
const rI = parseInt(red, 16);
const gI = parseInt(blue, 16);
const bI = parseInt(green, 16);
const num = ((rI * 256) + gI) * 256 + bI;
return num;
}
function numToCol (num) {
let n = num;
const bI = n > 256 ? n % 256 : 0;
n = parseInt(n / 256);
const gI = n > 256 ? n % 256 : 0;
n = parseInt(n / 256);
const rI = n > 0 ? n : 0;
const r = rI.toString(16);
const g = gI.toString(16);
const b = bI.toString(16);
const color = "#" + (r.length == 1 ? "0" + r : r) + (g.length == 1 ? "0" + g : g) + (b.length == 1 ? "0" + b : b);
return color;
}
function diffCol (n1, n2) {
let a = n1;
let b = n2
const b1 = a > 256 ? a % 256 : 0;
a = parseInt(a / 256);
const g1 = a > 256 ? a % 256 : 0;
a = parseInt(a / 256);
const r1 = a > 0 ? a : 0;
const b2 = b > 256 ? b % 256 : 0;
b = parseInt(b / 256);
const g2 = b > 256 ? b % 256 : 0;
b = parseInt(b / 256);
const r2 = b > 0 ? b : 0;
return [r2 - r1, g2 - g1, b2 - b1];
}
function apNextCol (s, d, i, h) {
const r = (d[0] * i) / h;
const g = (d[1] * i) / h;
const b = (d[2] * i) / h;
const add = ((parseInt(r) * 256) + parseInt(g)) * 256 + parseInt(b);
return numToCol(s + add);
}
function gradient(start, end, height) {
const a = colToNum(start);
const b = colToNum(end);
const d = b - a;
const d2 = diffCol(a,b);
const data = Array.from({ length: height });
return (
<View style={{flex:1}}>
{data.map((_, i) => {
// const c = numToCol(a + parseInt(d*i / gradientHeight));
const c = apNextCol(a, d2, i, height);
return (
<View
key={i}
style={{
position: 'absolute',
backgroundColor: c,
height: 1,
top: (i + 50),
right: 0,
left: 0,
zIndex: 2
}}
/>
); })}
</View>
);
}
class GradientComponent extends Component {
render () {
const { startColor, endColor, height } = this.props;
return (
<View style={{flex:1}}>
{gradient(startColor, endColor, 200)}
</View>
);
}
}
export default GradientComponent;