1import React from 'react'; 2import { StyleSheet, View } from 'react-native'; 3export default class NativeLinearGradient extends React.PureComponent { 4 constructor() { 5 super(...arguments); 6 this.state = { 7 width: undefined, 8 height: undefined, 9 }; 10 this.onLayout = event => { 11 this.setState({ 12 width: event.nativeEvent.layout.width, 13 height: event.nativeEvent.layout.height, 14 }); 15 if (this.props.onLayout) { 16 this.props.onLayout(event); 17 } 18 }; 19 } 20 getAngle() { 21 const startPoint = this.props.startPoint ? this.props.startPoint : [0.5, 0.0]; 22 const endPoint = this.props.endPoint ? this.props.endPoint : [0.5, 1.0]; 23 const { width = 0, height = 0 } = this.state; 24 let angle = 0; 25 const gradientWidth = height * (endPoint[0] - startPoint[0]); 26 const gradientHeight = width * (endPoint[1] - startPoint[1]); 27 angle = Math.atan2(gradientHeight, gradientWidth) + Math.PI / 2; 28 return `${angle}rad`; 29 } 30 getColors() { 31 const { colors } = this.props; 32 return colors 33 .map((color, index) => { 34 const colorStr = `${color.toString(16)}`; 35 const hex = `#${colorStr.substring(2, colorStr.length)}`; 36 const location = this.props.locations && this.props.locations[index]; 37 if (location) { 38 return `${hex} ${location * 100}%`; 39 } 40 return hex; 41 }) 42 .join(','); 43 } 44 getBackgroundImage() { 45 if (this.state.width && this.state.height) { 46 return `linear-gradient(${this.getAngle()},${this.getColors()})`; 47 } 48 else { 49 return 'transparent'; 50 } 51 } 52 render() { 53 const { colors, locations, startPoint, endPoint, onLayout, style, ...props } = this.props; 54 let compiledStyle = StyleSheet.flatten(style) || {}; 55 const flatStyle = { 56 ...compiledStyle, 57 // @ts-ignore: [ts] Property 'backgroundImage' does not exist on type 'ViewStyle'. 58 backgroundImage: this.getBackgroundImage(), 59 }; 60 // TODO: Bacon: In the future we could consider adding `backgroundRepeat: "no-repeat"`. For more browser support. 61 return <View style={flatStyle} onLayout={this.onLayout} {...props}/>; 62 } 63} 64//# sourceMappingURL=NativeLinearGradient.web.js.map