This question already has answers here:
draw line between two points in iphone?
(3 answers)
Closed 9 years ago.
I want to make a project in which I have to touch one dot and connect it with another dot and after connect it to another dot. When I connect one dot with another dot the line will create between them.
Actually when I click/ touch one dot The line will show and When I touch second dot the line will create between the two dots.
I am not able to do this yet, I am trying and searching on the net but unable to find the solution yet.
This is my need Like this one https://play.google.com/store/apps/details?id=zok.android.dots&hl=en
I think this is done by UIGesture Recogniser? Or is this something else? How I can achieve this?
Any Idea or suggestions from experts would be highly welcome.
Modify this code according to your requiements
CGContextRef context = UIGraphicsGetCurrentContext();
UIColor *currentColor = [UIColor blackColor];
CGContextSetStrokeColorWithColor(context, currentColor.CGColor);
CGContextSetLineWidth(context, 2.0);
CGContextBeginPath(context);
CGContextMoveToPoint(context, touchStart.x, touchStart.y);
CGContextAddLineToPoint(context, touchEnd.x, touchEnd.y);
CGContextStrokePath(context);
#Nisha:
Make gloabal instances of CGPoint touchStart and touchEnd and get them like this:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
touchEnd = CGPointZero;
touchStart = CGPointZero;
UITouch *touch = [touches anyObject];
CGPoint point = [touch locationInView:self];
NSLog(#"start point >> %#",NSStringFromCGPoint(point));
touchStart = point;
}
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint point = [touch locationInView:self];
touchEnd = point;
[self setNeedsDisplay];
}
You can store the touched locations in two different CGPoint with the help of the touchedEnded method.
Then, when you have your two points, you can add a new UIView as subview which is aware of the two CGPoint and will draw a line in its drawRect method. Or do it in the current view, by calling [view setNeedsDisplay] to trigger its own drawRect method.
Check out this link.
If it is possible for you please get the coordinates of two button with UI touch methods. You can find the touched locations in two different CGPoint with the help of the touchedEnded method.To find touch location documentation is here
After getting the location of UIButtons on your view you can draw the line between then with this method-
- (void)drawRect:(CGRect)rect
{
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSaveGState(context);
CGContextSetStrokeColorWithColor(context, [[UIColor blackColor]CGColor]);
CGContextSetLineWidth(context, 1.0);
CGContextMoveToPoint(context, startPoint.x, startPoint.y);
CGContextAddLineToPoint(context, endPoint.x, endPoint.y);
CGContextStrokePath(context);
CGContextRestoreGState(context);
}
Hope this helps
Try below steps.
Create one subclass of UIView. Add your UIButtons on it.
Implement Touches delgates, like touchesBegan, moved, end.
Inside touchesBegan check if touch isinsideview:myButton1 then make a flag true.
EDIT:
UITouch *touch = [[UITouch alloc] init];
touch = [touches anyObject];
CGPoint point = [touch locationInView:self];
if(CGRectContainsPoint(myButton1.frame, point))
NSLog(#"Inside myButton1");
Another way to test if subview is hit by touches is
CGPoint pt = [[touches anyObject] locationInView:self.view];
UIView *touchedView = [self.view hitTest:pt withEvent:event];
inside touches moved check if flag true then drawline()... and keep checking if touches are in insideview:myButton2. call setNeedsDisplay.
Now you will get number of ways and sample code to draw line in UIView. Just apply above logic.
Related
I want to overlay a a box shape over a photograph and allow the user to select each corner, and drag the corners to where they want.
I could use 4 invisible buttons(to represent each corner) that respond to drag events to get the x,y points for each corner, but is there some line drawing functionality available in xcode without touching any of the game api classes? I guess I want to draw lines onto a UIView.
Many Thanks,
-Code
Make a subclass of UIView to represent your view. Add a UIImageView to your view. This will hold the image with user's drawing.
Enable user interaction in the UIView sub-class.
self.userInteractionEnabled = YES;
Detect the starting tap by implementing this method in your subclass:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
// We are starting to draw
// Get the current touch.
UITouch *touch = [touches anyObject];
startingPoint = [touch locationInView:self];
}
Detect the last tap to draw straight line:
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
endingPoint = [touch locationInView:self];
// Now draw the line and save to your image
UIGraphicsBeginImageContext(self.frame.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context, 10);
CGContextMoveToPoint(context, NULL, startingPoint.x, startingPoint.y);
CGContextAddLineToPoint(context, NULL, endingPoint.x, endingPoint.y);
CGContextSetRGBFillColor(context, 255, 255, 255, 1);
CGContextSetRGBStrokeColor(context, 255, 255, 255, 1);
CGContextStrokePath(context);
self.image = UIGraphicsGetImageFromCurrentImageContext();
CGContextRelease(context);
}
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
I´m quite new to programming and i have sort of half made my (simple) app but i want to know how to draw an picture on the screen (the user draws the picture) and then use that image for the game to just move left and right (and to check if it is colliding with another image).
I've got this..
float pointx;
float pointy;
- (void)drawRect:(CGRect)rect {
CGColorRef blue = [[UIColor blueColor] CGColor];
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextClearRect(context, self.bounds);
CGContextSetFillColorWithColor(context, blue);
CGContextFillRect(context, CGRectMake(pointx, pointy, 10, 10));
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch=[[event allTouches]anyObject];
CGPoint point = [touch locationInView:touch.view];
pointx = point.x;
pointy = point.y;
[self setNeedsDisplay];
}
but then when i press on the screen a blue square goes to the finger, but dues not draw anything...
Create a class which is a subclass of UIView... then add these lines of code in tat...
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
gestureStartPoint = [touch locationInView:self];
[currentPath moveToPoint:(gestureStartPoint)];
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
currentPosition = [touch locationInView:self];
[currentPath addLineToPoint:(currentPosition)];
[self setNeedsDisplay];
}
- (void)drawRect:(CGRect)rect {
[[UIColor redColor] set];
[currentPath strokeWithBlendMode:kCGBlendModeNormal alpha:1.0];
}
in the header file declare the following.....
CGPoint gestureStartPoint,currentPosition;
UIBezierPath *currentPath;
and declare a property...
#property(nonatomic,retain)UIBezierPath *currentPath;
in the initWIthFrame method inside if block add these lines
currentPath = [[UIBezierPath alloc]init];
currentPath.lineWidth=3;
Create a viewcontroler class then add these lines of code in loadVIew method..
mainView=[[sampleView alloc]initWithFrame:CGRectMake(0, 0, 320, 480)];
mainView.backgroundColor=[UIColor whiteColor];
self.view=mainView;
where sampleView is the UIView subclass u created b4....
Hope this helps...
Drawing user generated pictures with Cocoa Touch is a 2 step process. A UIView will only draw the latest touch you hand it after clearing all the previously user drawn stuff.
One possible solution is to save all the user touches in a history array and (re)draw all of them into the view after any new touch is added. But this can be very slow, depending on the amount of drawing required.
Another possible 2 step method is to create your own bitmap drawing context. First draw your new latest thing into this context, which will have kept the older portions of the drawing if configured correctly, then draw this context into the UIView (or convert the bitmap to an image displayed in a layer over the view).
How is it possible to drag a UIImageView but only within a certain area of the screen? My code currently looks like this:
- (void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *touch = [[event allTouches] anyObject];
touch.view.frame = CGRectMake(104, 171, 113, 49);
if([touch view] == toggle)
{
CGPoint location = [touch locationInView:self.view];
CGPoint newLocation = CGPointMake(toggle.center.x, location.y);
toggle.center = newLocation;
NSLog(#"%f \n",toggle.center.y);
}
}
I want to be able to drag the image only within the frame i have defined.
You can use CGRectContainsRect(rect1, rect2) to check if the first rect is completely inside of the second
bool CGRectContainsRect (
CGRect rect1,
CGRect rect2
);
When you are using UIViews and want to see if one view falls completely within the frame of a second, a related function CGRectContainsRect will do the checking for you. This does not check for an intersection; the union of both rectangles must be equal to the first rectangle for this to return true. The function takes two arguments. The first rectangle is always the surrounding item. The second argument either falls fully inside the first or it does not.
So your code could be something like this
CGPoint location = [touch locationInView:self.view];
CGPoint newLocation = CGPointMake(toggle.center.x, location.y);
CGRect r = CGRectMake(newLocation.x-self.frame.size.width/2,
newLocation.y-self.frame.size.height/2,
self.frame.size.width,
self.frame.size.height);
if(CGRectContainsRect(r, theOtherRect)){
toggle.center = newLocation;
NSLog(#"%f \n",toggle.center.y);
}
Other useful CoreGraphics functions: http://blogs.oreilly.com/iphone/2008/12/useful-core-graphics-functions.html
Another hint:NSLog(#"%#", NSStringFromCGPoint(toggle.center)) makes logging of CGTypes easier. use equivalently: NSStringFromCGRect(rect)
if (newLocation.y > NSMaxY(touch.view.frame)) newLocation.y = NSMaxY(touch.view.frame);
if (newLocation.y < NSMinY(touch.view.frame)) newLocation.y = NSMinY(touch.view.frame);
toggle.center = newLocation;
You can do the same for the x coordinate if you like.
I have a UIView subclass that I want to be able to move around within it's superview. When the user touches the UIView somewhere outside self.center but within self.bounds it "jumps" because I add the new location to self.center to achieve the actual move. To avoid this behavior I'm trying to set an anchor point that lets the user grab and drag the view anywhere within it's bounds.
My problem is that when I calculate the new anchor point (as shown in the code below) nothing happens, the view doesn't change position at all. On the other hand, if I set the anchor point to a precalculated point I can move the view (but then of course it "jumps" to the precalculated point). How come this doesn't work as expected?
Thanks.
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
// Only support single touches, anyObject retrieves only one touch
UITouch *touch = [touches anyObject];
CGPoint locationInView = [touch locationInView:self];
// New location is somewhere within the superview
CGPoint locationInSuperview = [touch locationInView:self.superview];
// Set an anchorpoint that acts as starting point for the move
// Doesn't work!
self.layer.anchorPoint = CGPointMake(locationInView.x / self.bounds.size.width, locationInView.y / self.bounds.size.height);
// Does work!
self.layer.anchorPoint = CGPointMake(0.01, 0.0181818);
// Move to new location
self.center = locationInSuperview;
}
As Kris Van Bael pointed out, your going to need to do the anchor point calculations in the touchsBegan:withEvent: method in order not to negate the movement. Additionally, since changing the layer's anchorPoint will move the view's initial position, you have to add an offset to the view's center point to avoid a 'jump' after the first touch.
You can do this by calculating (and adding to your view's center point) the offset based on the difference between the initial and final anchorPoints (multiplied by your view's width/height) or you could set the view's center to the initial touch point.
Something like this perhaps:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
CGPoint locationInView = [touch locationInView:self];
CGPoint locationInSuperview = [touch locationInView:self.superview];
self.layer.anchorPoint = CGPointMake(locationInView.x / self.frame.size.width, locationInView.y / self.frame.size.height);
self.center = locationInSuperview;
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
CGPoint locationInSuperview = [touch locationInView:self.superview];
self.center = locationInSuperview;
}
More info on anchorPoint's from apple's docs here and a similar SO question I referenced here.
You should update the anchorpoint only on TouchBegin. If you recalculate it all the time (TouchMoved), it is logical that the subview doesn't move.
Hi I want to implement a very simple game on iphone. I have a image and a text. If a user draw a line between the image and the text then it says "correct"
Now what I am thinking is that whenever a user touch the screen I will get the location (like X,Y) of that touching spot ( which method to call to get the location? ) and then I will draw a black dot there. If the user continuously and smoothly touch the screen then a line will form. Finally I will only need to judge whether the starting point of the line locates within the image and the ending point locates within the text.
I dont know whether my idea is a correct way to implement this kinda game. If it is how to get coordinate of touching spot and draw a black dot in that specific location?
Thanks for helping!
You may get the touch coordinates in touchesMoved of your view controller:
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint touch_point = [touch locationInView:self.view];
NSLog(#"x: %.0f y: %.0f", touch_point.x, touch_point.y);
}
To draw the line, you have add a view and draw line in drawRect:
- (void)drawRect:(CGRect)rect {
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context, 1.0);
CGContextSetStrokeColorWithColor(context, [UIColor orangeColor].CGColor);
// ...
CGContextMoveToPoint(context, one_x, one_y);
CGContextAddLineToPoint(context, two_x, two_y);
CGContextStrokePath(context);
// ...
}
where one_x one_y two_x two_x are coordinates for two points ..
This is exactly how the iPhone touch delegation works. It calls touchesBegan:, touchesMoved: and touchesEnded:. To draw the lines, you need this code:
CGContextRef context = UIGraphicsGetCurrentContext();
[current set];
CGContextSetLineWidth(context, 4.0f);
for (int i = 0; i < (self.points.count - 1); i++)
{
CGPoint pt1 = POINT(i);
CGPoint pt2 = POINT(i+1);
CGContextMoveToPoint(context, pt1.x, pt1.y);
CGContextAddLineToPoint(context, pt2.x, pt2.y);
CGContextStrokePath(context);
}
And with the help of this code, you should be ready to make it. If you need any help, just comment on this or make another question.
CGPoint pt = [[touches anyObject] locationInView:self];
[self.points addObject:[NSValue valueWithCGPoint:pt]];
[self setNeedsDisplay];