用手指在iPhone上绘制直线 [英] Drawing Straight Lines with Finger on iPhone

查看:189
本文介绍了用手指在iPhone上绘制直线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

背景:我正在尝试创建一个非常简单的iPhone应用,该应用将允许用户用手指在屏幕上绘制多条直线.

Background: I am trying to create a really simple iPhone app that will allow the user to draw multiple straight lines on the screen with their finger.

我正在UIViewController中使用这两种方法来捕获每条线的端点的坐标.

I'm using these two methods in my UIViewController to capture the coordinates of each line's endpoints.

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event

问题: 我希望在touchesEnded触发后立即显示该行,然后继续在屏幕上绘制更多的行.我该怎么做呢?我不一定需要代码,但是我需要有关如何将其组合在一起的总体思路的帮助.另外,我不是xib的忠实拥护者,如果可能会影响答案,我希望通过编程方式全部完成.

Question: I would like the line to show up as soon as touchesEnded has fired and then keep drawing more lines on the screen. How do I do this? I don't necessarily need the code, but I need help with the big picture idea of how to put it together. Also, I'm not a huge fan of xibs and like to do things all programmatically if that affects the answer.

我尝试过的事情:我尝试使用Quartz 2d,但似乎要使用它,必须在单独的子类化视图的drawRect方法中进行绘制.因此,我必须为每行创建一个新视图吗?然后我的坐标就会混乱b/c,我不得不将touches的位置从UIViewController转换为视图.

What I've Tried: I've tried using Quartz 2d but it seems in order to use that, you have to do your drawing in the drawRect method of a separate subclassed view. So I would have to create a new view for each line? and then my coordinates would be messed up b/c I'd have to translate the touches positions from the UIViewController to the view.

我还尝试了OpenGL,使用OpenGL取得了一些成功(使用

I've also tried with OpenGL, which I've had a bit more success with (using the GLPaint sample as a template) but OpenGL seems like overkill for just drawing some straight lines on the screen.

推荐答案

您不需要多个视图,也不需要OpenGL.

You don't need multiple views, and you don't need OpenGL.

成为UIView的子类-将其称为CanvasView.

Make a subclass of UIView -- call it CanvasView.

在画布中制作一个对象来表示一行"-它是NSObject的子类,具有CGPoint属性的开始和结束位置.

Make an object to represent "a line" in your canvas -- it would be a subclass of NSObject with CGPoint properties for start and end.

CanvasView应该保留画布中的行的数组.

CanvasView should keep an array of the lines that are in the canvas.

-[CanvasView drawRect:]中,循环遍历数组中的行,并绘制每一行.

In -[CanvasView drawRect:], loop through the lines in the array, and draw each one.

-[CanvasView touchesBegan:withEvent:]中,将起点存储在实例变量中. 在-[CanvasView touchesEnded:withEvent:]中,用起点和终点制作一条新线,并将其添加到您的线阵列中.调用[self setNeedsDisplay]使视图重新绘制.

In -[CanvasView touchesBegan:withEvent:], stash the start point in an instance variable. In -[CanvasView touchesEnded:withEvent:], make a new line with the start and end points, and add it to your array of lines. Call [self setNeedsDisplay] to cause the view to be redrawn.

这篇关于用手指在iPhone上绘制直线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆