Drawing on the iPhone in objective c [closed] - iphone

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

Related

How to connect two buttons( dots) with a line in iOS? [duplicate]

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.

Implementing Eraser functionality for drawing app

I was following this great tutorial at ray wenderlich's site about creating a simple drawing app with UIKit.
http://www.raywenderlich.com/18840/how-to-make-a-simple-drawing-app-with-uikit
the tutorial is great and everything is working. the problem that I have is that when it came to creating the eraser functionality the solution proposed by ray was to use the brush with the same color that the background has. To me this doesn't seem like a great solution. what if the background is not a solid color like a gradient or any image like in so many coloring book apps.
So basically the question is: is there a way to remove color (convert all pixels in that area to transparent maybe) from a UIImageView at a given location?
Any help or pointers would greatly be appriciated. Thanks
I have the same issue in my app after the long search i found the simple solution for this issue.
i just used touches methods of the UIViewController
The below is the my approach,
Code:-
#pragma mark touches stuff...
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
lastTouch = [touch locationInView:self.editedImageView];
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
currentTouch = [touch locationInView:self.editedImageView];
CGFloat brushSize;
if (isEraser)
{
brushSize=eraser;
}
else
{
brushSize=mark;
}
CGColorRef strokeColor = [UIColor whiteColor].CGColor;
UIGraphicsBeginImageContext(self.editedImageView.frame.size);
CGContextRef context = UIGraphicsGetCurrentContext();
[self.editedImageView.image drawInRect:CGRectMake(0, 0, self.editedImageView.frame.size.width, self.editedImageView.frame.size.height)];
CGContextSetLineCap(context, kCGLineCapRound);
CGContextSetLineWidth(context, brushSize);
if (isEraser) {
CGContextSetStrokeColorWithColor(UIGraphicsGetCurrentContext(), [UIColor colorWithPatternImage:self.im].CGColor);
}
else
{
CGContextSetStrokeColorWithColor(context, strokeColor);
CGContextSetBlendMode(context, kCGBlendModeClear);
}
CGContextBeginPath(context);
CGContextMoveToPoint(context, lastTouch.x, lastTouch.y);
CGContextAddLineToPoint(context, currentTouch.x, currentTouch.y);
CGContextStrokePath(context);
self.editedImageView.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
lastTouch = [touch locationInView:self.editedImageView];
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
}
The Inputs:
self.editedImageView.image = "Your Custom image";
self.im = "Your Custom image";
The simple solution of your problem will be :-
CGContextSetStrokeColorWithColor(UIGraphicsGetCurrentContext(), [UIColor colorWithPatternImage:self.im].CGColor);
Note:
This not unerase it again drawing the image over
Update:-
self.im = "Your Custom image";
this will be like this....
-(void)eraserConfigure
{
UIImageView *resizeImage=[[[UIImageView alloc]initWithImage:editedImage]autorelease];
/*UIImage */self.im=[UIImage imageFromView:resizeImage scaledToSize:CGSizeMake(self.editedImageView.frame.size.width, self.editedImageView.frame.size.height)];
}
Use the brush but for the color use:
[UIColor clearColor]
I could solve the issue using below code:
CGContextSetBlendMode(UIGraphicsGetCurrentContext(),kCGBlendModeClear);
Reference

I want to draw a rectangle like shape with drag-able corners in IOS

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

(iphone) a very simple Iphone game

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

How do you make an image follow your finger in objective-c? [closed]

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 9 years ago.
How do you make an image follow your finger in objetive-c?
Create your UIView and configure it (or any subclass thereof such as a UIImageView)
Set the position of your Image to be where the user is touching:
There are four delegate methods for accepting touch events which are a part of any class that inherits from UIResponder such as a UIView. Use the delegate method that is most appropriate to you. If you want it to follow your finger, this will be -touchesMoved:
- (void) touchesMoved:(NSSet*)toucheswithEvent:(UIEvent*)event {
CGPoint pt = [[touches anyObject] locationInView:self];
myImageView.center = pt;
}
Other delegate methods available to you are:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
I wrote an example application that does exactly what you want. It's a demo of drawing Quartz 2D graphics, but it draws a red square and black circle where you drag your finger and should be simple enough to follow:
alt text http://brockwoolf.com/shares/stackoverflow/3445494/screen.png
Download Xcode project (32kb)
there is an exellent post here.
by Divan Visagie
here is the relevant code (taken from the link above):
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//Find the path for the menu resource and load it into the menu array
NSString *menuPlistPath = [[NSBundle mainBundle] pathForResource:#"Menu" ofType:#"plist"];
menuArray = [[NSArray alloc] initWithContentsOfFile:menuPlistPath];
//add some gestures
// UISwipeGestureRecognizer *swipeLeft = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:#selector(handleSwipeLeft:)];
// [swipeLeft setDirection:UISwipeGestureRecognizerDirectionLeft];
//[self.view addGestureRecognizer:swipeLeft];
// UISwipeGestureRecognizer *swipeRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:#selector(handleSwipeRight:)];
// [swipeRight setDirection:UISwipeGestureRecognizerDirectionRight];
//[self.view addGestureRecognizer:swipeRight];
}
float difference;
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
CGPoint contentTouchPoint = [[touches anyObject] locationInView:content];
difference = contentTouchPoint.x;
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
CGPoint pointInView = [[touches anyObject] locationInView:self.view];
float xTarget = pointInView.x - difference;
if(xTarget > menuTable.frame.size.width)
xTarget = menuTable.frame.size.width;
else if( xTarget < 0)
xTarget = 0;
[UIView animateWithDuration:.25
animations:^{
[content setFrame:CGRectMake(xTarget, content.frame.origin.y, content.frame.size.width, content.frame.size.height)];
}
];
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
CGPoint endPoint = [[touches anyObject] locationInView:self.view];
float xTarget = endPoint.x - difference;
if(xTarget < (menuTable.frame.size.width/2))
xTarget = 0;
else
xTarget = menuTable.frame.size.width;
[UIView animateWithDuration:.25
animations:^{
[content setFrame:CGRectMake(xTarget, content.frame.origin.y, content.frame.size.width, content.frame.size.height)];
}
];
}
The Apple Sample Code library comes with a well-written example, named Touches. It also demonstrates the new UIGestureRecognizers feature in iOS 4.0.