咱們要花的爲一個黃色的五角星而且其中的填充黃色可以任意調整,好比只填滿半個五角星,或者只填滿一個角等等。blog
首先要重寫DrawRect 方法,而後在這裏實現咱們的畫圖代碼。ip
- (void)drawRect:(CGRect)rect { CGFloat centerX = rect.size.width / 2; CGFloat centerY = rect.size.height / 2; CGFloat r0 = self.radius * sin(18 * th)/cos(36 * th); /*計算小圓半徑r0 */ CGFloat x1[5]={0},y1[5]={0},x2[5]={0},y2[5]={0}; for (int i = 0; i < 5; i ++) { x1[i] = centerX + self.radius * cos((90 + i * 72) * th); /* 計算出大圓上的五個平均分佈點的座標*/ y1[i]=centerY - self.radius * sin((90 + i * 72) * th); x2[i]=centerX + r0 * cos((54 + i * 72) * th); /* 計算出小圓上的五個平均分佈點的座標*/ y2[i]=centerY - r0 * sin((54 + i * 72) * th); } CGContextRef context = UIGraphicsGetCurrentContext(); CGMutablePathRef startPath = CGPathCreateMutable(); CGPathMoveToPoint(startPath, NULL, x1[0], y1[0]); for (int i = 1; i < 5; i ++) { CGPathAddLineToPoint(startPath, NULL, x2[i], y2[i]); CGPathAddLineToPoint(startPath, NULL, x1[i], y1[i]); } CGPathAddLineToPoint(startPath, NULL, x2[0], y2[0]); CGPathCloseSubpath(startPath); CGContextAddPath(context, startPath); CGContextSetFillColorWithColor(context, self.startColor.CGColor); CGContextSetStrokeColorWithColor(context, self.boundsColor.CGColor); CGContextStrokePath(context); CGRect range = CGRectMake(x1[1], 0, (x1[4] - x1[1]) * self.value , y1[2]); CGContextAddPath(context, startPath); CGContextClip(context); CGContextFillRect(context, range); CFRelease(startPath); }
因爲這樣的五角星是中空的,因此咱們選取十個點,首先五角星五個尖在一個大圓上,且在大圓上平均分佈,內角的五個點在一個小圓上,也是平均分佈。it
最後建立路徑。建立好路徑後要進行色彩填充,分爲描邊以及內容。table
描邊爲黑色,內容爲黃色class
這裏的self.value是一個0-1的值,用來表示星星填充的範圍,爲1表明整個星星所有填充爲黃色。變量
這裏設置一個變量range 描繪了這個星星須要填充的範圍方法
最後利用CGContextFillRect 這個方法 將range範圍進行黃色填充im