[英]How To Draw line on touch event?
嘿我是目标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;
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,并尝试声明触摸事件但不工作...
我的应用日志文件看起来像......
x:0 y:1079934976在Touch Move Thu 1月13日11:20:05 .local DragDrop [536]:
CGContextAddLineToPoint:无效的上下文0x0 2011-01-13 11:20:05.149 DragDrop [536:207] x:0 y:1079902208 Thu Jan 13 11:20:05 .local DragDrop [536]:
CGContextSetRGBStrokeColor:无效的上下文0x0 Thu Jan 13 11:20:05 .local DragDrop [536]:
CGContextDrawPath:无效的上下文0x0 Thu Jan 13 11:20:05 .local DragDrop [536]:
CGContextMoveToPoint:无效的上下文0x0 2011-01-13 11:20:05.199 DragDrop [536:207] x:0 y:1079934976在Touch Move Thu 1月13日11:20:05 .local DragDrop [536]:
CGContextAddLineToPoint:无效的上下文0x0 2011-01-13 11:20:05.200 DragDrop [536:207] x:0 y:1079885824
您通常不会直接在触摸检测方法中绘制。 通常,你只需在那里存储新的点/线并在drawRect:
绘制所有这些点/线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];
}
}
请注意,这简化了很多。 如果你绘制很多行,性能将受到影响,最终,你需要将绘图缓存在位图图像中,但这应该让你开始。
您需要在调用AddLineToPoint后调用CGContextStrokePath。 确保首先定义笔划路径颜色。
CGContextSetRGBStrokeColor(context,0,0,1,1);
CGContextStrokePath(context);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.