Play & animate with UIButton? - iphone

I am doing some RnD work, looking forward for experts suggestion:
I have to create a custom Button with any defined background image. So that user can throw that button in any direction with smooth way, under which total covered distance is directly proportional to pressure applied on UIButton to throw it.
Can any one guide me so that i can cover this task ?

A good start would be to attach a UIPanGestureRecognizer to your button (or view or whatever), then use velocityInView:. From UIPanGestureRecognizer.h:
// velocity of the pan in pixels/second in the coordinate system of the specified view
- (CGPoint)velocityInView:(UIView *)view;
Using the velocity (possibly in conjunction with translationInView:) you can then move your button according to the speed and velocity of the gesture.

Related

How to make a menu with icons spinning in a circle?

I am trying to create a menu for my app with a few icons in a circle. User should be able to spin this menu, making the icons change their positions around this circle path, but not rotating themselves. I read this earlier http://www.raywenderlich.com/9864/how-to-create-a-rotating-wheel-control-with-uikit so I can see how to follow the finger movement, but I need this menu to have inertial spin after the touch ends. I have 2 questions about how to do this.
First one, what's the best way to make animation with icons moving around in a circle? It should be slowing down until it stops and, if user moves his finger fast enough, should be able to do more than one full circle.
Second, how do I measure speed of finger movement at the end of it? I tried to use locationInView and previousLocationInView and just spin it by difference of angles between them multiplied by some constant. Problem is, when I keep my finger in one place for a while and take it up, I still get inertial movement of the circle and in this case I don't want it to move at all.
You want to use a scroll view. Specifically you want a hidden scroll view where you attach the pan gesture recogniser from the scroll view to your custom menu view. Then you implement the delegate methods of the scroll view to redraw your menu. This WWDC video has a good overview of the process. The benefit of this approach is that you get true iOS style acceleration and deceleration for free. You don't need to worry about finger position or speed, only the content offset of the scroll view.
Unless you want to spin your finger round in a circle with the menu items. That's a different ball game...
In theory, the same approach as above can be used for spinning your finger in a circle. You would need to ensure that directionalLockEnabled was set to NO on the scroll view. The problem is that the calculations to determine the rotation of your menu view are a lot more complex. Probably you would want to be modal and check if the scroll view is dragging in the callbacks. If it is dragging you would use the touches on the pan gesture to find the exact finger location to set the rotation. You'd also want to maintain data on the instantaneous direction of finger movement so that when the touch is released... If it isn't dragging then you use the scroll view content offset to apply the deceleration effect on the rotation (using the scroll direction just before the touch was released to know how to use the content offset changes).

How to gently drag panel from offscreen like JetBlue iPhone app

I'm looking for a way to slide a partially concealed tool panel from off screen like the JetBlue iPhone app does. I know how to do this with regular swipe gesture recognizers, but that app has a certain threshold, after which the panel "snaps" to the on-screen position, otherwise it hides back offscreen.
How can I implement this kind of swipe-to show, but with a threshold kind of gesture recognizer? Are there any open source projects that do this kind of UI manipulation?
I have a similar interface element in an app I've written. My interface element is a UIViewController for the entire tool panel. I put a UIButton over the gripper illustration, change the button's type to custom so it visually disappears. I connect Touch Drag Inside and Touch Drag Outside to an IBAction that adjusts the position of the panel according to where the drag moves. I connect Touch Up Inside and Touch Up Outside to an IBAction that finalizes the positioning of the view. If the touch up event happens too close to the bottom, I just close the panel. If it happens anywhere higher than that threshold I open the panel. I use UIView's animation methods to smooth out these transitions. The over extension element seen in the JetBlue app can be accomplished in the drag event handler. As the panel gets closer and closer to the limit, open the view a smaller and smaller amount with each move of the touch higher. Then in the finalization, just animate the panel back down into it's preferred ending position.
The JetBlue app differs from my app in that I have a small gripper area, but JetBlue's app allows you to swipe the whole panel to adjust position. To match that functionality, I would adjust my implementation to totally cover the panel with buttons. Each would respond to my drag events with the addition that dragging would set a flag. Then my touch up event handler would check if the flag was set. If so, finalize the dragging of the panel. Otherwise, perform the appropriate action associated with each button.
If you can already implement the basics with gestures, then you're almost there!
To be honest, while I've done exactly this in my application, I use the old fashioned touchesBegan, touchesMoved, etc.
In terms of gestures, you'll have to use UIPanGestureRecognizer so you can have full control of the drag. UISwipeGestureRecognizer only recognizes swipes.
Anyway, after a certain point, you simply translate the panel only a fraction of the distance the person dragged.
CGRect newPanelFrame = panel.frame;
if (newPanelFrame.origin.y + dragOffset > 275) {
newPanelFrame.origin.y += dragOffset / 2.0;
}
panel.frame = newPanelFrame;
In touchesEnded:withEvent: or if (gestureRecognizer.state == UIGestureRecognizerStateEnded)
CGRect newPanelFrame = panel.frame;
if (newPanelFrame.origin.y > 275) {
newPanelFrame.origin.y = 275;
}
panel.frame = newPanelFrame;
The reason why I've never bothered with the UIPanGestureRecognizer is because I could never figure out how to get the non-cumulative translation (translationForView: is cumulative), which is necessary if you want to essentially slow down the drag after the threshold.
I was just doing some research into achieving a similar effect, stumbled across this post, and as a result decided to give JetBlue a try.
After playing with the sliding panel for a bit, I'm actually thinking the JetBlue guys actually went about this in a slightly more different manner.
The motions of the slider in the JetBlue app seem to handle much nicer than what you could do with a collection of UIGestureRecognizers; it's capable of animating at different velocities depending how quickly the user swipes it, and the rubber-banding compensates for this properly too.
So on that note, I actually think that they're not using UIGestureRecognizers, but that panel is actually just a standard UIScrollView aligned to the bottom of the app window, and with a bit of extra logic (probably applied via the delegate) that just makes sure it isn't possible for the scroll view to stop animating between the 'open' and 'shut' state.

round image button VS square controller

I have a custom button with a round image.
The problem is that the controller is square by default so whenever i click on the corners of the image, the button responds calling the associated method, when in reality he shouldn´t because there is no image on the corners, so the button shouldn´t respond.
Anyone knows a work around this bug?
One way to handle this is to reduce the size of the button. It'll still be a rectangle (or square) though. More involved way would be to implement - (UIView *) hitTest: (CGPoint) pt withEvent: (UIEvent *) event & handle which area of the button was clicked & if its not in the circle you defined ignore that touch event.
But if you ask me, let it be the way it is. In touch, people are rarely that accurate (compared to a mouse click). So the rectangle button provides more area for the user to tap on a button even if he is slightly off the mark.
You can't solve this with UIControl settings. You'll have to do custom hit detection and determine if the image is under the tap. You can do this using UITapGestureRecognizer.

How do I detect a swiping / flicking gesture?

I want to allow the user to flick a ball that is on screen. The user would tap on the ball and then flick, the velocity / speed of the flick would then dictate initial velocity.
I took a look at UISwipeGestureRecognizer but it seems like that is more targeted at navigation than flicking.
How do I go about implementing this?
I am using Cocos2d and Box2d.
Have you considered UIPanGestureRecognizer? You can get velocity data from that ([panGesture velocityInView:]), and distinguish the initial velocity of the 'swipe' using the state property on the gesture recognizer.
Or is that not sufficient?

iPhone button with non-rectangle shape?

How can I get a non-rectangular shaped button?
For example I do have a PNG image with alpha transparency.
How can I set the shape of a button to this image without the transparent color.
Like the others say you should have a reasonable surface for registering touch events, but I'm sure you know that and have your reasons so I'll just tell you how I did it:
I needed to do this not so long ago and what I did is what Sixten Otto just suggested. There are some hints in my original question ("UPDATE" section) for getting the alpha value for your image at a certain point:
How to create a transparent window with non-rectangular buttons?
Edit: I suggest subclassing UIControl in the example below but if you don't need any special behavior on your button apart from the "non-rectangleness" of it then just subclassing a borderless UIButton set up with your PNG will do the job and require less work. You have more control on the control's behavior by subclassing UIControl and doing it the "hard way" though.
I would suggest that you subclass UIControl and override the touch event methods, then check for alpha under the tapped point and not handle the event if alpha == 0. For drawing you override drawRect: and use the NSImage's drawInRect:fromRec:operation:fraction: method in there to draw your image in the control's frame.
First you need to load the image and get a bitmap representation of it:
buttonImage = [NSImage imageNamed:#"myButtonImage"];
buttonImageRep = [[buttonImage representations] objectAtIndex:0];
Then you can draw it to the control's view: (where stateImage is a pointer to the image that must be drawn depending on if the button is pressed or not)
- (void)drawRect:(NSRect)aRect {
[stateImage drawInRect:[self bounds] fromRect:NSMakeRect(0.0,0.0,[buttonImage size].width,[buttonImage size].height)
operation:NSCompositeSourceOver fraction:1.0];
}
At this point you have drawn your button with your png image. You can override the touch event methods and handle the event if the alpha is not 0:
NSColor *colorUnderMouse = [buttonImageRep colorAtX:mouse.x y:mouse.y];
float alpha = [colorUnderMouse alphaComponent];
That's what I did and it works wonderfully. Hope this helps!
N.B: My example is for the Mac but it should also work on the iPhone, maybe with some slight modifications.
It sounds like you are looking to have the clickable area of the button exactly match the PNG you are using.
If that is what you are looking for, I would firstly say to not do that. The iPhone is pressed using a finger, which generally doesn't have the accuracy to distinguish such a small region.
However if you are stuck on the idea, then the solution is to not use buttons at all, instead handle the click in a parent frame and manually interpret the X/Y value of the click to determine if it is in some bounding region (In the case of a rounded edge button, would likely consist of oring the result of checking 4 circles and 2 rectangles)
Edit:
Realizing part of your original question, I noticed you mentioned you wanted to handle the function automatically based on the Alpha channel. While I would recommend my method of bounding regions, you could in theory accomplish this by sampling the PNG to test the Alpha channel at a value offset by the origin of the button. Potentially even doing this in a normal button's click event.
Rectangular buttons are a button type, you can use the custom button type and assign an image to get rid of the rectangular edges of the button...heres a reference to button types http://developer.apple.com/iphone/library/documentation/UIKit/Reference/UIButton_Class/UIButton/UIButton.html#//apple_ref/doc/c_ref/UIButtonType and to UIButton http://developer.apple.com/iphone/library/documentation/UIKit/Reference/UIButton_Class/UIButton/UIButton.html
As Guvante says, it's really not a good idea to rely on precision touches. Apple, for instance, recommends that controls be at least 44px across.
I'd recommend using a UIButton of type UIButtonTypeCustom, set the button's image to your PNG, and register for touch events (see here for more on event handling). Then, in your action method, you can get the coordinates of the touch out of the event, and test those coordinates against the alpha of your image to see whether you should treat it as a "real" touch or not.
Another option could be to split your button up into multiple, rectangular parts.
#Form right about using 'drawRect' to implement custom shape for button.
But better method to exam touch inside or not inside button is using of
- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event;
You can create your button transparent for touches in some parts.
If you can't use custom image for button (for example if you draw text on the button) you can use new method to draw subviews hierarchy into a image:
- (BOOL)drawViewHierarchyInRect:(CGRect)rect afterScreenUpdates:(BOOL)afterUpdates;