在APP中實現類似聊天內容背景圖時,需要繪制圓角及箭頭。很多人會選擇使用圖片(這也是最省事的一種方法),但是對于在視圖中對內容做約束布局的話,我們無法準確的知道箭頭的偏移量。下面就來介紹一下利用CGContextRef怎樣繪制吧。
先來看看效果圖吧!
代碼實現:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
- ( void )drawRect:(CGRect)rect { float lw = 2; // 邊線寬度 float aw = 4; // 箭頭寬 float ah = 5; // 箭頭高 float r = 3; // 圓角角度 // 需要減去邊線的寬度,為什么不是減去邊線的寬度x2? // 因為左邊線和上邊線是往視圖內描繪的,而右邊線和下邊線是往視圖外描繪的。 float w = self.frame.size.width - lw; // 設置畫線長度 float h = self.frame.size.height - lw; // 設置畫線寬度 // 獲取上下文 CGContextRef context = UIGraphicsGetCurrentContext(); // 設置邊線寬度 CGContextSetLineWidth(context, lw); //邊框顏色 CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor); // 矩形填充顏色 CGContextSetFillColorWithColor(context, [UIColor whiteColor].CGColor); CGContextMoveToPoint(context, 0, lw); // 開始坐標左邊開始 CGContextAddArcToPoint(context, w, lw, w, r, r); // 右上角角度 CGContextAddArcToPoint(context, w , h, w-r, h, r); // 右下角角度 CGContextAddArcToPoint(context, aw, h, aw, h-r, r); // 左下角角度 CGContextAddLineToPoint(context, aw, ah); // 向左上豎線 CGContextAddLineToPoint(context, 0, lw); // 向左上斜線 CGContextDrawPath(context, kCGPathFillStroke); //根據坐標繪制路徑 // 父類調用 放在畫完邊線后。不然設置的文字會被覆蓋 [super drawRect:rect]; } |
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/xl348053718/article/details/115691483