通常您使用 Interface Builder 在 UIViewController 的类 XIB 文件上创建一个 UIView 对象,然后使用 Identity Inspector 中的自定义类工具将 UIView 与一个类相关联(该类是一个 UIView 类,其中包含用于绘制的代码UIView 对象。)。然后,您必须在 UIViewController 类中使用 @property 和 @systhesize 将 UIView(使用连接检查器)连接到您的类。这种方法是可以的,但在某些情况下它有局限性。
您可以务实地解决所有这些问题。
创建将用于在 UIView 对象上绘图的 UIView 类。在这个类中,您创建上下文引用 (CGContextRef) 为绘图工具提供上下文(在哪里绘制),例如字符串、线条、圆等。即
CGContextRef gg = UIGraphicsGetCurrentContext();
在 UIViewController 类中,您需要在 .h 文件中导入对 UIView 类的引用。我们称之为:DrawOnView
#import "DrawOnView.h"
然后在包含@interface 的括号中放置这一行:
UIView * draw; // draw can be changed to any name that suits your needs
然后在viewDidLoad方法里面类的.m部分你需要插入这段代码:
// Make the size and location that suits your needs
// You can change this on the go in your code as needed, such as if the
// device orientation is changed.
draw = [DrawOnView alloc] initWithFrame:CGRectCreate(50, 50, 100, 200)];
// You can change the background color of the view, if you like:
[draw setBackGroundColor:[UIColor greenColor]];
// Now add the view to your primary view
[self.view addSubview:draw];
现在,在我们程序的其他部分,您可以使用以下引用调用您在 DrawOnView 类中声明的方法和刷新(它调用 drawRect 方法,您的 UIView 类中的主要入口点):
[(DrawOnView*) draw setNeedsDisplay];
这是非常重要的。不要使用:
[draw setNeedsDisplay]; // This will not work!
假设您在 DrawOnView 中定义了其他方法并想要调用它们。
这是一个示例方法(在 .h 文件中):
-(BOOL) wasHotSpotHit: (CGPoint) p;
实际的方法可能如下所示(在 .m 文件中):
-(BOOL) washHotSpotHit: (CGPont) p
{
if(CGRectContainsPont(hotspot.frame, p))
{
return true;
}
return false;
}
使用这样的代码:
if([(DrawOnView*) draw testIfSpotHit:p])
{
// Do something for when user touches hot spot.
}