閱讀830 返回首頁    go 技術社區[雲棲]


UIView的drawRect方法

UIView的drawRect方法

 

 

自定義一個UIView類,代碼如下:

 

MainView.h

Cpp代碼  收藏代碼
  1. #import <UIKit/UIKit.h>  
  2.   
  3.   
  4. @interface MainView : UIView {  
  5.   
  6. }  
  7.   
  8. @end  
 

 

 

MainView.m

Cpp代碼  收藏代碼
  1. #import "MainView.h"  
  2.   
  3.   
  4. @implementation MainView  
  5.   
  6.   
  7. - (id)initWithFrame:(CGRect)frame {  
  8.       
  9.     self = [super initWithFrame:frame];  
  10.     if (self) {  
  11.         // Initialization code.  
  12.     }  
  13.     self.backgroundColor=[UIColor cyanColor];  
  14.       
  15.       
  16.       
  17.     return self;  
  18. }  
  19.   
  20.   
  21. // Only override drawRect: if you perform custom drawing.  
  22. // An empty implementation adversely affects performance during animation.  
  23. - (void)drawRect:(CGRect)rect {  
  24.     // Drawing code.  
  25.     //獲得處理的上下文    
  26.     CGContextRef context = UIGraphicsGetCurrentContext();    
  27.     //設置線條樣式    
  28.     CGContextSetLineCap(context, kCGLineCapSquare);     
  29.     //設置線條粗細寬度    
  30.     CGContextSetLineWidth(context, 1.0);     
  31.     
  32.     //設置顏色    
  33.     CGContextSetRGBStrokeColor(context, 1.0, 0.0, 0.0, 1.0);     
  34.     //開始一個起始路徑    
  35.     CGContextBeginPath(context);     
  36.     //起始點設置為(0,0):注意這是上下文對應區域中的相對坐標,    
  37.     CGContextMoveToPoint(context, 0, 0);     
  38.     //設置下一個坐標點    
  39.     CGContextAddLineToPoint(context, 100, 100);     
  40.     //設置下一個坐標點    
  41.     CGContextAddLineToPoint(context, 0, 150);    
  42.     //設置下一個坐標點    
  43.     CGContextAddLineToPoint(context, 50, 180);    
  44.     //連接上麵定義的坐標點    
  45.     CGContextStrokePath(context);  
  46.       
  47. }  
  48.   
  49.   
  50. - (void)dealloc {  
  51.     [super dealloc];  
  52. }  
  53.   
  54.   
  55. @end  
 

 

 

 

 

在Xcode中創建Application-Base項目:(這裏項目名假設為 Test95

 

Test95AppDelegate.h代碼:

Cpp代碼  收藏代碼
  1. #import <UIKit/UIKit.h>  
  2. #import "MainView.h"  
  3.   
  4. @interface Test95AppDelegate : NSObject <UIApplicationDelegate> {  
  5.     UIWindow *window;  
  6.     MainView *mainView;  
  7. }  
  8.   
  9. @property (nonatomic, retain) IBOutlet UIWindow *window;  
  10.   
  11. @end  
 

 

 

Test95AppDelegate.m中的didFinishLaunchingWithOptions方法代碼

Cpp代碼  收藏代碼
  1. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {      
  2.       
  3.     // Override point for customization after application launch.  
  4.     CGRect wholeWindow=CGRectMake(0, 20, 320, 320);  
  5.     mainView=[[MainView alloc]initWithFrame:wholeWindow];  
  6.       
  7.     [self.window addSubview:mainView];  
  8.     [self.window makeKeyAndVisible];  
  9.       
  10.     return YES;  
  11. }  
 

 

 

結果如下圖:


 


最後更新:2017-04-04 07:03:39

  上一篇:go iOS開發那些事--創建基於故事板的iOS 6的HelloWorld
  下一篇:go STL之四:list用法詳解