It seems implied from the question that you want the user to be able to tap anywhere on the screen and have an image drawn where they tap? As opposed to tapping in a designated place and having the image appear there?
If so, you re probably going to have to go with a custom view. In that case, you d do something like the following:
- Create a subclass of
UIView
.
- Override the
touchesBegan
method. Call [[touches anyObject] locationInView:self]
(where touches
is the first argument to the method, an NSSet
of UITouch
objects) to get the location of the touch, and record it.
- Override the
touchesEnded
method. Determine the location touches ended at using the same method as in step 2.
- If the second location is near the first, you ll want to place your image at that location. Record that location and call
[self setNeedsDisplay]
to cause the custom view to be redrawn.
- Override the
drawRect
method. Here, if the location has been set in step 4, you can use the UIImage
method drawAtPoint
to draw your image at the selected location.
For further details, this link might be worth a look. Hope that helps!
EDIT: I ve notice you ve asked essentially the same question before. If you re not happy with the answers given there, it s generally considered better to "bump" the old one, perhaps by editing it to ask for further clarification, rather than create a new question.
EDIT: As requested, some very brief sample code follows. This is probably not the best code around, and I haven t tested it, so it may be a little iffy. Just for clarification, the THRESHOLD
allows the user to move their finger a little while tapping (up to 3px), because it s very difficult to tap without moving your finger a little.
MyView.h
#define THRESHOLD 3*3
@interface MyView : UIView
{
CGPoint touchPoint;
CGPoint drawPoint;
UIImage theImage;
}
@end
MyView.m
@implementation MyView
- (id) initWithFrame:(CGRect) newFrame
{
if (self = [super initWithFrame:newFrame])
{
touchPoint = CGPointZero;
drawPoint = CGPointMake(-1, -1);
theImage = [[UIImage imageNamed:@"myImage.png"] retain];
}
return self;
}
- (void) dealloc
{
[theImage release];
[super dealloc];
}
- (void) drawRect:(CGRect) rect
{
if (drawPoint.x > -1 && drawPoint.y > -1)
[theImage drawAtPoint:drawPoint];
}
- (void) touchesBegan:(NSSet*) touches withEvent:(UIEvent*) event
{
touchPoint = [[touches anyObject] locationInView:self];
}
- (void) touchesEnded:(NSSet*) touches withEvent:(UIEvent*) event
{
CGPoint point = [[touches anyObject] locationInView:self];
CGFloat dx = point.x - touchPoint.x, dy = point.y - touchPoint.y;
if (dx + dy < THRESHOLD)
{
drawPoint = point;
[self setNeedsDisplay];
}
}
@end