从基于视图的模板开始,创建一个名为Drawer。将 UIView 类添加到您的项目中。命名它方视(.h 和 .m)。
双击DrawerViewController.xib打开它界面生成器。将那里的通用视图更改为方视在身份检查器(command-4)中使用Class弹出菜单。保存并返回Xcode.
将此代码放入您的drawRect:方法中SquareView.m文件来绘制一个大的、弯曲的、空的黄色矩形和一个小的、绿色的透明正方形:
- (void)drawRect:(CGRect)rect;
{
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetRGBStrokeColor(context, 1.0, 1.0, 0.0, 1.0); // yellow line
CGContextBeginPath(context);
CGContextMoveToPoint(context, 50.0, 50.0); //start point
CGContextAddLineToPoint(context, 250.0, 100.0);
CGContextAddLineToPoint(context, 250.0, 350.0);
CGContextAddLineToPoint(context, 50.0, 350.0); // end path
CGContextClosePath(context); // close path
CGContextSetLineWidth(context, 8.0); // this is set from now on until you explicitly change it
CGContextStrokePath(context); // do actual stroking
CGContextSetRGBFillColor(context, 0.0, 1.0, 0.0, 0.5); // green color, half transparent
CGContextFillRect(context, CGRectMake(20.0, 250.0, 128.0, 128.0)); // a square at the bottom left-hand corner
}
您不必调用此方法来进行绘图。当程序启动并且 NIB 文件被激活时,视图控制器将告诉视图至少绘制一次自身。