如何重复模式图像以在React Native中创建背景?

Shi*_*oim 13 ios reactjs react-native

我正在为iOS构建一个简单的ReactNative应用程序,我正在尝试添加背景图像.似乎没有backgroundImage标签,虽然我设法在页面上显示一次图像,但我不能像在CSS中一样在整个页面中重复它.有什么建议?

Sud*_*Plz 16

iOS版

iOS上的图像现在包含repeat resizeMode属性.

像这样使用它:

<Image
    src={/* whatever your source is */}
    resizeMode="repeat"
/>
Run Code Online (Sandbox Code Playgroud)

Android的

2018年6月更新:

从react-native 0.56 Android映像开始也支持repeat.(https://github.com/facebook/react-native/commit/0459e4ffaadb161598ce1a5b14c08d49a9257c9c)

2018年6月之前:

Android上,repeat属性不起作用:你将不得不使用像Shiraman的答案

外部库:

现在这个伟大的项目名为react-native-bgimage(由Alex Melanchenko创建),效果很好:

这是我如何使用它:

import RepeatingPattern from 'react-native-bgimage';

<RepeatingPattern
    drawable="block_pattern"
    style={{
      height: 45,
    }}
/>
Run Code Online (Sandbox Code Playgroud)

然后我在中添加一个模式png文件 android/app/src/main/res/drawable/block_pattern.png


小智 10

尽管这个问题已经很老了,我还是想把我的两分钱放进去。它也可以通过<ImageBackground>组件(参考)来完成。

例子:

<ImageBackground source={require('./path/to/image.png')} style={{width: '100%', height: '100%'}} imageStyle={{resizeMode: 'repeat'}}>
  // Your inside content goes here
</ImageBackground>
Run Code Online (Sandbox Code Playgroud)

不要忘记在文件的开头导入组件,例如 import { ImageBackground } from 'react-native';

  • 这里需要注意的是,我们不能在当前版本的 RN (v0.62.2) 中使用 .svg 图像 (2认同)

Aak*_*del 5

我想延长斯里兰卡的答案.要将重复的图像作为背景,您需要执行添加新视图并使其位置绝对和背景透明的附加步骤,然后添加其中的所有其他组件.

var React = require('react-native');
var Dimensions = require('Dimensions');

var {
  Image
} = React;

var RepeatImage = React.createClass({
    render: function(){
    var images = [],  
    imgWidth = 7,
    winWidth =Dimensions.get('window').width;

    for(var i=0;i<Math.ceil(winWidth / imgWidth);i++){
        images.push((
           <Image source={{uri: 'http://xxx.png'}} style={} />
        ))
    }

    return (
        <View style={{flex:1,flexDirection:'row'}}>
        {
         images.map(function(img,i){
         return img;
         })
        }
          <View style={{position: 'absolute', top: 0, bottom: 0, left: 0, right: 0}}>
              {/*Place all you compoents inside this view*/}
          </View>
        </View>
    )
  }
});
Run Code Online (Sandbox Code Playgroud)


Sri*_*man 0

你不能像React Native中的CSS那样重复背景图片。但是,您可以通过迭代图像来实现它,例如

var React = require('react-native');
var Dimensions = require('Dimensions');

var {
  Image
} = React;

var RepeatImage = React.createClass({
    render: function(){
    var images = [],  
    imgWidth = 7,
    winWidth =Dimensions.get('window').width;

    for(var i=0;i<Math.ceil(winWidth / imgWidth);i++){
        images.push((
           <Image source={{uri: 'http://xxx.png'}} style={} />
        ))
    }

    return (
        <View style={{flex:1,flexDirection:'row'}}>
        {
         images.map(function(img,i){
         return img;
         })
        }
        </View>
    )
  }
});
Run Code Online (Sandbox Code Playgroud)

  • 这是可行的记忆吗? (8认同)