Iphone 如何在触摸事件上划清界限?
嘿,我是目标C的初学者,请帮帮我 我编写了以下代码,但不起作用Iphone 如何在触摸事件上划清界限?,iphone,objective-c,ios4,Iphone,Objective C,Ios4,嘿,我是目标C的初学者,请帮帮我 我编写了以下代码,但不起作用 -(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { UITouch *touch = [touches anyObject]; if ([touch view] == self.view) { CGPoint location = [touch locationInView:self.view]; loc1 = location;
-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
if ([touch view] == self.view) {
CGPoint location = [touch locationInView:self.view];
loc1 = location;
CGContextMoveToPoint(context, location.x, location.y);
NSLog(@"x:%d y:%d At Touch Begain", loc1.x, loc1.y);
}
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
if ([touch view] == self.view)
{
CGPoint location = [touch locationInView:self.view];
CGContextMoveToPoint(context, loc1.x, loc1.y);
NSLog(@"x:%d y:%d At Touch Move", loc1.x, loc1.y);
CGContextAddLineToPoint(context, location.x, location.y);
NSLog(@"x:%d y:%d", location.x, location.y);
}
}
我在viewdidload方法中声明contex,并尝试在touch事件中声明contex,但不起作用
我的应用程序日志文件看起来像
x:0 y:1079934976在触摸屏上移动Thu Jan 13 11:20:05.本地
DragDrop[536]:
CGContextAddLineToPoint:无效的上下文0x0 2011-01-13 11:20:05.149
DragDrop[536:207]x:0 y:1079902208周四1月13日11:20:05.本地
DragDrop[536]:
CGContextSetRGBStrokeColor:无效上下文0x0-Thu-Jan 13 11:20:05
.本地DragDrop[536]:
CGContextDrawPath:无效的上下文0x0 Thu Jan 13 11:20:05。本地
DragDrop[536]:
CGContextMoveToPoint:无效的上下文0x0 2011-01-13 11:20:05.199
DragDrop[536:207]x:0 y:1079934976触碰移动Thu Jan 13 11:20:05
.本地DragDrop[536]:
CGContextAddLineToPoint:无效的上下文0x0 2011-01-13 11:20:05.200
DragDrop[536:207]x:0 y:1079885824
在调用AddLineToPoint之后,需要调用CGContextStrokePath。 但请确保首先定义笔划路径颜色
CGContextSetRGBStrokeColor(context,0,0,1,1);
CGContextStrokePath(context);
通常不会直接在触摸检测方法中绘制。 通常,您只需在那里存储新的点/线,然后在
drawRect:
中绘制所有点/线。假设您有一个自定义的UIView
子类,它有一个NSMutableArray
类型的实例变量paths
和一个UIBezierPath
类型的属性currentPath
。然后,您可以实现触摸检测和drawRect方法,大致如下所示:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
self.currentPath = [UIBezierPath bezierPath];
currentPath.lineWidth = 3.0;
[currentPath moveToPoint:[touch locationInView:self]];
[paths addObject:self.currentPath];
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
[self.currentPath addLineToPoint:[touch locationInView:self]];
[self setNeedsDisplay];
}
- (void)drawRect:(CGRect)rect {
[[UIColor redColor] set];
for (UIBezierPath *path in paths) {
[path stroke];
}
}
注意,这被简化了很多。如果你画了很多线,性能会受到影响,最终,你会想把画缓存在位图图像中,但这应该让你开始了。用我的答案,它画了一条线(徒手) 希望这有帮助