`
janedoneway
  • 浏览: 569544 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

iOS应用开发教程:新建UIView的子类

 
阅读更多

From: http://mobile.51cto.com/iphone-271839.htm

 

 

大致步骤

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) 绑定处理:

  1. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
  2.  
  3.  
  4. NSLog(@"didFinishLaunchingWithOptions."); 
  5.  
  6. CGRect drawingArea=[_window bounds]; 
  7.  
  8. view = [[HypnosisView alloc] initWithFrame:drawingArea]; 
  9.  
  10. [view setBackgroundColor:[UIColor yellowColor]]; 
  11.  
  12. [_window addSubview:view]; 
  13.  
  14. // Override point for customization after application launch. 
  15.  
  16. [_window makeKeyAndVisible]; 
  17.  
  18. return YES; 
  19.  

2) 绘图处理:

  1. - (void) drawRect:(CGRect)rect  
  2.   
  3. {  
  4.   
  5. NSLog(@"Entering the drawing function of HyponsisView.");  
  6.   
  7. //Get the drawing rectangle  
  8.   
  9. CGRect bounds=[self bounds];  
  10.   
  11. //Calculate the references  
  12.   
  13. CGPoint center;  
  14.   
  15. center.x=bounds.origin.x+bounds.size.width/2.0;  
  16.   
  17. center.y=bounds.origin.y+bounds.size.height/2.0;  
  18.   
  19. float radius=hypot(bounds.size.width, bounds.size.height)/2.0;  
  20.   
  21. //Prepare Drawing  
  22.   
  23. CGContextRef context=UIGraphicsGetCurrentContext();  
  24.   
  25. CGContextSetLineWidth(context,10);  
  26.   
  27. [[UIColor greenColor] setStroke];  
  28.   
  29. //Drawing the circles  
  30.   
  31. forfloat r=radius; r>0; rr=r-25)  
  32.   
  33. {  
  34.   
  35. CGContextAddArc(context, center.x, center.y, r, 0.0, M_PI*2.0,YES);  
  36.   
  37. CGContextStrokePath(context);  
  38.   
  39. }  
  40.   
  41. }  

运行效果:

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics