上一節我們談到用 XIB 檔案建構的自訂視圖,今天則介紹不借助 XIB 檔案、純粹以 Objective-C 程式碼完成的自訂視圖。
這次我們不建立 XIB 檔案,而是直接用 Objective-C 類別來取代它,透過覆寫 drawRect: 完成繪圖。
- (void)drawRect:(CGRect)rect
{
CGRect bounds = [self bounds];
CGPoint center;
center.x = bounds.origin.x + bounds.size.width / 2.0;
center.y = bounds.origin.y + bounds.size.height / 2.0;
// 建立圖形路徑句柄
CGMutablePathRef path = CGPathCreateMutable();
// 設定矩形邊界
CGRect rectangle = CGRectMake(center.x-100, center.y-150, 200.0f, 300.0f);
// 將矩形加入路徑
CGPathAddRect(path, NULL, rectangle);
// 取得上下文句柄
CGContextRef currentContext = UIGraphicsGetCurrentContext();
// 將路徑加入上下文
CGContextAddPath(currentContext, path);
// 設定填滿顏色
[[UIColor colorWithRed:0.20f green:0.60f blue:0.80f alpha:1.0f] setFill];
// 設定畫筆顏色
[[UIColor brownColor] setStroke];
// 設定邊框線寬
CGContextSetLineWidth(currentContext, 5.0f);
// 繪製
CGContextDrawPath(currentContext, kCGPathFillStroke);
// 釋放路徑
CGPathRelease(path);
// 建立文字
NSString *text = @"我是Developer_Zhang";
UIFont *font = [UIFont boldSystemFontOfSize:20];
// 設定文字範圍
CGRect textRect;
textRect.size = [text sizeWithFont:font];
textRect.origin.x = center.x - textRect.size.width / 2.0;
textRect.origin.y = center.y - textRect.size.height / 2.0;
// 設定字體顏色
[[UIColor redColor] setFill];
// 設定陰影
CGSize offset = CGSizeMake(4, 3);
CGColorRef color = [[UIColor blackColor] CGColor]; // 陰影顏色為黑色
CGContextSetShadowWithColor(currentContext, offset, 2.0, color); // 模糊半徑 2.0
[text drawInRect:textRect withFont:font];
}
- (void)viewDidLoad
{
[super viewDidLoad];
// 建立一個視窗大小的 CGRect
CGRect wholeWindow = [[self.view window] bounds];
// 建立一個視窗大小的 ZYCustomView 實例作為主視圖
self.view = [[ZYCustomView alloc] initWithFrame:wholeWindow];
[self.view setBackgroundColor:[UIColor whiteColor]];
}
畫面上出現一個填滿藍色、棕色邊框的矩形,中央則是帶有黑色陰影的紅色文字。這說明了完全以程式碼即可完成自訂視圖的繪製,不必依賴 XIB 檔案。