Is there an equivalent of FastOutSlowInInterpolator for iOS? - android

Is there an equivalent of FastOutSlowInInterpolator for iOS? I've recently got my hands on AndroidX and really like this interpolator. I've found the source code for it too but have no idea how to convert it to iOS implementation.

If you are using UIViewPropertyAnimator the curve that you need is .easeInOut, and you can pass it as curve parameter when you create your animator:
let animator = UIViewPropertyAnimator(duration: 0.4, curve: .easeInOut) {
// Animations
}
If you are not happy with this system curve, you can follow this answer and use this handy website to replicate FastOutSlowInInterpolator's control points.
As FastOutSlowInInterpolator documentation states:
Interpolator corresponding to fast_out_slow_in. Uses a lookup table
for the Bezier curve from (0,0) to (1,1) with control points: P0 (0,
0) P1 (0.4, 0) P2 (0.2, 1.0) P3 (1.0, 1.0)
So, in your particular case you are looking for something like this:
let timingParameters = UICubicTimingParameters(
controlPoint1: CGPoint(x: 0.4, y: 0),
controlPoint2: CGPoint(x: 0.2, y: 1)
)
let animator = UIViewPropertyAnimator(duration: 0.4, timingParameters: timingParameters)
or this:
let animator = UIViewPropertyAnimator(
duration: 0.4,
controlPoint1: CGPoint(x: 0.4, y: 0),
controlPoint2: CGPoint(x: 0.2, y: 1)
) {
// Animations
}

SwiftUI
In SwiftUI you can animate almost any change with .animate modifier and it accepts the curve as the argument. I think .interpolatingSpring(stiffness: 30, damping: 20) is the curve that you are looking for (the bottom one).
Examples
struct ContentView: View {
#State var isLeading = false
var body: some View {
VStack {
SpacedCircle(isLeading: $isLeading)
.animation(.linear)
SpacedCircle(isLeading: $isLeading)
.animation(.easeIn)
SpacedCircle(isLeading: $isLeading)
.animation(.easeOut)
SpacedCircle(isLeading: $isLeading)
.animation(.easeInOut)
SpacedCircle(isLeading: $isLeading)
.animation(.interactiveSpring(response: 0.27, dampingFraction: 0.5, blendDuration: 0.2))
SpacedCircle(isLeading: $isLeading)
.animation(.interpolatingSpring(stiffness: 30, damping: 20))
Button("Toggle") { isLeading.toggle() }
}
}
}
UIKit
You can achieve that similarly in UIKit too:
Example
#IBAction func touched(_ sender: UIButton) {
UIView.animate(withDuration: 1, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 3, options: []) {
self.circleView.transform = .identity
}
}
#IBAction func touchDown(_ sender: Any) {
UIView.animate(withDuration: 1, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 3, options: []) {
self.circleView.transform = CGAffineTransform(translationX: 240, y: 0)
}
}

Related

how to Extend highchart plot band outside graph using android wrapper

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)));

How to send mouse clicked coordinates from Flickable to ListView?

I'm developing an application for Android.
I have some ChartViews placed in the ListView.
Above ListView I have got a Flickable to scroll ChartViews synchronously in the x axis.
I need to show the coordinates of the point on the chart to which the user tap.
But I can't because flickable catches mouse click events and does not propagate it to other objects below.
I need the mouse event to come to a specific delegate that the user tapped on.
Is it possible to solve this problem?
Is there a way to get mouse coordinates during flick?
Is there a way to propagate mouse events to the ListView as if they came from the user?
Rectangle {
color: "#ffffff"
Component {
id: chartDelegate
Rectangle {
id: rootDelegRect
anchors {left: parent.left; right: parent.right }
height: 350
ChartView {
anchors { fill: parent;}
x: -10
y: -10
width: parent.width + 20
height: parent.height + 20
legend.visible: false
LineSeries {
name: "LineSeries"
axisX: ValueAxis {
min: 0
max: 4
labelFormat: "%.0f"
}
axisY: ValueAxis {
min: 0
max: 6
labelFormat: "%.0f"
}
XYPoint { x: 0; y: 0.0 }
XYPoint { x: 1; y: 5.2 }
XYPoint { x: 2; y: 2.4 }
XYPoint { x: 3; y: 0.1 }
XYPoint { x: 4; y: 5.1 }
}
}
MouseArea {
anchors.fill: parent
hoverEnabled :true
onMouseXChanged: console.log(mouseX,mouseY);//does not work when clicked
}
}
}
ListView { id: listViewCharts; objectName: "chart";
clip: true
anchors.top: parent.top; anchors.bottom: parent.bottom;
width: 1500
contentX:baseFlick.contentX; contentY:baseFlick.contentY;
model: listViewIdsModel
cacheBuffer: 1500
delegate: chartDelegate
}
Flickable {
id: baseFlick
anchors.fill: parent
contentHeight: listViewCharts.contentHeight
contentWidth: listViewCharts.width
}
}
Apparently this problem can only be solved using c++
To capture Flickable mouse events, do the following:
1) add the objectName of the object is Flickable
objectName: "baseFlick"
2) in c++ after creating a qml scene. Find the baseFlick object and Installs an event filter on this object
auto rootObj = engine.rootObjects().at(0);
auto item = rootObj->findChild<QQuickItem *>("baseFlick");
if(item!=nullptr){
item->installEventFilter(this);
} else qDebug()<<"ERR baseFlick item=nullptr";
3) implement the eventFilter virtual function
bool IDS2forUser::eventFilter(QObject *watched, QEvent *event)
{
...
return false;
}
In order to propagate mouse events to the ListView as if they came from the user.
In the eventFilter function:
1) Find the ListView (chart) object
auto rootObj = engine.rootObjects().at(0);
auto item = rootObj->findChild<QQuickItem *>("chart");
2) Find all of his children.
You need to look for children every time as their number may change.
Note, you should use the QQuickItem::childItems () function instead of QObject::children()
void IDS2forUser::getAllObjects(QQuickItem *parent, QList<QQuickItem *> &list) {
QList<QQuickItem *> children = parent->childItems();
foreach (QQuickItem *item, children) {
list.append(item);
getAllObjects(item,list);
}
}
3) Convert all coordinates to local coordinates of the object. And send all children events.
The whole function is presented below.
bool IDS2forUser::eventFilter(QObject *watched, QEvent *event)
{
auto rootObj = engine.rootObjects().at(0);
auto item = rootObj->findChild<QQuickItem *>("chart");
QList<QQuickItem *> list;
getAllObjects(item, list);
QQuickItem *watchedIt = dynamic_cast<QQuickItem *>(watched);
if(!watchedIt)return false;
QMouseEvent *mouseEvent = dynamic_cast<QMouseEvent *>(event);
if(!mouseEvent)return false;
foreach (QQuickItem *item, list) {
QPointF point=item->mapFromItem(watchedIt,mouseEvent->localPos());
if(point.x()<0 || point.y()<0 || point.x()>=item->width() || point.y()>=item->height())continue;
QMouseEvent mouseEvent2(mouseEvent->type(),
point,
mouseEvent->button(),mouseEvent->buttons(),Qt::NoModifier);
QCoreApplication::sendEvent(item, &mouseEvent2);
}
return false;
}

ReactNative PanResponder limit X position

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.

React Navigation: StackNavigator transition for Android

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.

React Native Android transition without animaiton

How do I transition between scenes without animations using Navigator?
When I do a Navigator.replace(), the view just switches instantly, I'd like to replicate this behavior with a Navigator.push() call.
I've been playing around with SceneConfigs and feel like that might be the right solution, but can't get it to work.
I found a hacky solution here. https://github.com/facebook/react-native/issues/1953
var NoTransition = {
opacity: {
from: 1,
to: 1,
min: 1,
max: 1,
type: 'linear',
extrapolate: false,
round: 100,
},
};
return {
...Navigator.SceneConfigs.FloatFromLeft,
gestures: null,
defaultTransitionVelocity: 100,
animationInterpolators: {
into: buildStyleInterpolator(NoTransition),
out: buildStyleInterpolator(NoTransition),
},
};

Categories

Resources