如何在react native中添加模糊效果



如何在React Native中为视图添加模糊,就像我们将其应用于图像或BackgroundImage一样?如果视图具有使用RGBA的半透明背景,我也希望为其添加模糊。

样本代码

<ImageBackground style={styles.bg}>
<View style={styles.content} />
</ImageBackground>

const styles = StyleSheet.create({
bg: {
width: "100%",
height: "100%"
},
content:{
width: "70%",
height: "70%",
backgroundColor: "rgba(255,255,355,0.4)",
alignSelf: "center"
}
})

您可以使用不透明度

const styles = StyleSheet.create({
bg: {
width: “100%”,
height: “100%”, 
Opacity:0.5
},
content:{
width: “70%”,
height: “70%”,
backgroundColor: “rgba(255,255,355,0.4)”,
alignSelf: “center”
}

})

似乎您试图模糊图像上的元素。一个好主意是有两个图像,第一个将始终在背景中,第二个将是一个绝对位置的子图像在隐藏溢出的图像上查看。因此,您只需要确保此子图像的大小与背景中的图像完全相同,并且与绝对定位的视图的位置相反。

import React, { useState } from 'react';
import { Image, View } from 'react-native';
import yourAsset from 'your/asset/folder/file.jpg';
const ImageBlur = () => {
const [containerSize, setContainerSize] = useState({
height: undefined,
width: undefined,
});
return (
<View
onLayout={({ nativeEvent }) => {
setContainerSize({
width: nativeEvent.layout.width,
height: nativeEvent.layout.height,
});
}}
style={{
position: 'relative',
width: '100%',
aspectRatio: 16 / 9,
}}
>
<Image
style={{ position: 'absolute', height: '100%', width: '100%' }}
resizeMode="contain"
source={yourAsset}
/>
<View
style={{
backgroundColor: 'black',
width: 100,
height: 150,
left: 100,
top: 40,
overflow: 'hidden',
}}
>
<Image
blurRadius={10}
source={yourAsset}
style={{
width: containerSize.width,
height: containerSize.height,
left: -100,
top: -40,
opacity: 0.7,
}}
resizeMode="contain"
/>
{ any children here will be blurred }
</View>
</View>
);
};
export default ImageBlur;

我还写了一篇Medium文章,解释了这个概念,并创建了一个react原生模糊视图图像Github存储库,介绍了我是如何实现这个实现的,以及一些使用示例。此外,还有性能测试反馈。

最简单的方法是执行以下操作:

import React, { Component } from 'react';
import { View, Text, ImageBackground, StyleSheet } from 'react-native';
const  BlurImage = () => {
return (
<ImageBackground source={require('your picture')} style={styles.ImageBackground}>
<View style={styles.container}>
<Text style={styles.text}> CSS Tricks </Text>
<Text style={styles.text}>You can style your Text and View as you deem fit</Text>
</View>
</ImageBackground>
);
}
export default BlurImage;
const styles = StyleSheet.create({
ImageBackground: {
flex: 1,
width: null,
height: null,
},
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'rgba( 0, 0, 0, 0.6 )',
},
text: {
color: 'white',
fontSize: 24
}
});

最新更新