I got an UIImageView composed of two images with transparancy channel activated.
The view looks something like this:
image
I would like to be able to detect precisely the touches within the center circle and distinguish them from the ones in the outern circle.
I am thinking of a collision detection algorithm based the difference between two circles. First test in the outern layer to see if there is a collision at all and then in the inner layer. If in the inner layer then activate inner botton otherwise active outern button.
Any help or suggestion in this?
Shall I create a github repo so everyone could contribute in it?
Here something than can help you:
UIImageView *myImageView;
// In viewDidLoad, the place you are created your UIImageView place this:
myImageView.userInteractionEnabled = YES;
UITapGestureRecognizer *tapInView = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(tapInImageView:)];
[myImageView addGestureRecognizer:tapInView];
}
-(void)tapInImageView:(UITapGestureRecognizer *)tap
{
CGPoint tapPoint = [tap locationInView:tap.view];
CGPoint centerView = tap.view.center;
double distanceToCenter = sqrt((tapPoint.x - centerView.x)*(tapPoint.x - centerView.x) + (tapPoint.y - centerView.y)*(tapPoint.y - centerView.y) );
if (distanceToCenter < RADIUS) {
// It's in center
} else {
// Touch outside
}
Related
I have an image as a background and I want to make certain parts of this image clickable with zooming in and out , Is there any way to do something like that ??
Don't create a new view for your gesture recognizer. The recognizer implements a locationInView: method. Set it up for the view that contains the sensitive region. On the handleGesture, hit-test the region you care about like this:
0) Do all this on the view that contains the region you care about. Don't add a special view just for the gesture recognizer.
1) Setup mySensitiveRect
#property (assign, nonatomic) CGRect mySensitiveRect;
#synthesize mySensitiveRect=_mySensitiveRect;
self.mySensitiveRect = CGRectMake(0.0, 240.0, 320.0, 240.0);
2) Create your gestureRecognizer:
gr = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:#selector(handleGesture:)];
[self.view addGestureRecognizer:gr];
// if not using ARC, you should [gr release];
// mySensitiveRect coords are in the coordinate system of self.view
- (void)handleGesture:(UIGestureRecognizer *)gestureRecognizer {
CGPoint p = [gestureRecognizer locationInView:self.view];
if (CGRectContainsPoint(mySensitiveRect, p)) {
//Add your zooming code here
} else {
NSLog(#"got a tap, but not where i need it");
}
}}
The sensitive rect should be initialized in myView's coordinate system, the same view to which you attach the recognizer.
Apple has a demo app called PhotoScroller that implements a zoomable, scrollable set of images (in a page view controller, but you don't need that.) That would be a good starting point for what you need.
Their sample apps used to be built into the Xcode docs. Since Xcode 6 I haven't seen them linked in the docs any more.
You can download PhotoScroller from Apple's online iOS Developer Library. (link)
I have multiple controllers in my PageViewController and in one controller I have a few sliders. Now there is a problem that user must touch exactly slider circle (I am not sure about right expression, thumb? - that moving part) and I would like to increase area in which reacts slider and not the whole PageViewController. I tried these solutions but it doesn't help:
thumbRectForBounds:
- (CGRect)thumbRectForBounds:(CGRect)bounds trackRect:(CGRect)rect value:(float)value
{
return CGRectInset ([super thumbRectForBounds:bounds trackRect:rect value:value], 15, 15);
}
Increase hitTest area:
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
if (CGRectContainsPoint(CGRectInset(self.frame, 200, 200), point) || CGRectContainsPoint(CGRectInset(self.frame, 200, 200), point)) {
return self;
}
return [super hitTest:point withEvent:event];
}
I have these methods in my custom slider class because I would like to reuse this. Last thing what I found and not tried yet is create some object layer over slider which "takes" gesture and disable PageViewController but I am not sure how to do it and I am not sure if it's good/best solution.
I am not a big fan of the UISlider component because as you noticed, it is not trivial to increase the hit area of the actual slider. I would urge you to replicate the UISlider instead using a pan gesture for a much better user experience:
i. create a slider background with a seperate UIImageView with a slider image.
ii. create the PanGesture:
UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:#selector(handlePan:);
[imageView addGestureRecognizer:pan];
iii. implement handlePan Method:
- (IBAction)handlePan:(UIPanGestureRecognizer *)recognizer {
//pan (slide) begins
CGPoint translation = [recognizer locationInView:self.view];
translation.y = self.slideImage.center.y;
self.slideImage.center = translation;
if(recognizer.state == UIGestureRecognizerStateEnded) {
LTDebugLog(#"\n\n PAN, with spot: %f\n\n", self.slideImage.center.x);
//do something after user is done sliding
}
}
The big benefit of this method is that you will have a much better user experience as you can make the responsive UIImageView as big as you want.
Alternatively, you could subclass a UISlider and increase the hit space there, although in my experience this gives mixed results.
Hope this helps
In your CustomSlider class override thumbRectForBounds method:
Simply return rect value as you required:
- (CGRect)thumbRectForBounds:(CGRect)bounds trackRect:(CGRect)rect value:(float)value
{
return CGRectMake (bounds.origin.x, bounds.origin.y, yourWidthValue, yourHeightValue );
}
Change yourWidthValue and yourHeightValue as per your requirement. And then while using
Create object like below:
CustomSlider *slider = [[CustomSlider alloc] initWithFrame:CGRectMake(0, 0, 300, 20)];
[slider thumbRectForBounds: slider.bounds trackRect:slider.frame value:15.f]; // change values as per your requirements.
Hope this helps.
Create a custom thumb image which has a large empty margin and set that on your slider, like this:
[theSlider setThumbImage:[UIImage imageNamed:#"slider_thumb_with_margins"] forState:UIControlStateNormal];
To make the image, get a copy of the system thumb image using any one of a number of UIKit artwork extractors (just search the web for one). Open the thumb image in Photoshop and increase the canvas size by twice the margin you want to add. Make sure you change the canvas size and not the image size, as the image size will stretch the image to fill the new size. This will put empty space around the thumb which will be part of the hit-test area but since it is all transparent it won't change the look of the slider.
I have looked up all related questions to this question but nothing brought success.
The problem is probably pretty simple:
I want to detect a collision between two geometrical objects which are animated in a way they are hitting eachother at a given time.
In order to use the method CGRectIntersectsRect i have to init the UIImage excactly with the size of the actual image of the geometrical object so it returns only a collision if the images/frames really collide.
So how do i specify the postion to place my image i have intiliazid with initWithImage.
I can't use the Method initWithFrame:CGRectMake as i do not want a UIImageview shaped as a rectangle.
Examples which do not work:
circleYellow = [[UIImageView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height / 2, 50, 50)];
circleYellow.image = [UIImage imageNamed:images[arc4random() % 5]];
circleYellow = [[UIImageView alloc] initWithImage:[UIImage imageNamed:images[arc4random() % 5]]];
I would recommend you check out cocos2d. It has tools for handling sprites, updating their position through Actions (animations) on the screen, etc.
Detecting the collision of two sprites becomes something like:
-(void)update(float dt)
{
CGRect rect1 = [sprite1 boundingBox];
CGRect rect2 = [sprite2 boundingBox];
if (CGRectIntersectsRect(rect1, rect2))
{
// Do something about the collision...
}
}
And if you need more sophisticated modeling of the motion, or if you want to be able to collide arbitrary shapes and not just the bounding boxes, Box2D built in. There are lots of examples available for this as well.
Was this helpful?
UIImageView and it's superclass UIView always create rectangles. From the UIView class reference:
The UIView class defines a rectangular area on the screen ...
It sounds like SpriteKit may be what you need - check out the sprite kit programming guide.
I would recommend using the SpriteKit:
//Create a SpriteNode loading your image
SKSpriteNode *cicleYellow = [SKSpriteNode spriteNodeWithImageNamed:images[arc4random() % 5]];
//Set the size and the position of the Sprite
circleYellow.size = CGSizeMake(50,50);
circleYellow.position = CGPointMake(0, self.view.frame.size.height);
//Create a circlePhisicsBody and add it to the Sprite
SKPhysicsBody *circlePhisicsBody = [SKPhysicsBody bodyWithCircleOfRadius:cicleYellow.size.width/2.0f];
cicleYellow.physicsBody = circlePhisicsBody;
Check out the Apple documentation on how to use the Sprite Kit.
You would need some timer function to check that every now and then but the algorihm for detecting collisions among Rectangles is pretty straight forward (square A and square B):
//If any of the sides from A are outside of B
if( bottomA <= topB ) { return false; }
if( topA >= bottomB ) { return false; }
if( rightA <= leftB ) { return false; }
if( leftA >= rightB ) { return false; }
//If none of the sides from A are outside B return true;
If you need to do it for circles only here is a good tutorial: http://gamedevelopment.tutsplus.com/tutorials/when-worlds-collide-simulating-circle-circle-collisions--gamedev-769
I'm having trouble getting a repeatable background to work in my game menu.
The user can slide a finger across the screen to select a character to play.
I have a parallax effect working with various backgrounds as the characters slide into view.
Sample below.
- (void)didMoveToView:(SKView *)view
{
self.pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:#selector(dragScene:)];
self.pan.minimumNumberOfTouches = 1;
self.pan.delegate = self;
[self.view addGestureRecognizer:self.pan];
}
- (void)dragScene:(UIPanGestureRecognizer *)gesture
{
CGPoint trans = [gesture translationInView:self.view];
SKAction *moveSky = [SKAction moveByX:trans.x*0.03 y:0 duration:0];
[_skyBackground runAction:moveSky];
}
I would like to repeat the backgrounds. I know how to do this with automatically scrolling backgrounds but I can't seem to get it to work here. It needs to repeat in both directions, left and right.
Thanks for any help!
You can create two more background nodes - one to the left of your current background node and one to the right. Move them aswell any time you move your existing _skyBackground node.
Then, in the update method, check if any of the three nodes needs to be "shifted" - either to behind the other two or in front. You're basically swapping the three nodes' positions if needed.
-(void)update:(NSTimeInterval)currentTime {
//get the left background node (or if using an ivar just use _leftNode)
SKSpriteNode *leftNode = (SKSpriteNode*)[self childNodeWithName:#"leftNode"];
//my positioning might be off but you'll get the idea
if (leftNode.position.x < -leftNode.size.width*2)
{
leftNode.position = CGPointMake(leftNode.size.width, leftNode.position.y);
}
if (leftNode.position.x > leftNode.size.width*2)
{
leftNode.position = CGPointMake(-leftNode.size.width, leftNode.position.y);
}
//repeat the same for _skyBackground and _rightNode
}
You may need more than 3 images if there's a slight gap between images as they're shifted.
I have an iPad app (XCode 4.6, Storyboards, iOS 6.2). I have a scene made up like this:
UIView (subViewData - covers the right quadrant of #2, below and to the right not covering the times and names of #2- contains appointment info (cust name, and the duration is shaded)
UIView (subViewGrid - covers bottom half (in image, it contains times on the left margin and names across the top margin.)
UIScrollView (covers the bottom half view)
UIView ------- UIView (one on the top half of the window, the other on the bottom half)
UIViewController (named CalendarViewController)
This is the code to initialize the UITapGestureRecognizer found in -viewDidLoad of the CalendarViewController:
// setup for tap recognizer
UITapGestureRecognizer *fingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self
action:#selector(singleFingerTap:)];
fingerTap.numberOfTapsRequired = 1;
fingerTap.numberOfTouchesRequired = 1;
[subViewData addGestureRecognizer:fingerTap];
This is the code in subViewData (#1) that is NOT getting executed:
- (void)singleFingerTap:(UITapGestureRecognizer*)gesture {
CGPoint pt = [gesture locationInView:self];
UIView *v = [self hitTest:pt withEvent:nil];
if(v.tag == 100) // if this is for calendar, return
return;
CGRect dataRect = CGRectMake(110.0,48.0,670.0,1450);
CGPoint dataPoint = CGPointMake(pt.x, pt.y);
// check to see if point is within the rectangle
if(!CGRectContainsPoint(dataRect, dataPoint)) {
NSLog(#"\n\nNOT within subViewData");
return;
}
else {
NSLog(#"\n\nIS within subViewData");
}
}
The question is why is it not capturing the taps? Is the recognizer code supposed to be in the controller or the view that is supposedly getting the taps? I have read almost everything I can find on the subject, but can't find anything within this specific scenario. Help is greatly appreciated.
You say:
This is the code to initialize the UITapGestureRecognizer found in -viewDidLoad of the CalendarViewController
And that code says:
[[UITapGestureRecognizer alloc] initWithTarget:self
action:#selector(singleFingerTap:)];
Then you must put singleFingerTap: in CalendarViewController, because you have told the gesture recognizer that the target is self, and self is an instance of CalendarViewController.
You also say:
This is the code in subViewData (#1) that is NOT getting executed
But I do not know what "in subViewData" means; you did not mention anything called "subViewData" in your explanation of the interface. Anyway it doesn't matter. You've specified self so the code needs to be in self.
However, it sounds to me as if the view in question is never receiving the touch at all. Perhaps it is not exposed (i.e. it's covered by another view). Perhaps its userInteractionEnabled is NO. There could be lots of reasons.