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

查看:40
本文介绍了如何在 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.

然后转到新建文件并创建一个Objective-C 类",将子类"设置为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.

现在打开Resources"组并双击MainWindow.xib"在Interface Builder中打开它.从这里您应该看到一个名为Window"的窗口.按 Cmd+Shift+L 调出库,然后将视图"组件拖到您的窗口上,并将其定位以便您可以看到所有内容.选择新视图后,按 Cmd+4 以显示身份检查器,然后在类身份"下,单击下拉菜单并选择我的视图.

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);
}

保存所有内容并单击构建并运行",您现在应该会在 iPhone 上看到一条短红线.

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天全站免登陆