iPhone - 在屏幕上绘图以响应触摸事件

标签 iphone ios cocoa-touch

我正在为一个类(class)做作业,需要一些指导。我正在使用一个应用程序将触摸事件和随后的手指拖动转换为屏幕上的绘图。我需要弄清楚如何将每个绘图保存在一个数组中,并在响应摇动事件时将它们全部删除。

它非常基本 - 有一个 HomeViewController (UIViewController) 和一个占据窗口的 DoodleView (UIView)。 HomeViewController 有一个 doodleview 属性,在 viewDidLoad 方法中,创建一个实例,将其分配给 self.doodleview,然后调用 addSubview。 touchesBegan、touchesMoved 和 touchesEnded 方法属于 doodleview 类。现在,每次点击和拖动都会删除前一个。

我最初尝试保存它们是为 HomeViewController 创建一个 NSMutableArray“doodleViews”属性,认为每个 touchesBegan 事件都在创建一个新的 doodleView 实例,并且只是在该数组的最后一个元素上调用 addSubview。这没有用,我不知道为什么。任何提示表示赞赏。

这是 HomeViewController 的一个片段:

- (void)viewDidLoad {
    [super viewDidLoad];

    CGRect window = [[UIScreen mainScreen] bounds];
    self.doodleView = [[DoodleView alloc] initWithFrame:window];

    CircleGestureRecognizer *recognizer = [[CircleGestureRecognizer alloc] initWithTarget:self action:@selector(handleCircleRecognizer:)]; 
    [self.doodleView addGestureRecognizer:recognizer];

    [self.view addSubview:self.doodleView];

}

这是来自 DoodleView 的片段:

- (void) touchesBegan:(NSSet *) touches withEvent:(UIEvent *) event
{
    NSLog(@"touches began");

    path = [UIBezierPath bezierPath];   
    path.lineWidth = 15.0f;
    path.lineCapStyle = kCGLineCapRound;
    path.lineJoinStyle = kCGLineJoinRound;

    UITouch *touch = [touches anyObject];
    [path moveToPoint:[touch locationInView:self]];
}

- (void) touchesMoved:(NSSet *) touches withEvent:(UIEvent *) event
{
    UITouch *touch = [touches anyObject];
    [path addLineToPoint:[touch locationInView:self]];
    [self setNeedsDisplay];
}

- (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    [path addLineToPoint:[touch locationInView:self]];
    [self setNeedsDisplay];
}

最佳答案

您可能希望将 UIBezierPath *path 保存到 touchesEnded 方法中的 NSMutableArray。然后在您的绘图代码中遍历数组并绘制每条路径。

当摇晃时,只需从该数组中removeAllObjects

关于iPhone - 在屏幕上绘图以响应触摸事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8056624/

相关文章:

ios - 如何跟踪多个选定的按钮?

iphone:NSMutableArray 和 NSMutableDictionary 中的问题

ios - 如何检测是否使用了英文 localizable.strings?

iphone - 应用程序在设备上崩溃,但 XCode 未记录崩溃

iphone - 自定义表格 View 背景的 UITableViewCell 颜色问题

iphone - 用于签署 iPhone 应用程序的配置文件名称?

iphone - 更改 UISwitch 上的文本

objective-c - 从结果类型为 'UITableViewCell *__strong' 的函数返回 'UITableView *' 的不兼容指针类型

iphone - iOS6和自动 View 卸载

ios - 更改 UITextView 文本方向