Home  >  Article  >  Web Front-end  >  Introduction to Image control in React-native

Introduction to Image control in React-native

零下一度
零下一度Original
2017-06-29 11:24:591857browse
1. Introduction

A React component used to display many different types of images, including network images, static resources, temporary local images, and Pictures on local disk (such as photo album), etc.
Starting from version 0.14, React Native provides a unified way to manage images in iOS and Android applications. To add a static image to your App, just place the image file somewhere in the code folder such as img, and then reference it like this:
<Image source= {require('./img/check.png')} />
If you have my-icon.ios.png and my-icon.android.png, Packager Different files are selected depending on the platform.
You can also use file name suffixes such as @2x and @3x to provide images for different screen resolutions. For example, the following code structure:
------ button.js
------ img
------ |-------- check@2x.png
------ |-------- check@3x.p
Packager will package all images and provide corresponding resources according to screen accuracy. For example, iPhone 5s will use check@2x.png, while Nexus 5 will use check@3x.png. If there is no image that exactly meets the screen resolution, the closest image will be automatically selected.
[Note] If the packager is running when you add images, you may need to restart the packager so that the newly added images can be correctly introduced. In order for the new image resource mechanism to work properly, the image name in require must be a static string and cannot be spliced ​​in require.
//Correct
<Image source={require('./my-icon.png')} />
Error
var icon = this.props.active ? 'my-icon-active' : 'my-icon-inactive';
<Image source={require('./' + icon + '.png')} />

Using the image resources of hybrid App

If you are writing a hybrid App (part of the UI uses React Native, and the other part uses platform native code), you can also use the image resources that have been packaged into the App. Image resources (packaged through Xcode's asset category or Android's drawable folder):
<Image source={{uri: 'app_icon'}} style={{width: 40, height: 40}} />
Note: This approach does not have any security checks. You need to ensure that the image actually exists in the application yourself, and also need to specify the size.

Load network images

Different from static resources, you need to manually specify the size of the image.
//Correct
<Image source={{uri: 'https://facebook.github.io/react/img/logo_og. png'}} style={{width: 400, height: 400}} />
//Error
<Image source={{ uri: 'https://facebook.github.io/react/img/logo_og.png'}} />

Why not specify the size in all cases

In the browser, if you do not specify the size of the image, the browser will first render a 0x0 size The element takes the place, then downloads the image, and then renders the image based on the correct size after the download is completed. The biggest problem with this is that the UI will jump up and down during the image loading process, making the user experience very bad.
In React This behavior is intentionally avoided in Native. This will require developers to do more work to know the size (or aspect ratio) of the remote image in advance, but we believe this can lead to a better user experience. However, when reading images from packaged application resource files (using the require('image!x') syntax), there is no need to specify the size, because their size is known immediately when loading.
For example, the actual output result of such a reference require('image!logo') may be:
{"__packager_asset":true,"isStatic" :true,"path":"/Users/react/HelloWorld/iOS/Images.xcassets/react.imageset/logo.png","uri":"logo","width":591,"height":573}

Realizing background images through nesting

Similar to the background-image in the web, just create it simply An component, and then embed the sub-component that requires a background image into it
return ( <Image source={...}> <Text>Inside</Text> </Image> );

Support GIF and WebP format images on Android

dependencies {
// If you need to support versions before Android4.0 (API level 14)
compile 'com.facebook.fresco:animated-base-support:0.11.0'

// If you need to support GIF animation
compile 'com.facebook.fresco:animated-gif:0.11.0'

// If you need to support WebP format, including WebP animations
compile 'com.facebook.fresco:animated-webp:0.11.0'
compile 'com.facebook.fresco:webpsupport:0.11.0'

// If you only need to support WebP format without moving images
compile 'com .facebook.fresco:webpsupport:0.11.0'
}
If you are using GIF and also using ProGuard, you need to set it in proguard-rules.pro Add the following rules:
-keep class com.facebook.imagepipeline.animated.factory.AnimatedFactoryImpl { public AnimatedFactoryImpl(com.facebook.imagepipeline.bitmaps.PlatformBitmapFactory, com.facebook.imagepipeline .core.ExecutorSupplier); }

2. Attributes

##1.onLayout (function) When the Image layout changes, this method will be called. The calling code is:
{nativeEvent: {layout: {x, y, width, height}}}.
2.onLoad (function): When the image is loaded successfully, call back this method
3.onLoadEnd (function): This method is called back when the image fails to load, regardless of whether the image is loaded successfully or failed
4.onLoadStart (fcuntion): When the image starts to load This method is called when
5.resizeMode scaling ratio, optional parameters ('cover', 'contain', 'stretch') When the size of the image exceeds the size of the layout, the Mode will be set according to Scale or crop the image
cover: Scale the image while maintaining the aspect ratio of the image until the width and height are greater than or equal to the size of the container view (if the container has padding, then accordingly minus). Annotation: In this way, the image completely covers or even exceeds the container, leaving no blank space in the container.
contain: Scale the image while maintaining the aspect ratio of the image until the width and height are less than or equal to the size of the container view (if the container has padding, subtract accordingly). Translation Note: In this way, the image is completely wrapped in the container, and there may be some blank space in the container.
stretch: Stretch the image without maintaining the aspect ratio until the width and height just fill the container.
repeat: Repeat tiles until the container is filled. The image will maintain its original size. Available for iOS only.
center: Centered without stretching.
6.source {uri:string} refers to the marked image. This parameter can be a network URL address or a local (use require (relative path) to reference) path

3. Style

1.FlexBox supports flexible box style
2.Transforms supports attribute animation 3.resizeMode setting Zoom mode
4.backgroundColor background color
5.borderColor border color 6.borderWidth border width
7.borderRadius border rounded corner
8.overflow If the image size exceeds the container, you can set the display or hide ('visible', 'hidden')
9.tintColor color setting 10.opacity setting Transparency 0.0 (transparent)-1.0 (completely opaque)

四. 示例

加载网路图片的例子
class MyImageDemo extends Component {    render() {        return (            <View style={[styles.flex,{marginTop:45}]}>                <MyImage imgs={imgs}> </MyImage>            </View>        );    } }
class MyImage extends Component {    constructor(props) {        super(props);        this.state = {            count: 0,//图片索引            imgs: this.props.imgs,        };    }
render() {        return (            <View style={[styles.flex,{alignItems:'center'}]}>                <View style={styles.image}>                    <Image style={styles.img}                           resizeMode='contain'                           source={{uri:this.state.imgs[this.state.count]}}/>                </View>                <View style={styles.btns}>                    <TouchableOpacity onPress={this.onPrevious.bind(this)}><View                        style={styles.btn}><Text>上一张</Text></View></TouchableOpacity>
<TouchableOpacity onPress={this.onNext.bind(this)}><View style={styles.btn}><Text>下一张</Text></View></TouchableOpacity>                </View> </View>        );    }
onPrevious() {        var count = this.state.count;        count--;        if (count >= 0) {            this.setState({                count: count,            });        }    }    onNext() {        var count = this.state.count;        count++;        if (count < this.state.imgs.length) {            this.setState({                count: count,            });        }    } }
const styles = StyleSheet.create({        flex: {            flex: 1,        },        image: {            width: 300,            height: 200,            borderWidth: 1,            justifyContent: 'center',            alignItems: 'center',            borderColor: '#ccc',            borderRadius: 5,        },        img: {            width: 200,            height: 150,        },        btn: {            width: 60,            height: 35,            borderWidth: 1,            borderColor: '#ccc',            borderRadius: 3,            justifyContent: 'center',            alignItems: 'center',            marginRight: 30,        },        btns: {            flexDirection: 'row',            marginTop: 20,            justifyContent: 'center'        }    } );

效果


Image_first.jpeg


点击下一张


Image_second.jpeg


点击下一张


Image_third.jpeg

记录我自己的RN学习之路,纯属自己增值,有什么不对的地方,一起讨论进步

The above is the detailed content of Introduction to Image control in React-native. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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