UIBezierPath
類用來繪制直線或曲線臂痕,從而組成各種形狀。
這里以 UIView
的一個子類 BNRHypnosisView
為例兼雄,重寫 UIView
的 drawRect:
方法姻僧,并在該方法中實現(xiàn)繪圖甫匹,示例代碼如下:
- (void)drawRect:(CGRect)rect {
CGRect bounds = self.bounds;
// 根據(jù) bounds 計算中心點(diǎn)
CGPoint center;
center.x = bounds.origin.x + bounds.size.width / 2.0;
center.y = bounds.origin.y + bounds.size.height / 2.0;
// 根據(jù)視圖寬和高中的較小值計算圓形的半徑
float radius = (MIN(bounds.size.width, bounds.size.height) / 2.0);
UIBezierPath *path = [[UIBezierPath alloc] init]; //創(chuàng)建一個對象
// 以中心為原點(diǎn),radius 為半徑蓝牲,定義一個 0 到 M_PI * 2.0 弧度的路徑(整圓)
[path addArcWithCenter:center
radius:radius
startAngle:0.0
endAngle:M_PI * 2.0
clockwise:YES];
path.lineWidth = 10; // 設(shè)置線條寬度為 10 點(diǎn)
[[UIColor orangeColor] setStroke]; // 設(shè)置繪制顏色為橙色
[path stroke]; // 繪制路徑
}
注意:這些值得單位是點(diǎn)(points)趟脂,不是像素(pixel)。若為像素例衍,則視圖在 Retina 和非 Retina 顯示屏上的大小無法保持一致昔期。
因為點(diǎn)的大小與設(shè)備分辨率相關(guān),取決于屏幕以多少像素顯示一個點(diǎn):
在 Retina 顯示屏上肄渗,一個點(diǎn)的寬高都是 2 個像素镇眷;
而在非 Retina 顯示屏上,一個點(diǎn)的寬高都是 1 個像素翎嫡。
運(yùn)行代碼欠动,效果圖如下:
在 BNRHypnosisView.m
的 initWithFrame:
方法中,設(shè)置對象的背景色透明,示例代碼:
- (instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
// 設(shè)置 BNRHypnosisView 對象的背景顏色為透明
self.backgroundColor = [UIColor clearColor];
}
return self;
}
- 繪制同心圓
兩種方法:
- 創(chuàng)建多個
UIBezierPath
對象具伍,每個對象代表一個圓形翅雏; - 使用一個
UIBezierPath
對象,為每個圓定義一個繪制路徑人芽。
方法 2 更好:只創(chuàng)建一個對象望几,內(nèi)存占用少。示例代碼:
float maxRadius = hypot(bounds.size.width, bounds.size.height) / 2.0;
for (float currentRadius = maxRadius; currentRadius > 0; currentRadius -= 20) {
[path addArcWithCenter:center
radius:currentRadius
startAngle:0.0
endAngle:M_PI * 2.0
clockwise:YES];
}
注:這里的
hypot
為數(shù)學(xué)函數(shù)(已知直角三角形的兩直角邊長度萤厅,求斜邊長度)橄抹。關(guān)于其他常用數(shù)學(xué)函數(shù),可參考 iOS math.h 常用數(shù)學(xué)函數(shù)
效果如下:
可以發(fā)現(xiàn)多了一條直線惕味,這是因為單個 UIBezierPath
對象將多個路徑(每個路徑可以畫出一個圓形)鏈接起來楼誓,形成了一個完整的路徑∶樱可以將 對象想象成一支在紙上繪畫的筆——繪制完某個圓后繪制另外一個疟羹,沒有抬起筆,因此會留下筆跡禀倔。所以要抬起筆榄融。
每次循環(huán)開始需要抬起畫筆,添加代碼如下:
[path moveToPoint:CGPointMake(center.x + currentRadius, center.y)]; //抬起畫筆
添加后的效果:
-
繪制圖像
從文件系統(tǒng)中加載一個圖像文件救湖,并將其繪制到同心圓中愧杯,效果如圖所示:
繪制圖像
從該文件創(chuàng)建一個 UIImage
對象,示例代碼:
UIImage *logoImage = [UIImage imageNamed:@"logo"];
在 drawRect:
方法中將圖像繪制到視圖捎谨,示例代碼:
[logoImage drawInRect:rect];
更多方法和屬性可參閱官方文檔民效。此外 UIBezierPath精講 寫得也不錯!推薦下涛救!
《iOS編程(第4版)》 筆記