如何在react-native-charts-wrapper中设置放大?

时间:2018-05-22 13:29:34

标签: reactjs react-native

我正在做我的第一个React Native应用, 我正在使用react-native-charts-wrapper来显示图表。

我在屏幕上有一个按钮监听器(请参阅下面的代码注释// CHANGE ZOOM HERE),以便在我正在显示的图形中设置预定义的缩放。

我该怎么做? 有没有人有使用该库的经验?

这是我的屏幕:

import React, {Component} from 'react';
import {View, Text, StyleSheet, processColor} from 'react-native';
import { Button} from "native-base";

import {CombinedChart} from 'react-native-charts-wrapper';
import moment from 'moment';

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'stretch',
        backgroundColor: 'transparent',
        paddingTop:20
    }
});

var InsulinShort = [];
var InsulinLong = [];
var glocuseTests = [];
const injectionsCount = 1000;

for (var i = 1; i < injectionsCount; i++) {
    var random = Math.random();
    if (random <= 0.7) {
        var gloguseValue = Math.floor(Math.random() * 40) + 75;
        var gloguseposition =Math.random();
        glocuseTests.push({x:i+gloguseposition,y: gloguseValue, marker: "level: "+gloguseValue});
    }
}
for (var i = 1; i < injectionsCount; i++) {
    var random = Math.random();
    if (random <= 0.15) {
        var shortvalue = Math.floor(Math.random() * 16) + 1  ;
        var shortPosition = Math.round(Math.random() * 100) / 100;
        InsulinShort.push({x:i+shortPosition,y: shortvalue*20, marker: shortvalue+ " units of short insulin"});
    }else if (random <= 0.3) {
        var longePosition = Math.round(Math.random() * 10) / 10;
        var longvalue = Math.floor(Math.random() * 16) + 1;
        InsulinLong.push({x:i+longePosition,y: longvalue*20, marker: longvalue+ " units of long insulin"});
    }else{
    }
}
export default class LogGraph extends Component {

    constructor() {
        super();
        // var valueFormatter = new Array(3515599953920);

        this.state = {
            loading: true,
            days:1000,
            legend: {
                enabled: true,
                textSize: 18,
                form: 'SQUARE',
                formSize: 18,
                xEntrySpace: 10,
                yEntrySpace: 5,
                formToTextSpace: 5,
                wordWrapEnabled: true,
                maxSizePercent: 0.5
            },
            xAxis: {
                valueFormatter: [
                    '01/04/18',
                    '02/04/18',
                    '03/04/18',
                    '04/04/18',
                    '05/04/18',
                    '06/04/18',
                    '07/04/18',
                    '08/04/18',
                    '09/04/18',
                    '10/04/18',
                    '11/04/18',
                    '12/04/18',
                    '13/04/18',
                    '14/04/18',
                    '15/04/18',
                    '16/04/18',
                    '17/04/18',
                    '18/04/18',
                    '19/04/18',
                    '20/04/18',
                ],
                // valueFormatterPattern:'ssss',
                // limitLines:100,
                // drawLimitLinesBehindData:false,
                // avoidFirstLastClipping: false,
                textColor: processColor('#000'),
                gridColor: processColor('#000'),
                axisLineColor: processColor('#000'),
                drawGridLines:true,
                drawAxisLine:false,
                drawLabels:true,

                granularityEnabled: true,
                // granularity:1515599953920,
                granularity: 1,
                // granularity: 131096  ,
                position:'TOP',
                textSize: 10,
                labelRotationAngle:45,
                gridLineWidth: 1,
                axisLineWidth: 2,
                gridDashedLine: {
                    lineLength: 10,
                    spaceLength: 10
                },
                centerAxisLabels:false,
            },

            yAxis: {
                left: {
                    axisMinimum: 0,
                    axisMaximum: 400,
                    labelCount: 6,
                    labelCountForce: true,
                    granularityEnabled: true,
                    granularity: 5,
                },
                right: {
                    axisMinimum: 0,
                    axisMaximum: 20,
                    labelCount: 6, // 0 5 10 15 20 25 30
                    labelCountForce: true,
                    granularityEnabled: true,
                    granularity: 5,
                }
            },

            marker: {
                enabled: true,
                markerColor: processColor('#F0C0FF8C'),
                textColor: processColor('white'),
                markerFontSize: 18,
            },

            data: {
                barData: {
                    config: {
                        barWidth: 1 / 24 ,
                    },
                    dataSets: [{
                        values:InsulinLong,
                        label: 'Long Insulin',
                        config: {
                            drawValues: false,
                            colors: [processColor('#a2a4b2')],
                        }
                    },{
                        values:InsulinShort,
                        label: 'Short Insulin',
                        config: {
                            barShadowColor: processColor('red'),
                            highlightAlpha: 200,
                            drawValues: false,
                            colors: [processColor('#d0d5de')],
                        }
                    }]

                },
                lineData: {
                    dataSets: [{
                        values: glocuseTests,
                        label: 'Glucose Level',
                        config: {
                            drawValues: false,
                            colors: [processColor('#81d0fa')],
                            // mode: "CUBIC_BEZIER",
                            drawCircles: true,
                            lineWidth: 3,
                        }
                    }],
                },
            }
        };

    }

    creatList(logs){
        // var startTime = moment().millisecond();



        var list = [];

        var time = false;

        if (logs) {
            // console.log('firstLogDay',moment(firstLogDay).format('L'));
            let gloguseItems   = [];
            let shortItems     = [];
            let longItems      = [];
            let firstValidFlag = false;
            let firstLogTime;
            let lastLogTime;
            let days;
            let firstLogDate;
            let firstLogDayTime;
            lastLogTime        = logs[0].time;
            for (var i = logs.length-1; i >= 0; i--) {
                let item = logs[i];
                if ( !firstValidFlag &&  ['glucose', 'long', 'short'].indexOf(item.type) >= 0 )  {
                    // debugger;
                    firstValidFlag = true;
                    firstLogTime = logs[i].time;
                    days = Math.round((lastLogTime-firstLogTime)/(1000*60*60*24));
                    firstLogDate = moment(firstLogTime).format('YYYY-MM-DD');
                    // console.log('firstLogDate',firstLogDate);
                    firstLogDayTime = new Date(firstLogDate);
                    firstLogDayTime = firstLogDayTime.getTime() - (2*60*60*1000);
                    // console.log('firstLogDayTime',firstLogDayTime);
                }

                if (firstValidFlag) {

                    let logX = ( item.time - firstLogDayTime ) /  1000 / 60 / 60 /24;
                    // logX =  Math.round(logX * 10) / 10
                    if (logX) {
                        // logX = item.time;
                        // console.log(logX);
                        let logY = item.amount;
                        if (item.type !== 'glucose') {
                            if (item.type === 'short') {
                                shortItems.push({
                                    x: logX,
                                    y:  logY*20,
                                    marker: logY+ " units of short insulin" + moment(item.time).format('LLL')
                                })
                            }
                            if (item.type === 'long') {
                                longItems.push({
                                    x: logX,
                                    y:  logY*20,
                                    marker: logY+ " units of long insulin" +  moment(item.time).format('LLL')
                                })
                            }
                        }else{
                            if(item.type === 'glucose'){
                                gloguseItems.push({
                                    x: logX,
                                    y: parseInt(logY),
                                    marker: "level: "+ logY +  moment(item.time).format('LLL')
                                })
                            }
                        }
                    }
                }

            }
            let oldData = this.state.data;
            oldData.lineData.dataSets[0].values = gloguseItems;
            oldData.barData.dataSets[1].values = shortItems;
            oldData.barData.dataSets[0].values = longItems;
            let DayFlag = firstLogDate;
            let valueFormatter = [];
            valueFormatter.push(moment(DayFlag).format('DD/MM/YYYY'));
            for (let i = 0; i < days; i++) {
                DayFlag = moment(DayFlag).add(1, 'days');
                valueFormatter.push(DayFlag.format('DD/MM/YYYY'));
            }
            let xAxis = this.state.xAxis;
            xAxis.valueFormatter = valueFormatter;
            this.setState({
                data:oldData,
                days:days,
                xAxis:xAxis,
                loading:false
            });

        }else{
            this.setState({loading:false});
        }

    }
    componentDidMount() {

        this.creatList(this.props.logs);
    }

    zoomTwentyPressed() {
      console.log ("pressed 25");
    }

    zoomFiftyPressed() {
      console.log ("pressed 50");
    }

    zoomHundredPressed() {
      console.log ("pressed 100");
      // CHANGE ZOOM HERE

    }


    static displayName = 'Combined';

    handleSelect(event) {
        let entry = event.nativeEvent
        if (entry == null) {
            this.setState({...this.state, selectedEntry: null})
        } else {
            this.setState({...this.state, selectedEntry: JSON.stringify(entry)})
        }

        // console.log(event.nativeEvent)
    }

    render() {
        return (

            <View style={styles.container}>

                {
                    (this.state.loading) ? <Text>Loading</Text>:
                    <CombinedChart
                        data={this.state.data}
                        xAxis={this.state.xAxis}
                        yAxis={this.state.yAxis}
                        legend={this.state.legend}
                        onSelect={this.handleSelect.bind(this)}
                        onChange={(event) => console.log(event.nativeEvent)}
                        marker={this.state.marker}
                        animation={{durationY: 1000,durationX: 1000}}
                        maxVisibleValueCount={16}
                        autoScaleMinMaxEnabled={true}
                        zoom={{scaleX: Math.floor(this.state.days/12), scaleY: 1, xValue:  4, yValue: 4, axisDependency: 'LEFT'}}
                        style={styles.container}/>
                }

                <View style={styles.buttonWrap}>

                    <Button block light onPress={this.zoomTwentyPressed()} style={(this.state.view === 'graph')?styles.buttonStyleCurrent:styles.buttonStyle}>
                        <Text>x100</Text>
                    </Button>
                    <Button block light onPress={this.zoomFiftyPressed()} style={(this.state.view === 'graph')?styles.buttonStyleCurrent:styles.buttonStyle}>
                        <Text>x50</Text>
                    </Button>
                    <Button block light onPress={this.zoomHundredPressed()} style={(this.state.view === 'graph')?styles.buttonStyleCurrent:styles.buttonStyle}>
                        <Text>x25</Text>
                    </Button>

                </View>

            </View>


        );

    }
}

1 个答案:

答案 0 :(得分:0)

我只是以props选项的json格式放入了propdataZoom,这是我的例子

{
                grafica: true,
                option: {
                    title: {
                        text: ''
                    },
                    width: WIDTH - 100,
                    tooltip: {
                        trigger: 'axis'
                    },
                    xAxis: {
                        data: energiaV2.map(function (item) {
                            console.log(item.date, moment(item.date).format('hh:mm:ss'))
                            return moment(item.date).utc().calendar()//moment(item.date).utc().format('LL');//moment(item.date).utc().format('hh:mm:ss a');
                        }),
                        name: "dias",
                        nameLocation: 'middle',
                        nameGap: 30,
                        splitLine: {
                            show: false
                        }
                    },
                    yAxis: {
                        splitLine: {
                            show: false
                        },
                        name: "kWh",
                        nameLocation: 'middle',

                    },
                    /* toolbox: {
                        left: 'center',
                        feature: {
                            dataZoom: {
                                yAxisIndex: 'none'
                            },
                            restore: {},

                        }
                    }, */
                    dataZoom: [{
                        type: 'inside',
                    }, {
                        start: 5,
                        end: 10,
                        handleIcon: 'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
                        handleSize: '80%',
                        handleWidth:30,
                        handleStyle: {
                            color: '#fff',
                            shadowBlur: 3,
                            shadowColor: 'rgba(0, 0, 0, 0.6)',
                            shadowOffsetX: 2,
                            shadowOffsetY: 2,


                        }
                    }],

                    series: [{
                        name: 'Activa kWh',
                        type: 'line',
                        data: energiaV2.map(function (item) {
                            return Math.floor(item.value * 100) / 100;
                        }),

                    },
                    {
                        name: 'Inductiva kVAr',
                        type: 'line',
                        data: energiaV2reactive.map(function (item) {
                            return Math.floor(item.value * 100) / 100;
                        }),

                    },
                    {
                        name: 'Capacitiva kVArhR',
                        type: 'line',
                        data: energiaV2inductive.map(function (item) {
                            return Math.floor(item.value * 100) / 100;
                        }),

                    },
                    ],
                    color: ['rgb(253, 180, 59)', 'rgb(240, 94, 54)', 'rgb(0, 128, 35)']


                },

                grafica: true,
            })