至少有一种方法可以让它在 ios 和 android 上看起来像这样:
想法:
这个想法是在 Text 对象上使用多个阴影。我们可以通过用 View 包裹 Text 组件并使用不同的阴影多次克隆相同的 Text 对象来使它们使用不同的方向来实现。
实施:
这是包装器组件的代码:
import * as React from "react";
import { StyleSheet, View } from "react-native";
import { Children, cloneElement, isValidElement } from "react";
type Props = {
children: any,
color: string,
stroke: number
}
const styles = StyleSheet.create({
outline: {
position: 'absolute'
},
});
export class TextStroke extends React.Component<Props> {
createClones = (w: number, h: number, color?: string) => {
const { children } = this.props;
return Children.map(children, child => {
if (isValidElement(child)) {
const currentProps = child.props as any;
const currentStyle = currentProps ? (currentProps.style || {}) : {};
const newProps = {
...currentProps,
style: {
...currentStyle,
textShadowOffset: {
width: w,
height: h
},
textShadowColor: color,
textShadowRadius: 1
}
}
return cloneElement(child, newProps)
}
return child;
});
}
render() {
const {color, stroke, children} = this.props;
const strokeW = stroke;
const top = this.createClones(0, -strokeW * 1.2, color);
const topLeft = this.createClones(-strokeW, -strokeW, color);
const topRight = this.createClones(strokeW, -strokeW, color);
const right = this.createClones(strokeW, 0, color);
const bottom = this.createClones(0, strokeW, color);
const bottomLeft = this.createClones(-strokeW, strokeW, color);
const bottomRight = this.createClones(strokeW, strokeW, color);
const left = this.createClones(-strokeW * 1.2, 0, color);
return (
<View>
<View style={ styles.outline }>{ left }</View>
<View style={ styles.outline }>{ right }</View>
<View style={ styles.outline }>{ bottom }</View>
<View style={ styles.outline }>{ top }</View>
<View style={ styles.outline }>{ topLeft }</View>
<View style={ styles.outline }>{ topRight }</View>
<View style={ styles.outline }>{ bottomLeft }</View>
{ bottomRight }
</View>
);
}
}
如果文字不大,也可以只用4个方向而不是8个方向来提高性能:
<View>
<View style={ styles.outline }>{ topLeft }</View>
<View style={ styles.outline }>{ topRight }</View>
<View style={ styles.outline }>{ bottomLeft }</View>
{ bottomRight }
</View>
用法:
<TextStroke stroke={ 2 } color={ '#000000' }>
<Text style={ {
fontSize: 100,
color: '#FFFFFF'
} }> Sample </Text>
</TextStroke>
您还可以在内部使用多个 Text 对象,因为包装器会复制所有对象。
性能:
我尚未检查此解决方案的性能。由于我们多次复制文本,它可能不是很好。
问题:
需要小心stroke 值。使用较高的值,阴影的边缘将可见。如果您确实需要更宽的描边,可以通过添加更多图层来覆盖不同的阴影方向来解决此问题。