Search code examples
javascripttypescriptreact-nativesvgreact-native-svg

How do I compensate for a rotated container view in my circular slider component?


I have successfully pieced together a circular slider component from various, partially-documented code snippets (mainly here). I've tidied things up a bit and now have something I can use as a slideable control dial in which I can set an arbitrary maximum angle for the slideable area:

Dial with no rotation and maxAngle set to 270

However, I want more flexibility - I want to be able to choose an arbitrary start angle too. This will allow me to create dials a little bit like car dashboard controls, for example. Shown below is my attempt to get this working. As you can see, this messes up the touch handling:

enter image description here

Clearly I need to compensate for the rotation in the touch handling.

I am achieving all this by encapsulating an SVG component (containing all the graphics and text shown here) in a view. For the example I am having trouble with, I rotate the container view (being careful to pass that rotation value to the text too, in order to rotate that text back to the vertical position).

The typescript component:

import React, { Component } from 'react';
import ReactNative, { PanResponder, View, Dimensions } from 'react-native';
import Svg, {
  Path,
  Circle,
  G,
  Text,
  Defs,
  LinearGradient,
  Stop,
  Linecap
} from 'react-native-svg';

interface Props {
  value: number;
  dialRadius: number;
  btnRadius: number;
  startCoord: number;
  startGradient: string;
  endGradient: string;
  dialWidth: number;
  cap: Linecap;
  dialBgWidth: number;
  backgroundColor: string;
  textSize: number;
  textColor: string;
  showValue: boolean;
  btnFill: string;
  maxAngle: number;
  rotationOffset: number;
  onValueChange (angle: number): void;
}

interface State {
  angle: number;
  xCenter: number;
  yCenter: number;
}

export default class CircularSlider extends Component<Props, State> {
  static defaultProps = {
    btnRadius: 10,
    dialRadius: 80,
    dialWidth: 20,
    textColor: 'white',
    textSize: 30,
    value: 0,
    showValue: true,
    startGradient: '#12D8FA',
    endGradient: '#12D8FA',
    backgroundColor: 'white',
    startCoord: 0,
    cap: 'butt',
    btnFill: 'transparent',
    dialBgWidth: 20,
    maxAngle: 360,
    onValueChange: null,
    rotationOffset: 0
  };

  _panResponder: any;
  circleSlider: any;
  container: any;

  constructor (props: any) {
    super(props);

    this.state = {
      angle: this.props.value,
      xCenter: 0,
      yCenter: 0
    };

    this._panResponder = PanResponder.create({
      onStartShouldSetPanResponder: (e, gs) => true,
      onStartShouldSetPanResponderCapture: (e, gs) => true,
      onMoveShouldSetPanResponder: (e, gs) => true,
      onMoveShouldSetPanResponderCapture: (e, gs) => true,
      onPanResponderMove: (e, gs) => {
        let xOrigin =
          this.state.xCenter - (this.props.dialRadius + this.props.btnRadius);
        let yOrigin =
          this.state.yCenter - (this.props.dialRadius + this.props.btnRadius);
        let a = this.cartesianToPolar(gs.moveX - xOrigin, gs.moveY - yOrigin);
        this.setState({ angle: Math.min(a, this.props.maxAngle) });
      }
    });
  }

  polarToCartesian (angle: number) {
    let r = this.props.dialRadius;
    let hC = this.props.dialRadius + this.props.btnRadius;
    let a = ((angle - (90)) * Math.PI) / (180.0) ;

    let x = hC + r * Math.cos(a);
    let y = hC + r * Math.sin(a);
    return { x, y };
  }

  cartesianToPolar (x: number, y: number) {
    let hC = this.props.dialRadius + this.props.btnRadius;
    if (x === 0) {
      return y > hC ? 0 : 180;
    } else if (y === 0) {
      return x > hC ? 90 : 270;
    } else {
      return (
        Math.round((Math.atan((y - hC) / (x - hC)) * 180) / Math.PI) +
        (x >= hC ? 90 : 270)
      );
    }
  }

  handleMeasure = (ox: number, oy: number, width: number, height: number, px: number, py: number) => {
    this.setState({
      xCenter: px + (this.props.dialRadius + this.props.btnRadius),
      yCenter: py + (this.props.dialRadius + this.props.btnRadius)
    });
  }

  handleOnLayout = () => {
    this.circleSlider.measure(this.handleMeasure);
  }

  render () {
    let {
      btnRadius,
      dialRadius,
      rotationOffset,
      textSize
    } = this.props;
    let width = (dialRadius + btnRadius) * 2;
    let startCoord = this.polarToCartesian(this.props.startCoord);
    let endCoord = this.polarToCartesian(this.state.angle);
    let maxAngle = this.polarToCartesian(this.props.maxAngle);

    return (
      <View
        ref={r => this.container = r }
        style={{ flex: 1, margin: 50, transform: [{ rotate: `${rotationOffset}deg` }] }}
      >
        <Svg
          onLayout={this.handleOnLayout}
          ref={r => this.circleSlider = r}
          width={width}
          height={width}
        >
          <Defs>
            <LinearGradient id='gradient1' x1='0%' y1='0%' x2='100%' y2='0%'>
              <Stop offset='0%' stopColor={this.props.startGradient} />
              <Stop offset='100%' stopColor={this.props.endGradient} />
            </LinearGradient>
          </Defs>
          <Text
              transform={`rotate(${-rotationOffset}, 90, 90)`} // compensate for rotated container
              x={width / 2}
              y={width / 2 + textSize / 4}
              fontSize={textSize}
              fill={this.props.textColor}
              textAnchor='middle'
            >
              {this.props.showValue &&
                this.props.onValueChange(this.state.angle) + ''}
            </Text>
          <G>
            <Path
              stroke={this.props.backgroundColor}
              strokeWidth={this.props.dialWidth}
              fill='none'
              strokeLinecap={this.props.cap}
              strokeLinejoin='round'
              d={`M${startCoord.x} ${startCoord.y} A ${dialRadius} ${dialRadius} 0 ${
                  (this.props.startCoord + 180) % 360 > (this.props.maxAngle) ? 0 : 1
                } 1 ${maxAngle.x} ${maxAngle.y}`}
            />
            <Path
              stroke={'url(#gradient1)'}
              strokeWidth={this.props.dialWidth}
              fill='none'
              strokeLinecap={this.props.cap}
              strokeLinejoin='round'
              d={`M${startCoord.x} ${startCoord.y} A ${dialRadius} ${dialRadius} 0 ${
                (this.props.startCoord + 180) % 360 > this.state.angle ? 0 : 1
              } 1 ${endCoord.x} ${endCoord.y}`}
            />
            <G x={endCoord.x - btnRadius} y={endCoord.y - btnRadius}>
              <Circle
                r={btnRadius}
                cx={btnRadius}
                cy={btnRadius}
                fill={this.props.btnFill}
                {...this._panResponder.panHandlers}
              />
            </G>
          </G>
        </Svg>
      </View>
    );
  }
}

And the component is used in this way, for now: <CircularSlider rotationOffset={-135} maxAngle={270} onValueChange={(angle) => angle } /> (or without the offset for the first gif example).

I have tried:

  • Adjusting the current angle before inserting into the PolarToCartesian() function, but this just got really messy and didn't really make sense, at least the way I did it.
  • Experimenting with this.container.measure(this.handleMeasure) instead of this.circleSlider.measure(this.handleMeasure), and this.circleSlider.measureLayout(ReactNative.findNodeHandle(this.container), this.handleMeasure) and removing the extra parameters px: number, py: number from handleMeasure and reading the offset (ox and oy), but this doesn't give the right kind of motion at all...

So how do I compensate for the rotation of the container view in touch handling? OR is there a completely different way to approach this that gives me the behaviour I need?

(Using React Native 0.57.0 and react-native-svg ^7.0.2 by the way)


Solution

  • I was on the right track with adjusting the angle to the cartesianToPolar() function in the onPanResponderMove() function, I just didn't take into account handling the maxAngle correctly, around 0. So in onPanResponderMove() I needed this:

    let a2 = 0;
    if (a + this.props.rotationOffset > 0) {
      a2 = a - (360 + this.props.rotationOffset);
    } else {
      a2 = a - this.props.rotationOffset;
    }
    
    this.setState({ angle: a2 > 0 ? Math.min(a2, this.props.maxAngle) : this.props.maxAngle });
    

    I also removed the rotation transform from the view and rotated my arc paths in a group instead with:

    <G transform={`rotate(${this.props.rotationOffset} ${width / 2} ${width / 2})`}>
    ... my paths ... 
    </G>