1 前言
從今天起我們開始學習IOS的圖形和動畫。
在 Cocoa Touch 中,程式是由“視窗”和“視圖”組成。一個帶有 UI 的程式至少有一個視窗,這個視窗至少 包括一個到多個視圖。在Cocoa Touch中,一個視窗就是一個UIWindow的執行個體。一般的,程式會開啟到主窗 口,然後程式員會向這個視窗添加視圖,來展示 UI 的不同的部分:例如按鈕,文本,映像和自訂控制項。所 有這些 UI 相關的組件是由 UIKit 來進行處理和繪製的。
Apple 為開發人員提供了強有力的架構,來處理 iOS 和 OS X 中的圖形和動畫。下面是這些架構和技術:
UIKit
進階別架構,允許程式員建立視圖,視窗,按鈕,和其他 UI 相關的控制項。它也將低層的 API 組合到一個 便於使用的進階別 API 中。
Quartz 2D
運行內部的用於 iOS 畫圖的主引擎;UIKit 使用了 Quarz。
Core Graphics
支援圖形環境(後面會介紹),載入圖片,繪製圖片等等的架構。
Core Animation
顧名思義,iOS 上的動畫架構。
今天我們來簡單的學習一下在 iOS 裝置上繪製文本。
2 代碼執行個體
ZYViewControllerView.m
[plain]
- (void)drawRect:(CGRect)rect{
//設定字型樣式
UIFont *helveticaBold = [UIFont fontWithName:@"HelveticaNeue-Bold" size:30.0f];
/* Load the color */
UIColor *magentaColor =[UIColor colorWithRed:0.5f
green:0.0f blue:0.5f
alpha:1.0f];
/* Set the color in the graphical context */
[magentaColor set];
//文字內容
NSString *myString = @"I Learn Really Fast";
//在屏 幕上 x 軸的 25 及 y 軸 190 處以 30 點的字型畫出一個簡單的字串
// [myString drawAtPoint:CGPointMake(25, 190) withFont:helveticaBold];
[myString drawInRect:CGRectMake(100,/* x */
120, /* y */
100, /* width */
200) /* height */
withFont:helveticaBold];
//獲得一個顏色用於Quartz 2D繪圖。唯讀
CGColorRef colorRef = [magentaColor CGColor];
//返回顏色組件
const CGFloat *components = CGColorGetComponents(colorRef);
//返回顏色組件的個數
NSUInteger componentsCount = CGColorGetNumberOfComponents(colorRef);
NSUInteger counter = 0;
for (counter = 0;counter <componentsCount; counter++){//迴圈輸出
NSLog(@"Component %lu = %.02f",(unsigned long)counter,components[counter]);
}
}
- (void)drawRect:(CGRect)rect{
//設定字型樣式
UIFont *helveticaBold = [UIFont fontWithName:@"HelveticaNeue-Bold" size:30.0f];
/* Load the color */
UIColor *magentaColor =[UIColor colorWithRed:0.5f
green:0.0f blue:0.5f
alpha:1.0f];
/* Set the color in the graphical context */
[magentaColor set];
//文字內容
NSString *myString = @"I Learn Really Fast";
//在屏 幕上 x 軸的 25 及 y 軸 190 處以 30 點的字型畫出一個簡單的字串
// [myString drawAtPoint:CGPointMake(25, 190) withFont:helveticaBold];
[myString drawInRect:CGRectMake(100,/* x */
120, /* y */
100, /* width */
200) /* height */
withFont:helveticaBold];
//獲得一個顏色用於Quartz 2D繪圖。唯讀
CGColorRef colorRef = [magentaColor CGColor];
//返回顏色組件
const CGFloat *components = CGColorGetComponents(colorRef);
//返回顏色組件的個數
NSUInteger componentsCount = CGColorGetNumberOfComponents(colorRef);
NSUInteger counter = 0;
for (counter = 0;counter <componentsCount; counter++){//迴圈輸出
NSLog(@"Component %lu = %.02f",(unsigned long)counter,components[counter]);
}
}
工程
注意:需要將nib檔案中的view視圖的class設定為ZYViewControllerView
運行結果
控制台顯示
2013-05-14 11:14:13.611 GraphicsStringTest[1030:c07] Component 0 = 0.50
2013-05-14 11:14:13.613 GraphicsStringTest[1030:c07] Component 1 = 0.00
2013-05-14 11:14:13.614 GraphicsStringTest[1030:c07] Component 2 = 0.50
2013-05-14 11:14:13.615 GraphicsStringTest[1030:c07] Component 3 = 1.00