I was using the drawing code from this tutorial to let someone draw in a small box: 开发者_JS百科http://www.ifans.com/forums/showthread.php?t=132024
The default code draws on the entire screen, how do you limit the drawing to a small box on the screen?
In this examples the touches and the drawing happen in the main view of the view controller:
UIGraphicsBeginImageContext(self.view.frame.size);
[drawImage.image drawInRect:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
etc...
So if you change the frame of that view to a smaller size, the drawing should be limited to the smaller size automatically.
Or you could "move" the touch recognition and the drawing to a another smaller subview:
- Create a new smaller subview.
- Add it to the main view.
- Add a UITapGestureRecognizer to the small view
- Handle the touches in the UITapGestureRecognizer action and do the drawing on the subview.
===== EDIT =====
Here is how to do it:
- (void)viewDidLoad{
[super viewDidLoad];
self.view.backgroundColor = [UIColor grayColor];
canvas = [[UIView alloc] initWithFrame:CGRectMake(200.0, 200.0, 300.0, 300.0)];
canvas.backgroundColor = [UIColor whiteColor];
[self.view addSubview:canvas];
UIImageView *iv = [[UIImageView alloc] initWithImage:nil];
iv.frame = canvas.frame;
[self.view addSubview:iv];
self.drawImage = iv;
[iv release];
UIPanGestureRecognizer *panRec = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(userPanned:)];
[canvas addGestureRecognizer:panRec];
[panRec release];
}
- (void)userPanned:(UIPanGestureRecognizer *)recognizer {
CGPoint touchPoint = [recognizer locationInView:canvas];
if (recognizer.state == UIGestureRecognizerStateBegan) lastTouchPoint = touchPoint;
if (CGRectContainsPoint(CGRectMake(0.0, 0.0, canvas.frame.size.width, canvas.frame.size.height), touchPoint)) {
UIGraphicsBeginImageContext(canvas.frame.size);
[drawImage.image drawInRect:CGRectMake(0.0, 0.0, canvas.frame.size.width, canvas.frame.size.height)];
CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 5.0);
CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 1.0, 0.0, 0.0, 1.0);
CGContextBeginPath(UIGraphicsGetCurrentContext());
CGContextMoveToPoint(UIGraphicsGetCurrentContext(), lastTouchPoint.x, lastTouchPoint.y);
CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), touchPoint.x, touchPoint.y);
CGContextStrokePath(UIGraphicsGetCurrentContext());
drawImage.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
lastTouchPoint = touchPoint;
}
}
canvas, lastTouchPoint and drawImage are iVars.
I did not implement the doubleTap and Tap routines to clear the image and to draw a point, but this should be enough to get you started.
精彩评论