React Native样式是否支持渐变?

Som*_*Guy 54 react-native

我看到有人为此做了这个:https://github.com/brentvatne/react-native-linear-gradient

但RN本身是否有支持?就像是

style = StyleSheet.create({
    backgroundGradient: "vertical",
    backgroundGradientTop: "#333333",
    backgroundGradientBottom: "#666666"
});
Run Code Online (Sandbox Code Playgroud)

isa*_*air 36

现在不行.您应该使用您链接的库; 他们最近添加了Android支持,它是react-native的主要贡献者之一.

  • react-native-SVG(另一个被广泛接受的包)也支持线性渐变 - 可以在此处看到创建线性渐变的良好且简单的实现 https://medium.com/@ibrahimozdogan/adding-gradient-in-react-native -f75ddd02aea4 (4认同)

Ily*_*lin 13

只需将您的渐变导出为SVGreact-native-svg在导入组件后设置宽度和高度时使用它,并preserveAspectRatio="xMinYMin slice"根据需要缩放 SVG 渐变。

  • 这个答案也值得评论。数百名开发人员使用react-native-svg库,并且仍然安装更多具有重复功能的库。我震惊地向下滚动,没有人提到它,并认为我可能是最聪明的‍♂️。 (3认同)
  • 同意@AlexShtromberg 最聪明的解决方案,无需额外的库。值得更多的赞成票。 (2认同)
  • 基于该答案,我创建了一个简单易用的组件(参见下面的答案):/sf/answers/5192808771/ (2认同)

小智 10

第一次运行 npm install expo-linear-gradient --save

您不需要使用动画标签,但这是我在代码中使用的。

里面 colors={[ put your gradient colors ]}

那么你可以使用这样的东西:

 import { LinearGradient } from "expo-linear-gradient";
 import { Animated } from "react-native";

 <AnimatedLinearGradient
    colors={["rgba(255,255,255, 0)", "rgba(255,255,255, 1)"]}
    style={{ your styles go here }}/>

const AnimatedLinearGradient = Animated.createAnimatedComponent(LinearGradient);
Run Code Online (Sandbox Code Playgroud)


538*_*MEO 10

虽然有点晚了,但我认为最好的解决方案是使用 SVG 渐变react-native-svg大多数项目都包含它。

这是几行多功能组件,每当我需要渐变时我都会使用它们:

简单的 SVG 线性渐变组件

import { View, StyleSheet, ViewProps, DimensionValue } from 'react-native'
import Svg, { Defs, Rect, LinearGradient, Stop } from 'react-native-svg'

type GradientProps = { fromColor: string, toColor: string, children?: any, height?: DimensionValue, opacityColor1?: number, opacityColor2?: number } & ViewProps

function Gradient({ children, fromColor, toColor, height = '100%', opacityColor1 = 1, opacityColor2 = 1, ...otherViewProps }: GradientProps) {
    const gradientUniqueId = `grad${fromColor}+${toColor}`.replace(/[^a-zA-Z0-9 ]/g, '')
    return <>
        <View style={[{ ...StyleSheet.absoluteFillObject, height, zIndex: -1, top: 0, left: 0 }, otherViewProps.style]} {...otherViewProps}>
            <Svg height='100%' width="100%" style={StyleSheet.absoluteFillObject}>
                <Defs>
                    <LinearGradient id={gradientUniqueId} x1="0%" y1="0%" x2="0%" y2="100%">
                        <Stop offset="0" stopColor={fromColor} stopOpacity={opacityColor1} />
                        <Stop offset="1" stopColor={toColor} stopOpacity={opacityColor2} />
                    </LinearGradient>
                </Defs>
                <Rect width="100%" height="100%" fill={`url(#${gradientUniqueId})`} />
            </Svg>
        </View>
        {children}
    </>
};

export default Gradient
Run Code Online (Sandbox Code Playgroud)

请参阅零食上的示例用法


Cas*_*rin 6

对于 iOS 和 Android 平台的渐变,这是一个不错的选择:

https://github.com/react-native-community/react-native-linear-gradient

还有其他方法,例如 expo,但是 react-native-linear-gradient 对我来说效果更好。

<LinearGradient colors={['#4c669f', '#3b5998', '#192f6a']} style={styles.linearGradient}>
  <Text style={styles.buttonText}>
    Sign in with Facebook
  </Text>
</LinearGradient>

// Later on in your styles..
var styles = StyleSheet.create({
  linearGradient: {
    flex: 1,
    paddingLeft: 15,
    paddingRight: 15,
    borderRadius: 5
  },
  buttonText: {
    fontSize: 18,
    fontFamily: 'Gill Sans',
    textAlign: 'center',
    margin: 10,
    color: '#ffffff',
    backgroundColor: 'transparent',
  },
});
Run Code Online (Sandbox Code Playgroud)


小智 6

世博会?好吧,在 React Native 中使用 EXPO 使用线性渐变这个方法。(2021 年 11 月更新)

没有 Pod 安装、没有错误、没有其他链接文件。

expo install expo-linear-gradient
Run Code Online (Sandbox Code Playgroud)

然后

import { LinearGradient } from 'expo-linear-gradient';

<View style={styles.container}>
      <LinearGradient
        // Background Linear Gradient
        colors={['rgba(0,0,0,0.8)', 'transparent']}
        style={styles.background}
      />
      <LinearGradient
        // Button Linear Gradient
        colors={['#4c669f', '#3b5998', '#192f6a']}
        style={styles.button}>
        <Text style={styles.text}>Sign in with Facebook</Text>
      </LinearGradient>
    </View>
Run Code Online (Sandbox Code Playgroud)

完整链接在这里:https ://docs.expo.dev/versions/latest/sdk/linear-gradient/


小智 5

您可以尝试使用此JS代码。.https ://snack.expo.io/r1v0LwZFb

import React, { Component } from 'react';
import { View } from 'react-native';

export default class App extends Component {
  render() {
    const gradientHeight=500;
    const gradientBackground  = 'purple';
        const data = Array.from({ length: gradientHeight });
        return (
            <View style={{flex:1}}>
                {data.map((_, i) => (
                    <View
                        key={i}
                        style={{
                            position: 'absolute',
                            backgroundColor: gradientBackground,
                            height: 1,
                            bottom: (gradientHeight - i),
                            right: 0,
                            left: 0,
                            zIndex: 2,
                            opacity: (1 / gradientHeight) * (i + 1)
                        }}
                    />
                ))}
            </View>
        );
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 这段代码创建了数百个视图,这对性能有影响。这是一个非常棘手的解决方法,而不是可用于生产的解决方案。请改用react-native-linear-gradient软件包。 (21认同)
  • 当然不是生产准备就绪的解决方案,但是令我惊讶的是您提出了这样的解决方案。满足您需求的东西肯定是一种难得的功能。 (7认同)

Li *_*eng 5

这是一个生产就绪的纯 JavaScript 解决方案:

<View styles={{backgroundColor: `the main color you want`}}>
    <Image source={`A white to transparent gradient png`}>
</View>
Run Code Online (Sandbox Code Playgroud)

以下是使用此解决方案的 npm 包的源代码: https://github.com/flyskywhy/react-native-smooth-slider/blob/0f18a8bf02e2d436503b9a8ba241440247ef1c44/src/Slider.js#L329

这是使用此 npm 包的饱和度和亮度的渐变调色板屏幕截图: https://github.com/flyskywhy/react-native-slider-color-picker

反应本机滑块颜色选择器