常規思路:
創建兩個 view,通過 for 循環創建 imageview,未點亮星星視圖在下、點亮星星視圖在上重合在一起,當用戶點擊視圖時,通過改變點亮星星視圖的 width 實現功能
本文思路:
直接重寫 drawrect 方法,在 drawrect 用 drawimage 畫出星星,根據 currentvalue 畫出不同類型的星星,當用戶點擊視圖時,改變 currentvalue,并根據改變后的 currentvalue 重新畫出星星。
展示圖:
代碼:
自定義一個繼承 uiview 的 cystarview
屬性:
1
2
3
4
5
6
7
8
9
10
11
12
|
/** 完成后執行的block */ @property (copy, nonatomic) void (^completionblock)(nsinteger); /** 是否可以點擊 */ @property (assign, nonatomic) bool clickable; /** 星星個數 */ @property (assign, nonatomic) nsinteger numberofstars; /** 星星邊長 */ @property (assign, nonatomic) cgfloat lengthofside; /** 評價值 */ @property (assign, nonatomic) nsinteger currentvalue; /** 星星間隔 */ @property (assign, nonatomic) cgfloat spacing; |
重寫 setter 方法,在 setter 方法中調用 setneedsdisplay,會執行 drawrect:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
- ( void )setlengthofside:(cgfloat)lengthofside { // 超過控件高度 if (lengthofside > self.frame.size.height) { lengthofside = self.frame.size.height; } // 超過控件寬度 if (lengthofside > self.frame.size.width / _numberofstars) { lengthofside = self.frame.size.width / _numberofstars; } _lengthofside = lengthofside; _spacing = (self.frame.size.width - lengthofside * _numberofstars) / _numberofstars; [self setneedsdisplay]; } |
在 drawrect 中畫星星:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
- ( void )drawrect:(cgrect)rect { uiimage *lightimage = [uiimage imagenamed:@ "star_light" ]; uiimage *darkimage = [uiimage imagenamed:@ "star_dark" ]; // 獲取當前上下文 cgcontextref context = uigraphicsgetcurrentcontext(); for ( int i = 0; i < self.numberofstars; i ++) { // 根據 currentvalue 選擇是畫亮的還是暗的星星 uiimage *image = i >= self.currentvalue ? darkimage : lightimage; cgrect imagerect = cgrectmake(self.spacing / 2 + (self.lengthofside + self.spacing) * i, (self.frame.size.height - self.lengthofside) / 2, self.lengthofside, self.lengthofside); cgcontextsavegstate(context); // 坐標系y軸是相反的,進行翻轉 cgcontextscalectm(context, 1.0, - 1.0); cgcontexttranslatectm(context, 0, - rect.origin.y * 2 - rect.size.height); cgcontextdrawimage(context, imagerect, image.cgimage); cgcontextrestoregstate(context); } } |
使用:
在要使用的控制器中:
1
2
3
4
5
6
7
8
9
10
|
#import "cystarview.h" // 初始化,傳入必要參數 cystarview *starview = [[cystarview alloc] initwithframe:frame numberofstars:number lengthofside:length]; // 設置 clickable,評論界面設置為yes,展示界面設置為no self.starview.clickable = yes; // // 設置 completionblock self.starview.completionblock = ^(nsinteger currentvalue) { // 點擊后的操作放這里 }; |
項目地址:點我點我!
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:http://www.jianshu.com/p/b87b08b0c7fd#