iOS上下文實現評價星星

coxb8788 7年前發布 | 12K 次閱讀 iOS開發 移動開發

常規思路:

創建兩個 view,通過 for 循環創建 imageView,未點亮星星視圖在下、點亮星星視圖在上重合在一起,當用戶點擊視圖時,通過改變點亮星星視圖的 width 實現功能

本文思路:

直接重寫 drawrect 方法,在 drawrect 用 drawimage 畫出星星,根據 currentValue 畫出不同類型的星星,當用戶點擊視圖時,改變 currentValue,并根據改變后的 currentValue 重新畫出星星。

展示圖:

展示圖

代碼:

自定義一個繼承 UIView 的 CYStarView

屬性:

/** 完成后執行的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:

- (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];

}</code></pre>

在 drawrect 中畫星星:

- (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);
}

}</code></pre>

關于坐標系相反而產生的翻轉的問題,可以閱讀: CGContextDrawImage使用和分析

使用:

在要使用的控制器中:

#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

 

 本文由用戶 coxb8788 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!