iOS開發——儀表盤的制作


從事iOS開發時間也不短了,可是卻沒有自己的博客,實在是慚愧。自己下定決心要堅持寫自己的博客,提高自己,也能跟大家有更多的交流。今天來跟大家分享一下儀表盤的制作,希望對大家有所幫助。

  廢話不多說直接上代碼

 1 //表盤支持的最小體溫數值
 2 static CGFloat MIN_VALUE = 34;
 3 //表盤支持的最大體溫數值
 4 static CGFloat MAX_VALUE = 43;
 5 @implementation WQMeasureDashboardView
 6 - (void)drawRect:(CGRect)rect {
 7     //
 8     UIImage *imageBg = [UIImage imageNamed:@"bg_measure_dashboard"];
 9     [imageBg drawInRect:rect];
10     
11     UIImage *imageMask = [self getMeasureMaskImage:rect];
12     [imageMask drawInRect:rect];
13     
14     int viewW = rect.size.width;
15     int viewH = rect.size.height;
16     //繪制文本
17     int textW = 55;
18     int textH = 25;
19     
20     int textX = (viewW-textW)*0.5;
21     int textY = (viewH-textH)*0.5;
22     
23     NSString *valueStr = [NSString stringWithFormat:@"%.2f",self.value];
24     NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:25],NSForegroundColorAttributeName:[UIColor blackColor]};
25     [valueStr drawInRect:CGRectMake(textX, textY,textW,textH) withAttributes:dic];
26 }
27 -(UIImage *)getMeasureMaskImage:(CGRect) rect{
28     //繪制表盤
29     UIImage *imageDash = [UIImage imageNamed:@"bg_measure_dashboard_mask"];
30     
31     int viewW = rect.size.width;
32     int viewH = rect.size.height;
33     
34     CGFloat centerX = viewW*1.0/2.0;
35     CGFloat centerY = viewH*1.0/2.0;
36     
37     //裁剪圖片,通過繪制扇形進行裁剪
38     UIGraphicsBeginImageContextWithOptions(rect.size,NO,0);
39     [[UIColor redColor]set];
40     CGContextRef context = UIGraphicsGetCurrentContext();
41     
42     CGContextSetLineWidth(context, 2);
43     CGContextMoveToPoint(context, centerX, centerY);
44     float startAngle =[self getStartAngle];
45     float endAngle = M_PI*5/2.0;
46     CGContextAddArc(context, centerX, centerY, centerX,startAngle ,endAngle, 0);
47     CGContextClosePath(context);
48     CGContextClip(context);
49     [imageDash drawInRect:rect];
50     
51     //獲取裁剪后的圖片
52     UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
53     
54     UIGraphicsEndImageContext();
55     return newImage;
56 }
57 #pragma 獲取裁剪圖片的開始角度
58 -(CGFloat)getStartAngle{
59     float currentValue = _value;
60     if (currentValue<=MIN_VALUE) {
61         currentValue = MIN_VALUE;
62     }
63     if (currentValue >= MAX_VALUE) {
64         currentValue = MAX_VALUE;
65     }
66     //由於整個表盤被分成了9等份,所以每一份對應的角度是40度
67     float angle = M_PI/2.0+M_PI*ABS(currentValue-MIN_VALUE)*(40.0/180.0);
68     return angle;
69 }
70 -(void)setValue:(float)value{
71     _value = value;
72     [self setNeedsDisplay];
73 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM