RN Image and ImageBackground

1. Basic usage of Image component

1.1 Load image from current project

To add a static image to your app, just place the image file somewhere in your code folder and reference it like this:

<Image source={require('./my-icon.png')} />  即:

            <View style={styles.container}>
                {/*Load image from project*/}
              <Text>Load image from project</Text>
              // Specify width and height in imageStyle
              <Image source={require('./img/icon.png')} style={styles.imageStyle} />

The search of the image resource file is similar to that of the JS module, which will search relative to the current js file path according to the filled image path.

     In addition, React Naive's Packager will select the corresponding file according to the platform, for example: my_icon.ios.png and my_icon.android.png two files (named android or ios), will select the corresponding file according to the android or ios platform respectively.

You can also use filename suffixes like @2x, @3x to provide images for different screen resolutions. For example, the following code structure:
.
├── button.js
└── img
    ├── [email protected]
    └── [email protected]
and button.js has this code:

<Image source={require ('./img/check.png')} />
Packager will package all images and provide corresponding resources according to the screen precision. For example, the iPhone 5s will use [email protected], while the Nexus 5 will use [email protected]. If no image fits the screen resolution, the closest one is automatically selected.
Note: If the packager is running when you add the image, you may need to restart the packager in order to import the newly added image correctly.

This will bring some of the following benefits:

Consistent file system for iOS and Android. Images and JS code are in the same folder, so that components can include their own images without having to set them up separately. Global naming is not required. You don't have to worry about conflicting image names anymore. Only images that are actually used (i.e. required) will be packaged into your app. Now during development, adding and modifying images does not need to be recompiled, just refresh your emulator like modifying the js code. Compared with accessing network images, Packager can know the size of the image, and there is no need to declare the size again in the code. Components or libraries distributed via npm can now include images.

Another way of writing:

// mistake
let icon = this.props.active ? 'my-icon-active' : 'my-icon-inactive';
<Image source={require('./' + icon + '.png')} />

// correct
let icon = this.props.active ? require('./my-icon-active.png') : require('./my-icon-inactive.png');
<Image source={icon} />

1.2 Load and use the pictures in the APP

<Image source={{uri: 'app_icon'}} style={{width: 40, height: 40}} />


{/*Load image from resource bundle*/}
 <Text>2. Load pictures from APP</Text>
 <Image source={{uri:'icon_a'}} style={styles.imageStyle} />

Use image resources that have been packaged in the APP (for example: xcode asset folder and Android drawable folder)

Note: This approach does not have any security checks. You need to make sure that the image actually exists in the app, and you need to specify the dimensions.

1.3 Loading pictures from the web

       Many image resources of the client are basically obtained through the network in real time. The writing method is different from the above method of loading local resource images. Here, you must specify the size of the image . The implementation is as follows

{/*Load image from network*/}
 <Text>3. Load pictures from the network</Text>
 <Image source={{uri: 'https://upload.wikimedia.org/wikipedia/commons/d/de/Bananavarieties.jpg'}}
        style={styles.imageStyle} />

1.4 Set the picture as the background

    <Image source={{uri:'https://upload.wikimedia.org/wikipedia/commons/d/de/Bananavarieties.jpg
'}} style={{flex:1,width:200, height:100, resizeMode: Image.resizeMode.stretch}}>

           <Text style={{marginTop: 60, backgroundColor: 'red'}}>The following is the background image</Text>

    </Image>

The ImageBackground control was added in rn version 0.46. When using Image after version 0.46, it cannot be used in nesting. ImageBackground solves this problem. Now if other components are nested in the label, a yellow box warning will now be reported. The use of ImageBackground is the same as that of Image, except that other components can be nested.

<ImageBackground
                    style={styles.newTaskHeader}
                    source={require("./../../img/task/xsrw-bg.png")}>
                    <Text style={styles.ntTitle}>Points are exchanged for coupons~</Text>

                    <Text style={styles.ntSubTitle}>Complete the task to get points, multiple coupons and gifts will not stop! </Text>
                </ImageBackground>

Question 1: On iOS, the default white background of Text will cover part of the image: as shown below


Solution:

Add a transparent background to ImageBackground

newTaskHeader: {
        height: 115,
        width: "100%",
        marginBottom: 10,
        justifyContent: "center",
        alignItems: "center",
        backgroundColor: "transparent"
        
    }

The effect after solving:


Question 2: The size of the picture must be specified when the picture is used as the background, otherwise it will not be displayed


Second, the common properties of the Image component

2.1 Attribute method

   onLayout(function)

   When the Image layout changes, this method will be called, and the calling code is: {nativeEvent: {layout: {x, y, width, height}}}.

   onLoad (function)

   When the image is loaded successfully, this method is called back

   onLoadEnd (function)

   When the image loading fails to call back this method, it does not matter whether the image is loaded successfully or failed

   onLoadStart (fcuntion)

   This method is called when the image starts to load

  resizeMode

   Zoom ratio, optional parameters ('cover', 'contain', 'stretch') When the size of the image exceeds the size of the layout, the image will be scaled or cropped according to the Mode setting

    A property like resizeMode, which is equivalent to setting the content mode of the image in OC.

 Image.resizeMode.cover: The image is centered, not stretched, and the excess part is truncated;

 Image.resizeMode.contain: The container fully accommodates the image, and the image is stretched in equal proportions;

 Image.resizeMode.stretch: The  image is stretched to fit the size of the container and may be deformed.

  source{uri:string}

   Refer to the marked image, the parameter can be a network url address or a local path


2.2 Style style attributes

  FlexBox supports flexbox style

  Transforms support property animation

  backgroundColor background color

  borderColor border color

  borderWidth border width

  borderRadius border rounded corners

  overflow sets the size of the image to exceed the container and can be displayed or hidden ('visible','hidden')

  tintColor color settings

  opacity set opacity 0.0 (transparent) - 1.0 (completely opaque)


Note on iOS border rounded corners
Please note that the following border rounded corner styles are currently not supported on iOS image components:
borderTopLeftRadius
borderTopRightRadius
borderBottomLeftRadius
borderBottomRightRadius



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324472062&siteId=291194637