2016-07-07 64 views

回答

1

酷的項目。一定要分享你創造的東西。我認爲其他人也會覺得這很有用。不幸的是,我還沒有看到它。如果我這樣做了,我會先看看jQuery插件是如何做到的。像https://github.com/magicismight/react-native-svg可以幫助您繪製形狀。希望我能更有幫助。祝你好運!

14

最近我一直在與react-native-svg合作,我認爲這太棒了--SVG和React是在geek-heaven中製作的一個匹配,只需創建自定義用戶界面,無需下拉到原生繪圖碼。

這裏有一個小CircularSlider組件實現上述你:

import React,{Component} from 'react' 
import {PanResponder,View} from 'react-native' 
import Svg,{Path,Circle,G,Text} from 'react-native-svg' 

class CircularSlider extends Component { 
    constructor(props){ 
    super(props) 
    this.handlePanResponderMove = this.handlePanResponderMove.bind(this) 
    this.cartesianToPolar = this.cartesianToPolar.bind(this) 
    this.polarToCartesian = this.polarToCartesian.bind(this) 
    const {width,height} = props 
    const smallestSide = (Math.min(width,height)) 
    this.state = { 
     cx: width/2, 
     cy: height/2, 
     r: (smallestSide/2)*0.85 
    } 
    } 
    componentWillMount =() => { 
    this._panResponder = PanResponder.create({ 
     onStartShouldSetPanResponder:() => true, 
     onMoveShouldSetPanResponder:() => true, 
     onPanResponderMove: this.handlePanResponderMove 
    }) 
    } 
    polarToCartesian(angle){ 
    const {cx,cy,r} = this.state 
     , a = (angle-270) * Math.PI/180.0 
     , x = cx + (r * Math.cos(a)) 
     , y = cy + (r * Math.sin(a)) 
    return {x,y} 
    } 
    cartesianToPolar(x,y){ 
    const {cx,cy} = this.state 
    return Math.round((Math.atan((y-cy)/(x-cx)))/(Math.PI/180)+((x>cx) ? 270 : 90)) 
    } 
    handlePanResponderMove({nativeEvent:{locationX,locationY}}){ 
    this.props.onValueChange(this.cartesianToPolar(locationX,locationY)) 
    } 
    render(){ 
    const {width,height,value,meterColor,textColor,onValueChange} = this.props 
     , {cx,cy,r} = this.state 
     , startCoord = this.polarToCartesian(0) 
     , endCoord = this.polarToCartesian(value) 
    return (
     <Svg onLayout={this.onLayout} width={width} height={height}> 
     <Circle cx={cx} cy={cy} r={r} stroke='#eee' strokeWidth={0.5} fill='none'/> 
     <Path stroke={meterColor} strokeWidth={5} fill='none' 
      d={`M${startCoord.x} ${startCoord.y} A ${r} ${r} 0 ${value>180?1:0} 1 ${endCoord.x} ${endCoord.y}`}/> 
     <G x={endCoord.x-7.5} y={endCoord.y-7.5}> 
      <Circle cx={7.5} cy={7.5} r={10} fill={meterColor} {...this._panResponder.panHandlers}/> 
      <Text key={value+''} x={7.5} y={1} fontSize={10} fill={textColor} textAnchor="middle">{value+''}</Text> 
     </G> 
     </Svg> 
    ) 
    } 
} 

export default CircularSlider 

完整的示例項目的代碼是在github上here

這僅僅是一個快速原型給你的想法,但這裏是它的外觀(CircularSlider的兩個實例,絕對定位使它們具有相同的中心):

enter image description here

+0

非常感謝,保存很多時間給我。 –

+0

@KD在github上查看這個非常好的實現https://github.com/bgryszko/react-native-circular-slider – Stevie