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

移动开发 iOS
本文我们将从实例想大家介绍iOS应用开发如何新建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) 绑定处理:

  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. }  

运行效果:

 

责任编辑:佚名 来源: iteye
相关推荐

2013-07-25 13:43:23

iOS开发学习UIView的Anim

2011-07-08 14:58:16

iPhone Xcode iOS

2011-08-11 10:27:37

iPhoneUIView视图

2011-08-11 10:16:23

iPhoneUIView视图

2011-08-15 13:50:06

IPhone开发UIView动画

2011-08-09 10:27:41

iOS剪贴板

2011-08-12 11:31:46

iPhoneUIView动画

2012-01-18 13:51:39

2012-12-24 13:38:01

iOSUIView

2011-05-11 10:02:37

iOS

2011-07-22 14:18:04

iOS 文件

2012-02-02 15:24:57

2013-09-13 13:16:05

2011-08-11 16:50:04

iOSTwitter

2011-07-28 09:58:31

Web

2015-12-09 14:00:41

ios应用

2014-04-23 13:30:23

类簇iOS开发

2012-08-30 09:32:12

FacebookiOS

2011-01-14 08:35:03

iPhoneiPad敏捷设计流程

2011-08-08 13:26:48

iOS开发 Twitter
点赞
收藏

51CTO技术栈公众号