如何在iPhone上画一条线? [英] How do I draw a line on the iPhone?

查看:167
本文介绍了如何在iPhone上画一条线?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是iPhone编程的初学者,并且想要使用Quartz和UIKit绘制一条线到手机屏幕上学习。

I am a beginner at iPhone programming, and would like to draw a line to the phone screen for the purpose of study using Quartz and UIKit.

我如何开始绘图?

推荐答案

第一步是定义UIView的子类,创建一个要绘制的空间。

The first step is to define a subclass of UIView, to create a space to draw in.

如果你开始一个新的应用程序,最简单的方法是从基于窗口的应用程序模板开始。

If you're starting with a new application, the easiest way will be to start with the "Window-based application" template.

然后转到New File并创建一个Objective-C Class,并将Subclass of设置为UIView,并给出一个名称,例如MyView.m。

Then go New File and create an "Objective-C Class" with "Subclass of" set to "UIView", and give it a name, say MyView.m.

现在打开资源组,双击MainWindow.xib,在Interface Builder中打开它。从这里你应该看到一个名为窗口的窗口。点击Cmd + Shift + L来打开库,并将一个视图组件拖动到您的窗口,并将其定位,以便您可以看到所有的。选择您的新视图,点击Cmd + 4以启动Identity Inspector,然后在类身份下,单击下拉菜单并选择MyView。

Now open up the "Resources" group and double click on "MainWindow.xib" to open it in Interface Builder. From here you should see a window named "Window". Hit Cmd+Shift+L to bring up the Library, and drag a "View" component onto your window, and position it so you can see all of it. With your new View selected, hit Cmd+4 to bring up the Identity Inspector and under "Class Identity", click the dropdown and choose MyView.

在MyView.m中实现drawRect:方法,这里是一些绘制一行的示例代码:

Next, you need to implement the drawRect: method in MyView.m, here's some example code that draws a line:

- (void)drawRect:(CGRect)rect {
    CGContextRef c = UIGraphicsGetCurrentContext();

    CGFloat red[4] = {1.0f, 0.0f, 0.0f, 1.0f};
    CGContextSetStrokeColor(c, red);
    CGContextBeginPath(c);
    CGContextMoveToPoint(c, 5.0f, 5.0f);
    CGContextAddLineToPoint(c, 50.0f, 50.0f);
    CGContextStrokePath(c);
}

保存所有内容,然后单击构建并运行红线。

Save everything and click "Build and Run", you should now see a short red line on the iPhone.

有关Core Graphics的更多信息,请查看Apple文档。我还发现在Xcode文档查看器中搜索以CGContext开头的函数并浏览这些函数很有帮助 - 你最终使用的大部分Core Graphics函数将以CGContext开头。

For more information about Core Graphics, look up the Apple Documentation. I've also found it helpful to search for functions beginning with CGContext in the Xcode documentation viewer, and browse through those - most of the Core Graphics functions you'll end up using will start with the term "CGContext".

这篇关于如何在iPhone上画一条线?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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