I have the following view where I'm using a pan gesture in the upwards or downwards direction to rotate it positively or negatively:
I'm wondering, is there a mathematical equation to precisely covert the amount panned to the amount it should be rotated so the timing is correct to keep the users finger on the view while it is rotating? For instance, if the pan translation comes back as 1, what would the proper amount be to rotate it?.
There are a few details you need to provide to give a meaningful answer:
Are you rotating the view about its centre (the default) or is there an anchor point?
Since the view is rotating, while the touch is moving strictly vertically in the superview, what's the expected behaviour as the view rotates further away from the vertical line defining the pan?
Is there a reason you're using a pan gesture instead of a rotation gesture, or even just direct touch tracking? It seems like it creates more problems than it solves.
I'm going to assume the view is rotating about its centre for the sake of simplicity, and I'll use a pan starting on the right side of the view as an example, with the rotation not exceeding ±90°. Here are two options:
Movement up and down translates linearly to the angle of rotation, i.e., a pan of a given distance rotates the view the same amount, no matter where the pan starts. In that case, you need to decide what the top and bottom limits of the pan are. They might be the bounds of the superview. Regardless, you want to convert the distance travelled in the Y direction to a value between -1 and 1, where -1 represents the bottom limit and 1 represents the top limit. Something like 2 * (dy / superview.bounds.size.height - 0.5). Multiply that by π/2 (M_PI_2 in math.h) to scale from the range [-1, 1] to the range [-π/2, π/2] and you've got the angle to add/subtract from the view's rotation at the beginning of the gesture.
The view tracks the touch so that its right edge is always "pointed at" the touch. In this case, pan isn't terribly useful because you only need the location of the touch in the superview, not the distance travelled. Calculate dx and dy as the difference in x and y coordinates from the view's centre to the touch location. Then calculate atan2(dy, dx) and you've got the absolute angle of rotation for the view.
I hope this puts you on the right track.
The answer is the angle would be panAmount.y / rectangleWidth.
Here is proof: https://math.stackexchange.com/questions/322694/angle-of-rotated-line-segment
Related
So I have a view that rotates according to a specific degree that is set by the direction the device is pointed in. The problem is when you go from 359.99 to 0.01 degree rotation (which is the smallest difference in actuality, the view chooses to rotate all the way from 360 down to 0, instead of just wrapping around. This causes problems with the animation because it makes the view spin 359 degrees back to the 0 position instead of just clicking into the 0 degree position from 359. I've tried setting animation to nil between 359-360 and 0-1 but if you move the device fast enough, you still see this bad animation. Any suggestions?
Image("arrow")
.rotationEffect(Angle(degrees: deviceHeading))
.animation(.easeOut)
https://youtu.be/MzpI6THHS8U
As you can see, right in that position, it rotates fully around instead of just doing a change of taking the short path to the new position.
I am making a vintage phone and got a working starting code where user moves his fingers over a UIImageView numbers and it rotates dial. It then moves it back to original position. See screenshot.
The three problems that I can't seem to figure out are;
How can I restrict user to rotate only in clockwise direction? Currently user can move it in any direction (clockwise and counter clockwise)
How can I detect which number that user selected? Meaning user touched 1 or 3 or 5? I need this info so that I can stop the rotation when that number reaches the bar on the right.
In my current code when I stop the rotation and let go of the circle, it moves back to it's place by moving back counter clockwise. It works well if I select 1,2,3,4 but for any number 5 and up the dial moves clockwise back to its original position. How can I force counter clockwise motion on touchesEnded?
Let’s assume that you’re talking about this gesture:
Source.
Build a single-touch rotation gesture recognizer. After building the gesture recognizer correctly, you can just look at the rotation and see what to do with the rotary pad.
There are several things you’ll consider when building a single-touch rotation gesture recognizer. If you look at UIRotationGestureRecognizer, it uses connection between two touches, backed by two fingers, to derive the current angle, then compares the angle to the previous angle, derived from an earlier touch change event, to see the delta.
Measuring the current angle
It takes two points to form a line and you need a line to know the angle. If you’re working with only one touch, you need an anchor point. There are many ways to send an anchor point to your gesture recognizer, and since you’re likely going to build a custom class, use delegation.
Accumulating rotation counts
If you simply note the angle and send off messages during touch changes, it’ll sometimes work. However, if you’d like to implement hysteresis (e.g. this rotary dial will only rotate once clockwise, then it tightens up), you’ll need to accumulate rotation counts for both clockwise and counter-clockwise directions.
Fortunately, you can assume that a) the touch events will not get dropped too often, and b) simply comparing the current angle against the past angle, seeing if they cross quadrant boundaries, will suffice.
For example:
If the touch moved from the top-left quadrant into the top-right quadrant, add one to the rotation count.
If the touch moved from the top-right quadrant into the top-left quadrant, subtract one from the rotation count.
(Yup, this actually works.)
Emitting the correct, accumulated rotation
If you want to emit rotation information exactly like how UIRotationGestureRecognizer did, there will be four things you’re tracking.
Starting Angle: The angle between a connection from the anchor point to the starting touch, and a connection from the anchor point to a fixed reference point.
Current Angle: The angle between a connection from the anchor point to the current touch, and a connection from the anchor point to a fixed reference point.
Rotation Count: The number of clockwise revolutions derived from continuously comparing the current value of Current Angle against its last value (as talked about in the last section). If the touch is moving counter-clockwise, then this count will go into negative.
You’ll provide Rotation Count * 2_PI + (Current Angle - Starting Angle) as the rotation.
OK, I would take a different approach. First, you want to create a RotaryDial class to encapsulate all of the behavior. Then you can just plug it into any view as you see fit.
To keep things simple I would consider making each number button a movable UIImageView, call it RotaryDialDigit or something like that. You would instantiate and place ten of those.
The dial "frame" would just tag along for the ride as the user moves one of the RotaryDialDigit buttons. It's just an image (unless you want the user to be able to touch it and do something with it.
From there, knowing which button is being held down and limiting its rotation to a given direction as well as stopping at at the bar is fairly easy stuff.
By using a protocol you can then have the RotaryDial instance tell the container when a number has been dialed. To the container RotaryDial would feel like a keypad sending a message every time a button is pressed. You really don't want the container bothering with anything other than completed number selections.
To detect which number is touched, when you create each number you should set the tag value of its UIView. Then when the user touches the number you can detect which UIView object it was by checking that tag value.
For the rotation problem, I'd suggest looking at how you are calculating the angle. At a guess I'd say for numbers greater than 4 (which you discern from the tag) you need to do something like subtract the angle you are currently calculating from 360 degrees (well 2Pi). (But I have a head cold right now so the actual math is escaping me :-) )
Without seeing your code, I assume the numbers are a static image and you are animating the finger holes as they rotate past each number. If so:
Detecting which number: defina a CGRect around each button. When the user taps the screen, check which rectangle contains the tap location.
Controlling rotation direction: as the user drags their finger, comtinuously calculate the angle from the dial stop to the current tap location. If the angle moves in the wrong direction, dont update the position of the finger hole. Note that trig functions return vales from +Pi to -Pi radians. For the digits greater than 5, rather than handle negative angles you will probably want to add 2Pi radians ( or 360 degrees) to the angle.
Rotating wrong way: the digits below 5 are generatting angles in the range of 0 to -Pi. Without seeing code, I suspect adding 2Pi to the angle will correct your rotation direction.
Here is a better dial:
Have fun!
I want to be able to detect someone's finger drawing a circular motion on the screen - as if they were drawing an 'O'. Is this possible with UIGestureRecognizer?
I think the answer to this depends on your definition of circular motion and how you intend to use it. For example, do you want to know how many degrees along a circle the users finger has travelled? Or, do you only care about a circle being completed? What is the degree of accuracy you require? Do you want to allow for the motion to be interrupted or does this have to be more of a touch-down > draw-circle > touch-up (in other words, single motion)?
One approach would be to define a bunch of rectangular zones along the circumference and detect if the user is touching these in sequence. This can provide you with direction and a coarse indication of angle.
Another approach is to store the points between touch down and touch up and do some filtering and curve fitting to figure out what shape is approximated by the points. First low-pass-filter using a basic FIR filter and then look at the dx and dy from point to point. A circle (as a series of arcs) will have to fall within a certain range of slope changes from point to point, otherwise you have some other shape.
Yet another approach is to use a Neural Network to take the points and tell you what the shape looks like.
I think this may be what you need
How to detect circular gesture via Gesture Recognizer?
Instead using a gesture recognizer, this project reacts to circular motions tracking the angle of UITouch events.
My answer to my question:
I used this: http://iphonedevelopment.blogspot.com/2009/04/detecting-circle-gesture.html
.. but turned the CircleView into a custom UIGestureRecognizer. Everything lovely.
No, it doesn't recognize natively a circular motion.
You have to implement your own method to do that.
Here's how i needed to do it using the touches callbacks in my view controller but this could be made into a gesture too. Note, I was trying to detect multiple circle motions (2 or more clockwise or counterclockwise circles made during a touch event.
Store touchesMoved CGPoints in an array.
Create a min/max rect of all the points in your history array.
Divide this min/max rect into 4 smaller rects.
Assign each history point a quadrant using CGRectContainsPoint() for each of the 4 quadrants
A clockwise motion will have quadrants ascending. A counter-clockwise motion will have quadrants descending.
Check the ratio of width/height if you want to detect circles vs ovals
I have subclassed UIImageView to create a soccer ball.
The ball bounces and moves along an x & y axis, and depending on where you touch the ball, the ball will move as you'd expect a soccer ball would.
My problem is that I would like to rotate the Ball(UIImageView), but still know the x & y positions from it's original position.
I am rotating it with the following code:
ball.superview.transform = CGAffineTransformMakeRotation(M_PI+(ball.center.x*.015));
ball.transform= CGAffineTransformMakeRotation(M_PI+(ball.center.x*.015));
When I rotate it, the x & y position also rotate. Can I somehow get the x/y distance from the centre of the UIImageView? Any other ideas?
Thanks,
James.
I think if you set the anchor of your CALayer of the UIIMageView to be the center of the UIImageView youll be ok, right now its set to the upper left corner and so are expiriencing the x and y moving.
Why are you rotating the superview also? If you don't do that the center x,y will not be affected.
Why not just use ball.center as the position. This way, rotations will have no effect on the position (assuming your image is correctly centered).
When changing the center point of an 10 degrees rotated view, the specified coordinates for the center point will not match the coordinate system of the superview.
As an example, when you want to go straight up by y - 50, and no horizontal movement (i.e. x = theRotatedView.center.x), the shift in y-direction will be rotated. The view will go up and right, and not just up.
The rotation is done on the view, not on the layer.
I could wrap it in a superview that does the movement, while the subview does the rotation. Then I had no problems with converting. But maybe there is some simple solution. I just want to move the center of an rotated view as if the view was not rotated, i.e. when wanting y to be decremented by 10, just do so without worrying about the rotated coordinates. Are there any methods or functions for converting between the coordinate systems, so that I can just specify the center point coordinates in superview coordinates and it will just be right when applying these to the rotated view's center property?
Look at the CGAffineTransform methods, such as CGAffineTransformMake, for an easier way to generate the transforms you need. You can combine rotation and translation in one matrix.
You can multiply your coordinates by a transformation matrix. This puts your coordinates into your parent view's "coordinate space". You can also use the inverse matrix of the parent view to take coordinates that are in the parent view and return them to "world space".
http://en.wikipedia.org/wiki/Rotation_matrix
Read further down the page for pseudo-code examples.