1. 程式人生 > 程式設計 >Android實現根據評分新增星級條

Android實現根據評分新增星級條

簡述

在仿寫豆瓣的時候,發現了根據評分不同,星級數也不同的星級條。

百度一搜,發現Android有自帶控制元件UIRatingBar,而iOS得要自己寫…好吧,那就寫吧。

圖片素材

首先,要準備三張圖片,圖片如下:
空星,半星,全星

因為我們可以看到,在豆瓣的評分星級條裡,只有空、半、全星,所以只需要準備這3種圖片。

思路

豆瓣的星級條中既有圖片,又有文字,所以我們自定義一個繼承於UIViewstarView

初始化方法

因為星級條要根據評分的資料來決定星的顆數,所以我們要重新建立一個初始化方法:

//在starView.m中寫

- (instancetype)initWithFrame:(CGRect)frame score:(double)score;


//在starView.h中對其進行操作實現
- (instancetype)initWithFrame:(CGRect)frame score:(double)score{
 self = [super initWithFrame:frame];
 //記得把傳過來的score賦值給全域性變數_starScore
 _starScore = score;
 return self;
}

這樣,我們就可以在ViewController.m中利用此方法初始化一個星級條檢視:

starView *star = [[CJTStarView alloc] initWithFrame:CGRectMake(100,100,200,50) score:6.8];

此處的score可以改成根據網路請求得到的評分資料。

根據新增星星圖片

在這裡,我設定的分數與星星的對應關係如下:

4.6-5.5 2.5顆星
5.6-6.5 3顆星
6.6-7.5 3.5顆星
7.6-8.5 4顆星
8.6-9.5 4.5顆星

而因為我們只有5顆星,所以對分數做如下處理:

_starScore = (_starScore / 2 - 0.3);

接下來就是用迴圈新增圖片到view上,因為我們有三種圖片,所以在迴圈中還要加判斷,程式碼如下:

for (int count = 0; count < 5; count++) {
 UIImageView *starImageView = [[UIImageView alloc] init];
 starImageView.frame = CGRectMake(count * self.frame.size.height,self.frame.size.height,self.frame.size.height);
 [self addSubview:starImageView];
 if (count <= _starScore - 0.5) {
  starImageView.image = [UIImage imageNamed:@"stars_full"];
 } else {
  if (_starScore - count >= 0 && _starScore - count < 0.5) {
  starImageView.image = [UIImage imageNamed:@"stars_half"];
  } else {
  starImageView.image = [UIImage imageNamed:@"stars_empty"];
  }
 }
 }

這裡的判斷條件是數學問題,就不詳細講了。

當然,如果分數與星星的對應規則和我不同,那麼就要適當修正這裡的判斷條件。

在星級條後新增分數

在豆瓣到星級條後面還有分數,因此我們在view中新增一個UILabel物件。

UILabel *scoreLabel = [[UILabel alloc] init];
 scoreLabel.frame = CGRectMake( 5 * self.frame.size.height + 10,8,self.frame.size.width - 5 * self.frame.size.height - 10,self.frame.size.height - 8);
 scoreLabel.text = [NSString stringWithFormat:@"%.1f",_starScore];
 scoreLabel.textColor = [UIColor grayColor];
 scoreLabel.font = [UIFont systemFontOfSize:25];

這裡要注意,因為我們在設定星級圖的時候會修改_starScore的值,所以要在新增星星圖片之前設定UILabel

效果圖

最後做出來到效果如下:

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。