我想成为Touchable
透明元素的一部分,即能够看到其背后的背景。
[可能的破解方法是使用MaskedView
并再次在Touchable
内绘制背景,作为children
的MaskedView
属性。但是,这仅适用于有限的情况。它在这里工作:
但是,例如,当我增加一些余量时,事情就异相了:
一些澄清,以防万一:
这里是MWE:
import React from 'react';
import {
View,
TouchableOpacity,
} from 'react-native';
import MaskedView from '@react-native-community/masked-view';
import LinearGradient from 'react-native-linear-gradient';
export default function () {
return (
<LinearGradient start={{x: 0, y: 0}} end={{x: 1, y: 0}}
colors={['red', 'blue', 'green']}
style={
{flex: 1,
alignItems: 'stretch',
justifyContent: 'center'}
}>
<TouchableOpacity>
<View style={
{height: 100,
alignItems: 'stretch',
justifyContent: 'center',
backgroundColor: 'white',
borderRadius: 30,
//marginLeft: 50, // -> if you uncomment this line, the translucid effect is ruined
}
}>
<MaskedView
style={{height: '100%', backgroundColor: 'yellow',
alignItems: 'stretch', justifyContent: 'center',
}}
maskElement={
<View style={{flex: 1, backgroundColor: 'transparent',
alignItems: 'center', justifyContent: 'center',
}}>
<View style={{width: 300, height: '100%', backgroundColor: 'black'}}/>
</View>
}
>
<LinearGradient start={{x: 0, y: 0}} end={{x: 1, y: 0}}
colors={['red', 'blue', 'green']}
style={{height: '100%'}}
/>
</MaskedView>
</View>
</TouchableOpacity>
</LinearGradient>
);
}
这里有个博览会小吃,以说明我的评论:https://snack.expo.io/SkCNR7Iqr
想法是,不要渲染然后隐藏内容,只是首先不要渲染任何内容。这将在按钮范围内呈现白色末端。包装器使用overflow: 'hidden'
来确保Touchable效果仅出现在有边界的borderRadius
内(在TouchableHighlight中更明显),并且将确保白色末端和其中的任何其他内容都将保持在有边界的borderRadius
内。
import * as React from 'react';
import { Text, View, StyleSheet, TouchableOpacity } from 'react-native'
import { LinearGradient } from 'expo-linear-gradient'
export default class App extends React.Component {
render() {
return (
<LinearGradient
start={{ x: 0, y: 0 }}
end={{ x: 1, y: 0 }}
colors={['red', 'blue', 'green']}
style={styles.gradient}>
<View style={styles.wrapper}>
<TouchableOpacity style={styles.touch}>
<View style={styles.end} />
<View style={styles.content} />
<View style={styles.end} />
</TouchableOpacity>
</View>
</LinearGradient>
);
}
}
const styles = StyleSheet.create({
gradient: {
flex: 1,
justifyContent: 'center'
},
wrapper: {
height: 100,
borderRadius: 30,
overflow: 'hidden',
marginLeft: 50,
flexDirection: 'row',
},
touch: {
flexDirection: 'row',
flex: 1,
},
end: {
width: 50,
backgroundColor: 'white',
height: '100%',
},
content: {
flex: 1,
}
});