iOS應用開發(fā)教程:新建UIView的子類
大致步驟
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消息的功能
關鍵代碼如下:
Java代碼
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);
- }
- }
運行效果:
