gpt4 book ai didi

iphone - 如何在触摸事件上画线?

转载 作者:行者123 更新时间:2023-12-03 20:18:48 27 4
gpt4 key购买 nike

嘿,我是 Objective 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 At Touch Move Thu Jan 13 11:20:05 .local DragDrop[536] :

CGContextAddLineToPoint: invalid context 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: invalid context 0x0 Thu Jan 13 11:20:05 .local DragDrop[536] :

CGContextDrawPath: invalid context 0x0 Thu Jan 13 11:20:05 .local DragDrop[536] :

CGContextMoveToPoint: invalid context 0x0 2011-01-13 11:20:05.199 DragDrop[536:207] x:0 y:1079934976 At Touch Move Thu Jan 13 11:20:05 .local DragDrop[536] :

CGContextAddLineToPoint: invalid context 0x0 2011-01-13 11:20:05.200 DragDrop[536:207] x:0 y:1079885824

最佳答案

您通常不会直接在触摸检测方法中进行绘制。通常,您只需在那里存储新的点/线,然后在drawRect:中绘制它们。假设您有一个 UIView 的自定义子类,它有一个 NSMutableArray 类型的实例变量 paths 和一个属性 currentPath类型为UIBezierPath。然后,您可以大致像这样实现触摸检测和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];
}
}

请注意,这已经简化了很多。如果您绘制许多线条,性能将会受到影响,最终您会希望将绘图缓存在位图图像中,但这应该可以帮助您入门。

关于iphone - 如何在触摸事件上画线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4669490/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com