Home Web Front-end JS Tutorial Detailed introduction to ReactNative Image component

Detailed introduction to ReactNative Image component

Aug 11, 2017 am 10:22 AM
image detailed

This article mainly introduces the detailed explanation of the use of ReactNative Image component. The editor thinks it is quite good. Now I will share it with you and give it as a reference. Let’s follow the editor and take a look.

It’s been quite interesting to learn ReactNative recently. During the learning process, I found that the content of articles written by some people on the Internet is outdated. This is mainly because the version of ReactNative is upgraded too quickly. If you now read an article written in 16 or even 15 years, and compare the knowledge points with official documents, you will be surprised. Therefore, I advise students who want to learn ReactNative to choose learning materials based on official documents and official demos, and other materials as supplements.

Image component

In ReactNative, Image is a component used to display images, which has the same effect as the ImageView control when developing Android. It can be used to display network images, static resources, temporary local images, and images on the local disk (such as photo albums), etc. Proper use of Image components can convey information to users more vividly and intuitively.

Image component loads static resources in the project

The static resources here refer to the images in the js part that are loaded, and are not resources under native applications of android and ios file, to load this kind of image resource, we introduce the image file through require('the path of the image file relative to this file directory') and set it to the source attribute of the Image component. As follows


 <Image
 style={styles.image}
  //  ./表示当前文件目录 ../ 父目录
   source={require(&#39;./reactlogo.png&#39;)}
 />
Copy after login

One thing to note is that the path cannot be spliced ​​with strings in the above require, otherwise a loading error will be reported.

Loading native image resources

The native resources mentioned here refer to the drawable in the res directory when we develop Android, or the mipmap directory. And the corresponding resource directory under ios. Loading this kind of image resources is a little different from loading resources in the project. Here we take android as an example. Load the file under drawable as follows


##

 <Image
 source={{uri: &#39;launcher_icon&#39;}}
 style={{width: 38, height: 38}}
/>);
Copy after login

In addition to loading through the above method, You can specify the image width and height in the nativeImageSource in the following way


<Image
 source={nativeImageSource({
 android: &#39;launcher_icon&#39;,
 width: 96,
 height: 96
  })}
/>
Copy after login

. If you set the width and height in the style attribute of the image component at the same time, the final width and height will be based on the style medium width. Whichever is higher. The image resources under drawable are loaded by default above. If you want to load the resources in mipmap, you can do as follows


<Image
 source={nativeImageSource({
 android: &#39;mipmap/launcher_icon&#39;,
 width: 96,
 height: 96
 })}
/>
Copy after login

Through the above method, we can load the image. If The pictures newly added to the drawable need to be recompiled and run, otherwise they will not take effect.

Loading network images


 <Image
 source={{uri: &#39;https://facebook.github.io/react/img/logo_og.png&#39;}}
 style={{width: 38, height: 38}}
/>);
Copy after login

One thing to note about loading network images is that you need to specify the width and height of the style, otherwise The image will not be displayed (the default width and height are not set to 0 anymore).

Commonly used attributes of the Image component

style:

  • width: Set the width of the image

  • height: Set the height of the picture

  • borderWidth: Set the border width

  • borderColor: Set the border Color

  • backgroundColor: Set the background color (this property is generally used when some pictures have transparent backgrounds)

  • opacity: Opacity, The value is between 0 and 1, where 1 means opaque and 0 means transparent.

  • tintColor: Colorize the picture. This attribute is more useful. For example, a black and white picture will often turn into another color picture when clicked. This attribute can be used at this time

blurRadius Sets the blur radius of the image, which can blur the image

defaultSource Sets the default image for the image, which is used to display the image before the network is successfully loaded. (ios support)

source

Above we introduced the source attribute to load different image resources, but there is another one we haven’t mentioned yet. It can receive an array as a parameter, so that it can be loaded according to the component. The width and height automatically load the image with matching width and height. The usage is as follows



 <Image
  style={{flex: 1}}
  source={[
       {uri: &#39;https://facebook.github.io/react/img/logo_small.png&#39;, width: 38, height: 38},
       {uri: &#39;https://facebook.github.io/react/img/logo_small_2x.png&#39;, width: 76, height: 76},     
        uri: &#39;https://facebook.github.io/react/img/logo_og.png&#39;, width: 400, height: 400}
      ]}
 />
Copy after login

resizeMode

This attribute is used to set the zoom mode of the image, the corresponding value is as follows

  • cover: Maintain the aspect ratio of the image until the width and height are greater than or equal to the size of the container view (refer to the effect below)

  • contain: Maintain the aspect ratio of the image Under the premise, scale the image until the width and height are less than or equal to the size of the container view

  • stretch: Stretch the image without maintaining the aspect ratio until the width and height just fill the container

  • center Center without stretching

  • repeat: Repeat tile the image until it fills the container. The image will maintain its original size. (iOS)


## Supports GIF and WebP format images on Android

Default Android does not support GIF and WebP formats. You need to add the corresponding dependencies as needed in the build.gradle file.

dependencies {
 // If your app supports Android versions before Ice Cream Sandwich (API level 14)
 compile &#39;com.facebook.fresco:animated-base-support:1.0.1&#39;

 // For animated GIF support
 compile &#39;com.facebook.fresco:animated-gif:1.0.1&#39;

 // For WebP support, including animated WebP
 compile &#39;com.facebook.fresco:animated-webp:1.0.1&#39;
 compile &#39;com.facebook.fresco:webpsupport:1.0.1&#39;

 // For WebP support, without animations
 compile &#39;com.facebook.fresco:webpsupport:1.0.1&#39;
}
Copy after login

If you use ProGuard while using GIF, you need to add the following rules to proguard-rules.pro

-keep class com.facebook.imagepipeline.animated.factory.AnimatedFactoryImpl {
 public AnimatedFactoryImpl(com.facebook.imagepipeline.bitmaps.PlatformBitmapFactory, com.facebook.imagepipeline.core.ExecutorSupplier);
}
Copy after login

ImageBackground

该组件是Image组件的扩展,它支持嵌套组件。如在图片上显示一个文本,则可以通过如下实现


      <ImageBackground
        style={{width: 100, height: 100, backgroundColor: &#39;transparent&#39;}}
        source={{uri: &#39;https://facebook.github.io/react/img/logo_og.png&#39;}}
      >
        <Text style={styles.nestedText}>
          React
        </Text>
      </ImageBackground>
Copy after login

实现效果图如下,一般的我们可以嵌套ActivityIndicator来提示用户图片正在加载,当加载完成隐藏此控件。


网络图片加载监听

对于网络图片的加载,ReactNative提供了一些属性用于图片不同加载时期的监听。

  • onLoadStart:图片开始加载时调用

  • onLoad:图片加载完成时调用,此时图片加载成功

  • onLoadEnd:加载结束后调用,与onLoad不同的是不论成功还是失败,此回调函数都会被执行。

使用方法如下


      <Image
        source={{uri:&#39;https://facebook.github.io/react/img/logo_og.png&#39;}}
        style={[styles.base, {overflow: &#39;visible&#39;}]}
        onLoadStart={() => console.log(&#39;onLoadStart&#39;)}
        onLoad={(event) => console.log(&#39;onLoad&#39;) }
        onLoadEnd={() => console.log(&#39;onLoadEnd&#39;)}
      />
Copy after login

对于iOS,还提供了加载进度的回调函数onProgress


<Image
  style={styles.image}
  onProgress={(event) => {
   console.log(&#39;onProgress&#39;)
   this.setState({
    progress: Math.round(100 * event.nativeEvent.loaded / event.nativeEvent.total)
  })}}/>
Copy after login

可以通过参数event.nativeEvent.loaded获取已经加载的大小,通过event.nativeEvent.total获取图片的总大小。

不仅如此,ReactNative还提供了预加载图片函数prefetch(url: string),它可以将图片下载到磁盘缓存


var prefetchTask = Image.prefetch(&#39;https://facebook.github.io/react/img/logo_og.png&#39;);
prefetchTask.then(() => {
  //此处可设置状态,显示Image组件。此时组件会使用预加载的图片信息。而不用再次加载
  console.log(&#39;加载图片成功&#39;)
}, error => {
  console.log(&#39;加载图片失败&#39;)
})
Copy after login

好了,今天就介绍到这里,文中若有错误的地方欢迎指正,再次感谢。文中一些示例源码,可前往GitHub在线预览,也可以下载项目学习其他组件。

The above is the detailed content of Detailed introduction to ReactNative Image component. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use Bing Image Creator for free How to use Bing Image Creator for free Feb 27, 2024 am 11:04 AM

This article will introduce seven ways to get high-quality output using the free BingImageCreator. BingImageCreator (now known as ImageCreator for Microsoft Designer) is one of the great online artificial intelligence art generators. It generates highly realistic visual effects based on user prompts. The more specific, clear, and creative your prompts are, the better the results will be. BingImageCreator has made significant progress in creating high-quality images. It now uses Dall-E3 training mode, showing a higher level of detail and realism. However, its ability to consistently produce HD results depends on several factors, including fast

How to delete images from Xiaomi phones How to delete images from Xiaomi phones Mar 02, 2024 pm 05:34 PM

How to delete images on Xiaomi mobile phones? You can delete images on Xiaomi mobile phones, but most users don’t know how to delete images. Next is the tutorial on how to delete images on Xiaomi mobile phones brought by the editor. Interested users can come and join us. Let's see! How to delete images on Xiaomi mobile phone 1. First open the [Album] function in Xiaomi mobile phone; 2. Then check the unnecessary pictures and click the [Delete] button in the lower right corner; 3. Then click [Album] at the top to enter the special area , select [Recycle Bin]; 4. Then directly click [Empty Recycle Bin] as shown in the figure below; 5. Finally, directly click [Permanent Delete] to complete.

Imagemagic installation Centos and Image installation tutorial Imagemagic installation Centos and Image installation tutorial Feb 12, 2024 pm 05:27 PM

LINUX is an open source operating system. Its flexibility and customizability make it the first choice of many developers and system administrators. In the LINUX system, image processing is a very important task, and Imagemagick and Image are Two very popular image processing tools, this article will introduce you to how to install Imagemagick and Image in Centos system, and provide detailed installation tutorials. Imagemagic installation Centos tutorial Imagemagick is a powerful image processing toolset, which can perform various image operations under the command line. The following are the steps to install Imagemagick on Centos system: 1

Detailed instructions for using cookies Detailed instructions for using cookies Feb 22, 2024 pm 12:21 PM

Cookies are a common web technology used to store information about users' personal preferences and behavior on websites. In today's digital age, almost all websites use cookies to provide personalization and a better user experience. This article will introduce the use of cookies in detail to help users better understand and master this technology. First, let's understand the basic concept of cookies. Cookies are small text files stored on the user's browser by the website and contain information about the user's visit to the website.

imagefilledrectangle() function in PHP imagefilledrectangle() function in PHP Aug 30, 2023 am 09:05 AM

The imagefilledrectangle() function draws a filled rectangle. Syntax imagefilledrectangle($img,$x1,$y1,$x2,$y2,$color) Parameters image Use imagecreatetruecolor() to create a blank image. x1The x coordinate of point 1. y1 The y coordinate of point 1. x2 x coordinate of point 2. y2 The y coordinate of point 2. color fill color. Return value imagefilledrectangle() function returns successfully

Detailed explanation of what is the shortcut key of win7 task manager Detailed explanation of what is the shortcut key of win7 task manager Jul 12, 2023 pm 09:49 PM

The task manager is a common program that we usually use on the computer. You can see all the commonly used programs on the computer. A friend wants to open the win7 task manager, but he doesn’t know what the shortcut key for the win7 task manager is. I will teach you below. Here's how to quickly open the win7 task manager. 1. Press and hold the Ctrl+Alt+Delete keys on the keyboard, and then choose to run the task manager. 2. Another shortcut key can also open the task manager. Press and hold Esc+shift+Ctrl to open the task manager. 3. Press the Win+R keys to open the run window, type C:\Windows\system32\taskmgr.exe on the page, and press Enter. You can also

Detailed tutorial on how to reinstall win7 system by yourself Detailed tutorial on how to reinstall win7 system by yourself Jul 18, 2023 pm 06:17 PM

How to reinstall win7 system by yourself? The system is prone to malfunctions after being used for a long time. Many win7 users like to reinstall the system by themselves. While choosing to use a USB flash drive to install, we can also choose to download and reinstall the system when the computer is running normally. But what do you do? What about reinstalling the win7 system? Next, the editor will tell you the detailed steps of reinstalling the win7 system. Friends who are interested come and take a look! 1. In the first step, we open the browser, search for the download and installer, reinstall the system software with one click, and select the win7 system. 2. After the software download is completed, click to restart the computer. 3. Enter the startup page and select the second option zhuangjibape to enter. 4. After entering the pe system, wait for the installation and reinstall the system online.

Simple and detailed win7 installation method Simple and detailed win7 installation method Jul 14, 2023 pm 10:13 PM

The win10 system is the current mainstream operating system, so when buying a computer, the win10 system is usually pre-installed. However, some friends prefer to use the win7 system, but do not know how to install the win7 system. So the simple and detailed win7 installation method is what? Therefore, this issue will bring you the installation diagram of win7 system on the issue of how to install win7 system. The simple and detailed win7 installation method is as follows: 1. Search the official website of Kaka Installer, download the Kaka Installer tool after entering, back up important files on the system C drive, open the Kaka Installer and click to reinstall the system online. 2. Next, you can choose the original Microsoft win7 system and click below to install this system. 3. Select the third-party software that needs to be installed and click Next.

See all articles