我使用本教程中的绘图代码让某人在一个小方框中绘图:http://www.ifans.com/forums/showthread.php?t=132024
默认代码在整个屏幕上绘制,如何将绘图限制在屏幕上的小方框中?
答案 0 :(得分:3)
在此示例中,触摸和绘图发生在视图控制器的主视图中:
UIGraphicsBeginImageContext(self.view.frame.size);
[drawImage.image drawInRect:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
等...
因此,如果您将该视图的框架更改为较小的尺寸,则应自动将图形限制为较小的尺寸。
或者您可以将触摸识别和绘图“移动”到另一个较小的子视图中:
=====编辑=====
以下是如何操作:
- (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和drawImage是iVars。
我没有实现doubleTap和Tap例程来清除图像并绘制一个点,但这应该足以让你开始。