I am using Reanimated2 on my React Native app in an Android emulator. I am trying to rotate a component using useAnimatedStyle. Here's my code. It works on iOS, but on Android I get an error.
const animatedStyle = useAnimatedStyle(() => {
let rotate = interpolate(x.value, [-150, 0, 150], [-Math.PI / 36, 0, Math.PI / 36], Extrapolate.CLAMP);
return {
transform: [{ translateY: y.value }, { translateX: x.value }, { rotate }],
}
});
I'm getting the following error on Android only: Transform with key of "rotate" must be a string: {"rotate":0}]
Then I change the code to a string:
const animatedStyle = useAnimatedStyle(() => {
let rotate = interpolate(x.value, [-150, 0, 150], ["-10deg", "0deg", "10deg"], Extrapolate.CLAMP);
return {
transform: [{ translateY: y.value }, { translateX: x.value }, { rotate }],
}
});
Then I get this error:
Error while updating property 'transform' of a view managed by: RTCView
null
For input string: "-10degNaN"
Can anyone help me fix this?
https://docs.swmansion.com/react-native-reanimated/docs/1.x.x/nodes/interpolate/
The documentation states, that you should use your first approach. Interpolate the numbers and then add the deg afterwards.
This should do the trick:
const animatedStyle = useAnimatedStyle(() => {
let rotate = interpolate(x.value, [-150, 0, 150], [-Math.PI / 36, 0, Math.PI / 36], Extrapolate.CLAMP);
return {
transform: [{ translateY: y.value }, { translateX: x.value }, { rotate: `${rotate}deg` }],
}
});
Related
I've been trying pretty hard to add an onClick function on my clusters that zooms a bit on the map, but I can't figure out how to do so, and I can't find any help on the documentation.
I've been trying to work with controller.onCircleTappedand controller.onFeatureTapped but I don't understand how it's working, or how to link the callback to a particular cluster.
Thank you all!
Here's my current code:
`
Future<void> addGeojsonCluster() async {
var geojson = {
"type": "FeatureCollection",
"crs": { "type": "name", "properties": { "name": "pois" } },
"features": [
for(var marker in markers){
"type" : "Feature", "properties" : {"id" : marker.title}, "geometry": {"type" : "Point", "coordinates" : [marker.longitude, marker.latitude] }
},
]
};
await controller.addSource(
"poi",
GeojsonSourceProperties(
data: geojson,
cluster: true,
clusterMaxZoom: 14, // Max zoom to cluster points on
clusterRadius:
50, // Radius of each cluster when clustering points (defaults to 50)
)
);
await controller.addLayer(
"poi",
"poi-circles",
const CircleLayerProperties(
circleColor: [
Expressions.step,
[Expressions.get, 'point_count'],
'#51bbd6', //blue
100,
'#f1f075', //yellow
750,
'#f28cb1' //pink
],
circleRadius: [
Expressions.step,
[Expressions.get, 'point_count'],
20,
100,
30,
750,
40
]),
);
await controller.addSymbolLayer(
"poi",
"unclustered-point",
const SymbolLayerProperties(
textField: [Expressions.get, "id"],
textHaloWidth: 1,
textSize: 12.5,
textHaloColor: '#ffffff',
textOffset: [
Expressions.literal,
[0, 2]
],
iconImage: "images/mapbox_circle_marker.png",
iconSize: 2,
iconAllowOverlap: true,
textAllowOverlap: true,
textColor: '#000000',
textHaloBlur: 1,
),
filter: [
'!',
['has', 'point_count']
],
enableInteraction: true,
);
await controller.addLayer(
"poi",
"poi-count",
const SymbolLayerProperties(
textField: [Expressions.get, 'point_count_abbreviated'],
textFont: ['DIN Offc Pro Medium', 'Arial Unicode MS Bold'],
textSize: 12,
));
}
`
You need to register a OnTapListener on the whole map and query all the features on the map.
MapWidget(
onTapListener: _clickMap,
)
And in _clickMap you query for everything displayed on the map and decide depending on the return what to do. Here I zoom in to the next cluster step. Keep in mind, that there is currently a confirmed bug in the sdk. OnTapListener is not return ScreenCoordinates but geographical coordinates. So you need to convert them first with pixelForCoordinate.
void _clickMap(ScreenCoordinate coordinate) async {
ScreenCoordinate coordin = await mapboxMap!.pixelForCoordinate({
"coordinates": [coordinate.y, coordinate.x]
});
List<QueriedFeature?> features = await mapboxMap!.queryRenderedFeatures(
RenderedQueryGeometry(
type: Type.SCREEN_COORDINATE, value: json.encode(coordin.encode())),
RenderedQueryOptions(
layerIds: ['clusters', "unclustered-point"], filter: null));
if (features.isNotEmpty) {
if ((features[0]!.feature["properties"] as Map)['cluster'] != null) {
FeatureExtensionValue cluster = await mapboxMap!
.getGeoJsonClusterExpansionZoom(
'earthquakes', features[0]!.feature);
mapboxMap?.easeTo(
CameraOptions(
center: Point(
coordinates: Position(
(features[0]!.feature['geometry'] as Map)["coordinates"][0],
(features[0]!.feature['geometry'] as Map)["coordinates"][1],
)).toJson(),
zoom: double.parse(cluster.value!),
bearing: 0,
pitch: 0),
MapAnimationOptions(duration: 500, startDelay: 0));
}}}
Hope that helps :)
I have a requirement to extend my plot band outside the graph and give a shape. Need to achieve the portion marked in the attached screenshot. using highchart android wrapper. While searching for the solution, I found the jsfiddle I would like to do the same thing using the android wrapper; I am using highchart library of version 6.1.4
targetimage
Link : https://jsfiddle.net/BlackLabel/e52smy16/
<script src="https://code.highcharts.com/highcharts.js"></script>
<div id="container"></div>
const renderCustomPlotBand = function(chart) {
let ren = chart.renderer,
customOptions = chart.yAxis[0].options.customPlotBand,
from = customOptions.from,
to = customOptions.to,
xEnd = chart.plotLeft + chart.plotSizeX,
xBeginig = chart.plotLeft - 40,
point1 = [xEnd, chart.yAxis[0].toPixels(from)],
point2 = [xBeginig, chart.yAxis[0].toPixels(from)],
point3 = [xBeginig, chart.yAxis[0].toPixels(to)],
point4 = [xEnd, chart.yAxis[0].toPixels(to)],
textWidth = chart;
if (customOptions.enabled) {
chart.customPlotBand = ren.g('customPlotBand').add().toFront()
chart.customText = ren.g('customText').add().toFront();
ren.path(['M', point1[0], point1[2], 'L', point2[0], point2[2], point3[0], point3[2], point4[0], point4[2]])
.attr({
'stroke-width': 1,
stroke: 'red'
}).add(chart.customPlotBand);
ren.label(customOptions.text, point2[0] - 10, point2[2] - 17).attr({
padding: 5,
fill: 'white',
rotation: -90
}).add(chart.customText);
chart.customText.translate(0, -(point2[2] - point3[2]) / 2 + chart.customText.element.getBBox().height - 3)
}
}
Highcharts.chart('container', {
chart: {
marginLeft: 80,
events: {
render() {
renderCustomPlotBand(this)
}
}
},
yAxis: [{
//Declere your custom plotband
customPlotBand: {
enabled: true,
from: 2,
to: 4,
text: 'Target'
},
title: {
text: null
},
lineWidth: 1,
gridLineWidth: 1
}],
series: [{
data: [1, 3, 6, 2, 5]
}]
});```
Unfortunately, there is no option to create a custom plotBand like in the provided example, since the renderer module is not available in the Android wrapper.
The only way of achieving similar behaviour is using static plotBand.
HIYAxis hiyAxis = new HIYAxis();
HIPlotBands plotBands = new HIPlotBands();
plotBands.setColor(HIColor.initWithName("red"));
plotBands.setFrom(2);
plotBands.setTo(4);
hiyAxis.setPlotBands(new ArrayList<>(Collections.singletonList(plotBands)));
options.setYAxis(new ArrayList<>(Collections.singletonList(hiyAxis)));
I'm building a Music Player and I'm focusing on the progress bar.
I was able to react to swipe gestures, but I cant limit how far that gesture goes.
This is what I've done so far. I've reduced everything to the minumal:
constructor(props) {
super(props);
this.state = {
pan: new Animated.ValueXY()
};
}
componentWillMount() {
this._panResponder = PanResponder.create({
onMoveShouldSetResponderCapture: () => true,
onMoveShouldSetPanResponderCapture: () => true,
onPanResponderGrant: (e, gestureState) => {
// Set the initial value to the current state
let x = (this.state.pan.x._value < 0) ? 0 : this.state.pan.x._value;
this.state.pan.setOffset({ x, y: 0 });
this.state.pan.setValue({ x: 0, y: 0 });
},
onPanResponderMove: Animated.event([
null, { dx: this.state.pan.x, dy: 0 },
]),
onPanResponderRelease: (e, { vx, vy }) => {
this.state.pan.flattenOffset();
}
});
}
render() {
let { pan } = this.state;
// Calculate the x and y transform from the pan value
let [translateX, translateY] = [pan.x, pan.y];
// Calculate the transform property and set it as a value for our style which we add below to the Animated.View component
let imageStyle = { transform: [{ translateX }, { translateY }] };
return (
<View style={styles.container}>
<Animated.View style={{imageStyle}} {...this._panResponder.panHandlers} />
</View>
);
}
Here there is an image showing what the problem is.
Initial position:
Wrong Position, limit exceeded:
So the idea is to stop keeping moving once the limit (left as well as right) is reached. I tried checking if _value < 0, but it didn't work since It seems to be an offset, not a position.
Well any help will be appreciated.
Instead of letting your animation die at your borders, you could interpolate your
Animated.Value with y=x, but with clamping it to your width.
return (
<View style={styles.container}>
<Animated.View
style={{
transform: [{
translateX: this.state.pan.x.interpolate({
inputRange: [0, trackWidth ],
outputRange: [0, trackWidth ],
extrapolate: 'clamp'
})
}],
}}
{...this._panResponder.panHandlers}
/>
</View>
);
Here's a more in-depth example: https://github.com/olapiv/expo-audio-player/blob/master/src/AudioSlider.js
onPanResponderMove: (e, gestureState)=> {
this.state.pan.x._value > 0 ? null : Animated.event([
null,
{dx: this.state.pan.x, dy: this.state.pan.y},
])(e, gestureState)
},
I was trying to do something similar; I wanted to have it so that you can pull the page part way and then release and it goes back to where it was.
My solution was this:
panResponder = PanResponder.create({
onMoveShouldSetPanResponderCapture: (e, { dx }) => {
// This will make it so the gesture is ignored if it's only short (like a tap).
// You could also use moveX to restrict the gesture to the sides of the screen.
// Something like: moveX <= 50 || moveX >= screenWidth - 50
// (See https://facebook.github.io/react-native/docs/panresponder)
return Math.abs(dx) > 20;
},
onPanResponderMove: (e, gestureState) => (
// Here, 30 is the limit it stops at. This works in both directions
Math.abs(gestureState.dx) > 30
? null
: Animated.event([null, { dx: this.animatedVal }])(e, gestureState)
),
onPanResponderRelease: (e, { vx, dx }) => {
// Here, abs(vx) is the current speed (not velocity) of the gesture,
// and abs(dx) is the distance traveled (not displacement)
if (Math.abs(vx) >= 0.5 || Math.abs(dx) >= 30) {
doSomeAction();
}
Animated.spring(this.animatedVal, {
toValue: 0,
bounciness: 10,
}).start();
},
});
🍰
This method doesn't cancel the gesture handler if the user is still holding it down after exceeding the X limit.
Change MaxDistance & MinDistance to whatever values you like 😃
onPanResponderMove: (e, gestureState) => {
// Configure Min and Max Values
const MaxDistance = maxDistance;
const MinDistance = 0;
const dxCapped = Math.min(Math.max(parseInt(gestureState.dx), MinDistance), MaxDistance);
// If within our bounds, use our gesture.dx....else use dxCapped
const values = {}
if(gestureState.dx < MaxDistance && gestureState.dx > MinDistance){
values.dx = gestureState.dx
values.dy = gestureState.dy
}else{
values.dx = dxCapped
values.dy = gestureState.dy
}
//Animate Event
Animated.event([null, {
dx: pan.x,
dy: pan.y,
}])(e, values);
},
Hope this helps some folks. 🐱
A tricky point is that while I can not move the icon beyond that clamp but the pan.x value is indeed beyond the clamp limit although you don't see it. Then, when you want to move it back, you don't know how much swipe you need to move it back. This could be a nuance.
My solution is:
onPanResponderGrant: () => {
console.log("pan responder was granted access!")
pan.setOffset({
x: (pan.x._value>xMax)? xMax : (pan.x._value<xMin)? xMin: pan.x._value,
y: (pan.y._value>yMax)? yMax : (pan.y._value<yMin)? yMin: pan.y._value,
});
},
Then, can also console.log pan.x._value in following to double check.
onPanResponderRelease: () => {
pan.flattenOffset();}
I found this helpful for my own project. Note can only use pan.x_value not pan.x.
In my case I also used useMemo instead of useRef so the limits can be reset, which I learned from React Native's panResponder has stale value from useState?
There's a solution to a similar problem on this other question: https://stackoverflow.com/a/58886455/9021210
that can be repurposed for what you're looking for
const DRAG_THRESHOLD = /*configure min value*/
const DRAG_LIMIT = /*configure max value*/
onPanResponderMove: (e, gesture) => {
if ( (Math.abs( gesture.dy ) > DRAG_THRESHOLD) &&
(Math.abs( gesture.dy ) < DRAG_LIMIT ) )
{
return Animated.event([
null, {dx: 0, dy: pan.y}
]) (e, gesture)
}
},
This is not my answer, so I recommend you follow the link to see further explanation and if you like it upvote the original poster! :) I was trying to do the same thing and it worked for me! hope it helps.
P.S. I found that other solutions relying on checking the animation value rather than the gesture value would sometimes get stuck.
Running RN v0.40.0 on a Physical device on Android 5.1. I'm trying to animate a text to appear with fade-in and slide up in the following way:
export default class Example extends PureComponent {
constructor(props) {
super(props);
this.translate = new Animated.Value(-15);
this.fade = new Animated.Value(0);
}
componentWillReceiveProps() {
setTimeout(() => {
Animated.timing(this.translate, {
toValue: 0,
duration: 800,
easing: Easing.inOut(Easing.ease),
}).start();
Animated.timing(this.fade, {
toValue: 1,
duration: 800,
easing: Easing.inOut(Easing.ease),
}
).start();
}, 150);
}
render() {
return (
<View>
<Animated.View
style={{
transform: [
{translateY: this.translate},
],
opacity: this.fade
}}
>
<Text>
{this.props.text}
</Text>
</Animated.View>
</View>
);
}
And after I reload JS bundle from the dev menu and go to that view app crashes with no error log, sometimes showing Application ... stopped working, sometimes not. If I start the app from the android menu again it loads ok, crashes only for the first time. It definitely has something to do with animations since before I introduced animations I had no crashes. There are no logs, no clues, please, give me some advice what could that be and what should I try and what should I check. Thanks.
Btw, on that view with animations I have a pretty heavy background image (~400k) could that be a problem?
UPD: I have narrowed it down to that it crashes when I'm trying to run animations in parallel, either with setTimeout or with Animation.parallel. What could be the problem?
Not sure what's causing the crash, but using Animated.parallel has worked for me:
Animated.parallel([
Animated.spring(
this.state.pan, {
...SPRING_CONFIG,
overshootClamping: true,
easing: Easing.linear,
toValue: {x: direction, y: -200}
}),
Animated.timing(
this.state.fadeAnim, {
toValue: 1,
easing: Easing.linear,
duration: 750,
}),
]).start();
where SPRING_CONFIG is something like
var SPRING_CONFIG = {bounciness: 0, speed: .5};//{tension: 2, friction: 3, velocity: 3};
and pan and fadeAnim values are set in the constructor this.state values as:
pan: new Animated.ValueXY(),
fadeAnim: new Animated.Value(0),
with the animated View as
<Animated.View style={this.getStyle()}>
<Text style={[styles.text, {color: this.state.textColor}]}>{this.state.theText}</Text>
</Animated.View>
and the getStyle function is
getStyle() {
return [
game_styles.word_container,
{opacity: this.state.fadeAnim},
{transform: this.state.pan.getTranslateTransform()}
];
}
This tutorial helped me set this up...good luck!
I am using this library https://reactnavigation.org/docs/intro/ to build android by react-native. I can make the navigation happens on android device but how I can make the screen slide in from the right and fade in from the left. It seems that this behaviour happens on iOS device but not in Android. Is there any animation configuration for android app?
Please see below animation. This is recorded in iOS.
Starting from : "#react-navigation/native": "^5.5.1",
import {createStackNavigator, TransitionPresets} from '#react-navigation/stack';
const TransitionScreenOptions = {
...TransitionPresets.SlideFromRightIOS, // This is where the transition happens
};
const CreditStack = createStackNavigator();
function CreditStackScreen() {
return (
<CreditStack.Navigator screenOptions={TransitionScreenOptions}> // Don't forget the screen options
<CreditStack.Screen
name="Credit"
component={HomeScreen}
options={headerWithLogo}
/>
<HomeStack.Screen
name="WorkerDetails"
component={WorkerDetails}
options={headerWithLogoAndBackBtn}
/>
</CreditStack.Navigator>
);
}
You can watch this video to understand more:
https://www.youtube.com/watch?v=PvjV96CNPqM&ab_channel=UnsureProgrammer
You should use transitionConfig to override default screen transitions as written on this page.
Unfortunately there is no example provided how that function works but you can find some examples in this file: \react-navigation\lib\views\CardStackStyleInterpolator.js
So your code should look like this:
const navigator = StackNavigator(scenes, {
transitionConfig: () => ({
screenInterpolator: sceneProps => {
const { layout, position, scene } = sceneProps;
const { index } = scene;
const translateX = position.interpolate({
inputRange: [index - 1, index, index + 1],
outputRange: [layout.initWidth, 0, 0]
});
const opacity = position.interpolate({
inputRange: [
index - 1,
index - 0.99,
index,
index + 0.99,
index + 1
],
outputRange: [0, 1, 1, 0.3, 0]
});
return { opacity, transform: [{ translateX }] };
}
})
});
For StackNavigatoin 6.x.x
Just import
import { TransitionPresets } from '#react-navigation/stack';
Then create a config:
const screenOptionStyle = {
// headerShown: false,
...TransitionPresets.SlideFromRightIOS,
};
And finally just assign them to the Stack Navigator Screen Options:
<Stack.Navigator
screenOptions={screenOptionStyle}
>
<Stack.Screen
...
...
All the above answers are correct, but the solutions work ONLY if you are using createStackNavigator, and not if you are using createNativeStackNavigator; unfortunatelly, if you are following the get started section from react-navigation's docs, you will end up using the latter.
Here you can find a SO question speaking about the differences between the two, but the most relevant one for this questions is that many of the options that your can pass to the former (such as transitionConfig), cannot be passed to the latter.
If you are using createNativeStackNavigator this is how you can do it:
import { createNativeStackNavigator } from '#react-navigation/native-stack'
const StackNavigator = createNativeStackNavigator()
const MyNativeStackNavigator = () =>{
return <StackNavigator.Navigation
screenOptions={{
animation: 'slide_from_right', //<-- this is what will do the trick
presentation: 'card',
}}
>
{routes}
</StackNavigator.Navigator>
}
you need to import StackViewTransitionConfigs from 'react-navigation-stack'
then, override the transitionConfing function.
const myStack = createStackNavigator({
Screen1,
Screen2,
Screen3
},{
transitionConfig: () => StackViewTransitionConfigs.SlideFromRightIOS
}
On #react-navigation/stack component version, the way to do a slide from the right animation is:
<Stack.Navigator
screenOptions={{
cardStyleInterpolator: ({index, current, next, layouts: {screen}}) => {
const translateX = current.progress.interpolate({
inputRange: [index - 1, index, index + 1],
outputRange: [screen.width, 0, 0],
});
const opacity = next?.progress.interpolate({
inputRange: [0, 1, 2],
outputRange: [1, 0, 0],
});
return {cardStyle: {opacity, transform: [{translateX}]}};
},
}}>
<Stack.Screen name="MainScreen" component={MainScreen} />
...
</Stack.Navigator>
Better you can use the react native navigation for this. You can configure your screen using configureScene method. Inside that method use Navigator.SceneConfigs for animating screen. It's work for both android and iOS.
You can get useful information from index.d.ts file, find the export interface TransitionConfig , then press 'Ctrl' & left_click on NavigationTransitionSpec and NavigationSceneRendererProps, then you can get everything you want.