I have a color picker where I can drag a cursor across a linear gradient and it selects the color the cursor is on.
I want to update the color picker so that given a startingColor
, it determines the location of the cursor for that color.
Components
I have a linear gradient
import { LinearGradient } from "expo-linear-gradient";
<LinearGradient
colors={["#BF81CF", "#E075AB", "#EB5E5E", "#E37861", "#F5E769", "#81CF84", "#A5AEFF", "#B0AFAF"]}
...
/>
Every time I drag the cursor I determine the corresponding color by doing the following (I’m using react-native-reanimated):
const translateX = useSharedValue(0);
const animatedColorPreviewStyle = useAnimatedStyle(() => {
const inputRange = colors.map(
(_, index) => (index / colors.length) * maxWidth + CIRCLE_COLOR_VIEWER
);
const backgroundColor = interpolateColor(
translateX.value,
inputRange,
colors,
"RGB"
);
onColorChanged?.(backgroundColor);
return {
backgroundColor,
};
});
Given startingColor = "#e76b5f"
, how do I determine what the translateX.value
needs to be?
Attempts
useEffect(() => {
if (startingColor) {
const startingColorInt = parseInt(startingColor.substring(1), 16);
const inputRange = colors
.map((item) => parseInt(item.substring(1), 16))
.sort()
.reverse();
const outputRange = colors.map(
(_, index) => (index / colors.length) * maxWidth + CIRCLE_COLOR_VIEWER
);
const indexPosition = interpolate(
startingColorInt,
inputRange,
outputRange
);
translateX.value = indexPosition;
}
}, [selectedColor]);
While this gives me a value in the correct range, it’s incorrect.
Any help would be greatly appreciated!