前陣子與群裡的一位設計師合作,參照網上一段旋鈕 gif 的構想,純用程式碼把它復刻了出來。先來看看原型的模樣。

再看我完成後的成品——我額外加入了一個「移動光源來控制陰影」的效果,讓整體更立體一些(那個小太陽的擺放確實有點突兀……)。
程式碼連結:https://git.oschina.net/BearXR/CircleKnob
單獨的下載包:https://download.csdn.net/detail/xiongbaoxr/9419655

接下來簡單拆解一下我的思路與部分關鍵程式碼。
1. 搭建底盤
首先要做出兩個圓盤,以及旋鈕上那顆紅點。

用 view 畫出兩個圓盤和一個小小的紅色控制點。
注意:紅色控制點我另外開了一個 view,方便後續掛上手勢控制,又不會干擾底層的 view。而且所有 view 的圓心都要設定精準,因為後面牽涉到大量與角度相關的計算,最好能讓它與 self.view 或 window 建立明確關聯。
2. 為底盤加入點擊與拖動手勢
這一步要加上手勢,以及起始角、終止角。我畫了輔助線方便除錯,手勢與過渡動效都完成後,效果如下。

3. 加入外圍扇環
由於後續要做陰影,除了扇環底色與效果共用一個 view,其餘每一小格我都各自開了獨立 view,並把旋鈕圓心設為錨點來旋轉。

#pragma mark - 設置外圍的扇環形 - (void)initSetFanView { CGFloat delta_distance = 26; fanView = [[FanView alloc] initWithFrame:CGRectMake(0, 0, knob_width + delta_distance * 2, knob_width + delta_distance * 2)]; fanView.center = knob.center; fanView.backgroundColor = [UIColor clearColor]; fanView.userInteractionEnabled = NO; [self.view addSubview:fanView]; fanView.knobValue = -startAngleValue;//設置起始點 fanView.lightSource_InWindow = lightSource; } - (void)drawRect:(CGRect)rect { contextBack = UIGraphicsGetCurrentContext(); contextFore = UIGraphicsGetCurrentContext(); [self drawFan:contextBack bezierPath:bezierPathBack knobAngle:180 + endAngleValue strokeColor:[UIColor colorWithRed:202/255.0 green:207/255.0 blue:202/255.0 alpha:1.0f]]; [self drawFan:contextFore bezierPath:bezierPathFore knobAngle:_knobValue strokeColor:[UIColor colorWithRed:174/255.0 green:0/255.0 blue:0/255.0 alpha:1.0f]]; } // 繪制扇形 - (void)drawFan:(CGContextRef)context bezierPath:(UIBezierPath *)bezierPath knobAngle:(CGFloat)knobAngle strokeColor:(UIColor *)strokeColor { CGRect frame = self.frame; CGFloat radius = (CGRectGetWidth(frame) - lineWidth) / 2; CGFloat angleForOne = M_PI / 180.0f; CGFloat circleLength = radius * 2 * M_PI; int gapCount = fanShowCount - 1; //間隙個數 CGFloat gapWidth = 5; //間隙距離 // 計算需要繪制的角度(角度制) knobAngle = knobAngle < -startAngleValue ? -startAngleValue : knobAngle; knobAngle = knobAngle > 180 + endAngleValue ? 180 + endAngleValue : knobAngle; // 設置弧線路徑 bezierPath = [UIBezierPath bezierPathWithArcCenter:CGPointMake(CGRectGetWidth(frame)/2, CGRectGetHeight(frame)/2) radius:(CGRectGetWidth(frame) - lineWidth)/2.0 startAngle:angleForOne * (180 - startAngleValue) endAngle:angleForOne * (180 + knobAngle) clockwise:YES]; CGContextAddPath(context, bezierPath.CGPath); // 設置線的顏色,線寬,接頭樣式 CGContextSetStrokeColorWithColor(context, strokeColor.CGColor); CGContextSetFillColorWithColor(context, [UIColor clearColor].CGColor); CGContextSetLineWidth(context, lineWidth); CGContextSetLineCap(context, kCGLineCapButt); // 繪制虛線 CGFloat drawLineLength = circleLength * (1- (startAngleValue + endAngleValue)/fullAngleValue); CGFloat showLineLengthPer = (drawLineLength - gapWidth * gapCount)/(fanShowCount - 1); CGFloat lengths[2] = {showLineLengthPer,gapWidth}; CGContextSetLineDash(context, 0, lengths, 2); CGContextDrawPath(context, kCGPathFillStroke);//最後一個參數是填充類型 if (!self.blockViewArray) { self.blockViewArray = [[NSMutableArray alloc] init]; } // 繪制小方格view(並且只繪制一次) static BOOL drawBlock = NO; if (!drawBlock) { drawBlock = YES; for (int i = 1; i < fanShowCount; i++) { CGFloat blockWidth = lineWidth + 8; CGFloat blockHeight = 5; CGFloat block_x = CGRectGetWidth(frame) / 2 - radius - blockWidth/2; CGFloat block_y = CGRectGetHeight(frame) / 2; // 角度修正 if (blockHeight > gapWidth) { block_y = block_y - blockHeight/2; }else{ block_y = block_y + (gapWidth - blockHeight)/2; } // 方格view 可輔助繪制垂直平分線 ViewWithAutoShadow *viewBlock = [[ViewWithAutoShadow alloc] initWithFrame:CGRectMake(block_x, block_y, blockWidth, blockHeight)]; viewBlock.showAssistPoint = NO; viewBlock.backgroundColor = [UIColor colorWithRed:248/255.0 green:238/255.0 blue:237/255.0 alpha:1.0f]; [self addSubview:viewBlock]; // 根據錨點旋轉 CGFloat blockAngle = (180 + startAngleValue + endAngleValue)/fanShowCount*i - startAngleValue; CGAffineTransform rotate = GetCGAffineTransformRotateAroundPoint1(viewBlock.center.x, viewBlock.center.y, CGRectGetWidth(frame)/2, CGRectGetHeight(frame)/2, blockAngle/180.0 * M_PI); [viewBlock setTransform:rotate]; AppDelegate *myDelegate = [[UIApplication sharedApplication] delegate]; [viewBlock drawShadowEffectWithSourcePoint:_lightSource_InWindow assistInView:myDelegate.window]; [self.blockViewArray addObject:viewBlock]; } } }
4. 加入動畫效果
為底盤與扇環都加上動效,這裡用到了計時器(dispatch source timer)。關於計時器的用法,可參考這篇部落格:https://blog.csdn.net/xiongbaoxr/article/details/50580701

動效程式碼片段:
// 執行動畫 - (void)changeRadiusWithAnimation:(CGFloat)radius lastRadius:(CGFloat)lastRadius duration:(CGFloat)duration { CGFloat countAll = ABS(radius - lastRadius); double delaySeconds = 0.001f; CGFloat animateCount = duration/delaySeconds; __block int i = 0; dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue); dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, delaySeconds * NSEC_PER_SEC, 0); dispatch_source_set_event_handler(timer, ^{ dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ if (i >= animateCount) { dispatch_source_cancel(timer); }else{ i ++; dispatch_sync(dispatch_get_main_queue(), ^{ // 扇環進度條動畫 CGFloat anglePer = countAll/animateCount * i; int k = radius > lastRadius ? anglePer : -anglePer; CGFloat needValue = lastRadius + k; fanView.knobValue = needValue; // 該方法會重新調用drawRect方法 [fanView setNeedsDisplay]; // 旋鈕轉動 knob.transform = CGAffineTransformMakeRotation((needValue/180.0 - 0) * M_PI); }); } }); }); dispatch_resume(timer); }
5. 最後一步是陰影效果,這部分牽涉的細節最多,我不逐行解釋程式碼,只談思路。陰影處理主要集中在 ViewWithAutoShadow.h 這個類別。
5.1 先設定一個光源點,那顆小太陽所在的位置就是光源。

5.2 為了方便除錯與理解,我把所有要做投影的 view 都畫上與光源的連線、垂直平分線並適度延長,同時標出每個 view 的四個頂點與中心點。

5.3 仔細看,每個夾角處都有一小段突出,那就是陰影的偏移量。依此偏移量設定陰影,就能獲得接近真實的仿真效果。

5.4 把陰影套上去看看最終效果,是不是已經頗有味道了?

5.5 最後把輔助線全部關掉,再欣賞一次成品。
