ImageBrowser.js 8.28 KB
/**
 * Created by Cassie on 18/06/15
 */
import React, {Component} from "react";
import {
    Animated,
    CameraRoll,
    Image,
    InteractionManager,
    Modal,
    StyleSheet,
    Text,StatusBar,
    TouchableOpacity,
    View
} from "react-native";
import Carousel from "react-native-looped-carousel";
import RNFS from "react-native-fs";
import {height, width, zoomH, zoomW} from "../../utils/getSize";
import {xnToast} from "../../utils/utils";

export default class ImageBrowser extends Component {
    constructor(props) {
        super(props);
        this.state = {
            imgList: [],//图片列表集合
            currentIndex: 0,
            bottom: new Animated.Value(-(320 / zoomH)),
            download: false,
            startDown: false,
            showSave:false,
            downloadProgress: 0
        };
    };

    componentWillMount() {
        this.currentIndex = this.props.currentIndex;
    }

    /*保存图片*/
    savePic() {
        InteractionManager.runAfterInteractions(() => {
            this.setState({
                startDown: true,
                download: false,
                downloadProgress: 0
            });
            let currentIndex = this.currentIndex;
            const filePath = this.props.imgList[currentIndex];
            const downloadPath = filePath + '?x-oss-process=image/resize,w_1000';
            const fileName = filePath.substring(filePath.lastIndexOf('/') + 1);
            const downloadDest = RNFS.CachesDirectoryPath + '/' + fileName;

            console.log(filePath);

            try {
                RNFS.downloadFile({
                    fromUrl: downloadPath,
                    toFile: downloadDest,
                    background: true,
                    progress: (progress) => {
                        this.setState({
                            downloadProgress: parseInt((progress.bytesWritten / progress.contentLength) * 100)
                        })
                    }
                }).promise.then((response) => {
                    this.setState({
                        download: true,
                    }, function () {
                        setTimeout(() => {
                            xnToast("已保存");
                            this.setState({
                                startDown: false,
                                download: false
                            })
                        }, 1000)
                    });
                    return CameraRoll.saveToCameraRoll(downloadDest, 'photo');
                }).catch((error) => {
                    this.setState({
                        startDown: false
                    });
                    console.log(error);
                    alert('保存图片出错,请稍后再试')
                });
            } catch (error) {
                this.setState({
                    startDown: false
                });
                alert(JSON.stringify(error))
            }
        })
    };

    componentWillUnmount() {
        this.setState = (state, callback) => {
            return;
        };
    };

     /*模态框取消操作*/
     closeModal() {
        this.setState({
            showSave: false,
            bottom: new Animated.Value(-(320 / zoomH))
        },function () {
            StatusBar.setBackgroundColor(global.homeColor);
        })
    };
     //打开弹窗
     openModal = () =>{
        this.setState({
            showSave: true
        });
        Animated.timing(
            this.state.bottom,
            {toValue: (0 / zoomH)}
        ).start();
    };

    //保存图片
    renderSaveView() {
        return (
            <Modal animationType={'none'} visible={this.state.showSave} transparent={true}
                onRequestClose={() => this.closeModal()}>
                <TouchableOpacity activeOpacity={1} style={styles.modalBg} onPress={() => this.closeModal()}>
                    <Animated.View style={{
                        width: '100%',
                        position: 'absolute',
                        bottom: this.state.bottom,
                    }}>
                        <TouchableOpacity
                            activeOpacity={0.8} style={styles.settingItem} onPress={() => {
                                this.savePic();
                                this.closeModal();
                            }}>
                            <Text style={{ fontSize: 18, color: '#000' }}>保存到手机</Text>
                        </TouchableOpacity>

                        <View style={{ width: '100%', backgroundColor: '#eee' }}>
                            <View style={{ width: '100%', backgroundColor: '#ddd', height: (5 / zoomH) }}></View>
                            <TouchableOpacity activeOpacity={0.8}
                                style={[styles.settingItem, { borderBottomWidth: 0 }]}
                                onPress={() => {
                                    this.closeModal()
                                }}>
                                <Text style={{ fontSize: 18, color: '#000' }}>取消</Text>
                            </TouchableOpacity>
                        </View>
                    </Animated.View>
                </TouchableOpacity>
            </Modal>
        );
    }

  setIndex(index){
    console.log('------2----'+index);
    this.props.callback(index);
  }
    render() {
        let _this = this;
        return (
            <View style={styles.background}>

                <TouchableOpacity activeOpacity={1} style={styles.viewBg} onPress={() => { }}>
                    <Carousel
                        style={{ flex: 1 }}
                        bullets={false}
                        isLooped={false}
                        autoplay={false}
                        currentPage={this.props.currentIndex}
                        onAnimateNextPage={(index) => {this.currentIndex = index;
                        this.setIndex(index)
                        }}
                        
                    >
                        {this.props.imgList.map((item, index) =>
                            <TouchableOpacity activeOpacity={1} key={index} style={{
                                flex: 1,
                                display: 'flex',
                                justifyContent: 'center',
                                alignItems: 'center'
                            }} onLongPress={() => {  this.openModal(); }}
                            onPress = {()=>{this.props.onClick(index)}}>
                                <Image
                                    style={{width:'100%', height:'100%'}}
                                                source={{uri: item+'?x-oss-process=image/resize,w_1000'}}
                                    resizeMode="contain" />
                            </TouchableOpacity>
                        )}
                    </Carousel>
                </TouchableOpacity>
                {this.renderSaveView()}
            </View>
        );
    }
}

const styles = StyleSheet.create({
    background: {
        backgroundColor: '#000',
        flex: 1
    },
    viewBg: {
        flex: 1
    },
    picItem: {
        width: '100%',
        height: (50 / zoomH),
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        borderStyle: 'solid',
        borderBottomColor: '#eee',
        borderBottomWidth: StyleSheet.hairlineWidth
    },
    delBtn: {
        width: (50 / zoomW),
        height: (45 / zoomH),
        marginTop: (1 / zoomH),
        marginRight: (1 / zoomW),
        display: 'flex',
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#ea281a',
        position: 'absolute',
        right: 0,
        borderRadius: 7
    },
    loadingBox: {
        width: (100 / zoomW),
        height: (120 / zoomH),
        backgroundColor: 'rgba(0,0,0,.5)',
        borderRadius: 8,
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center'
    },
    modalBg: {
        width: width,
        height: height,
        backgroundColor: 'rgba(0,0,0,.5)',
        display: 'flex',
        alignItems: 'center'
    },


    settingItem: {
        width: '100%',
        backgroundColor:'#eeeeee',
        height: (50 / zoomH),
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center'
    },
});