Custom UIView,要自定义,需要重写:
- (id)initWithFrame: (CGRect) frame //依照Frame建立新的View,建立出來的View要通过addSubview加入到父View中。
-(void)drawRect:(CGRect)rect //自画,永远不要直接调用drawRect,而要通过 [self setNeedDisplay],由系统再去异步调用drawRect。并且必须在主线程中调用。
自定义UIView不能使用nib文件设计界面,必须在程序中用代码创建各个控件,否则即使在主线程中调用setNeedDisplay也是不起作用。
大致步骤
1) 新建一个UIView的子类(@interface HypnosisView : UIView)
2) 自定义绘图函数:(void) drawRect:(CGRect)rect
◆确定绘图范围:CGRect bounds=[self bounds]
◆获得CGContext, CGContextRef context=UIGraphicsGetCurrentContext();
◆进行绘图操作
3) 将新视图绑定到主窗口
◆在HypnosisterAppDelegate中添加一个成员变量HypnosisView *view;
◆确定绘图范围
◆在didFinishLaunchingWithOptions中增加子视图:[_window addSubview:view];
◆进行显示 [_window makeKeyAndVisible];
待确定事项:
1) CGContextStrokePath的功能
2) makeKeyAndVisible消息的功能
关键代码如下:
代码
1) 绑定处理:
- - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
- {
- NSLog(@"didFinishLaunchingWithOptions.");
- CGRect drawingArea=[_window bounds];
- view = [[HypnosisView alloc] initWithFrame:drawingArea];
- [view setBackgroundColor:[UIColor yellowColor]];
- [_window addSubview:view];
- // Override point for customization after application launch.
- [_window makeKeyAndVisible];
- return YES;
- }
2) 绘图处理:
- - (void) drawRect:(CGRect)rect
- {
- NSLog(@"Entering the drawing function of HyponsisView.");
- //Get the drawing rectangle
- CGRect bounds=[self bounds];
- //Calculate the references
- CGPoint center;
- center.x=bounds.origin.x+bounds.size.width/2.0;
- center.y=bounds.origin.y+bounds.size.height/2.0;
- float radius=hypot(bounds.size.width, bounds.size.height)/2.0;
- //Prepare Drawing
- CGContextRef context=UIGraphicsGetCurrentContext();
- CGContextSetLineWidth(context,10);
- [[UIColor greenColor] setStroke];
- //Drawing the circles
- for( float r=radius; r>0; rr=r-25)
- {
- CGContextAddArc(context, center.x, center.y, r, 0.0, M_PI*2.0,YES);
- CGContextStrokePath(context);
- }
- }
运行效果:
![](http://hi.csdn.net/attachment/201108/8/0_1312807989vn1T.gif)
由于这里不能上传文件,需要demo的朋友,请发邮件到ch_soft@163.com索取。