自定义弧形滑块加渐变色填充
首先用到的是:- (void)drawRect:(CGRect)rect此方法与视图绘画有关
方法使用:
- 在视图第一次出现时,UIView设置frame才会调用drawRect;
- 或者布局改变时、视图的内容改变时,调用sizeThatFits或setNeedsDisplay后drawRect方法才会被调用;
- sizeThatFits后会调用drawRect:
下面在画布上画一个弧形,弧形涉及到的参数:圆的半径、开始/结束弧度、绘制方向(顺时针/逆时针)
然后绘制拖动按钮:
#pragma mark 画按钮
-(void)drawHandle:(CGContextRef)ctx{
CGContextSaveGState(ctx);
CGPoint handleCenter = [self pointFromAngle: _angle +3.5];
[UIColor.whiteColor set];
CGContextFillEllipseInRect(ctx, CGRectMake(handleCenter.x-4, handleCenter.y-4, _lineWidth+8, _lineWidth+8));
CGContextRestoreGState(ctx);
}
渐变填充色CGContextDrawLinearGradient参数:根据需求传入一个颜色数组
-(void)drawBigHandle:(CGContextRef)ctx
{
CGContextSaveGState(ctx);
CGPoint handleCenter = [self pointFromAngle: _angle +3.5];
[KDSRGBColor(229, 229, 229) set];
CGContextFillEllipseInRect(ctx, CGRectMake(handleCenter.x-5, handleCenter.y-5, _lineWidth+10, _lineWidth+10));
CGContextRestoreGState(ctx);
}
-(CGPoint)pointFromAngle:(int)angleInt{
//Define the Circle center
CGPoint centerPoint = CGPointMake(self.frame.size.width/2 - _lineWidth/2, self.frame.size.height/2 - _lineWidth/2);
//Define The point position on the circumference
CGPoint result;
result.y = round(centerPoint.y + radius * sin(ToRad(angleInt)));
result.x = round(centerPoint.x + radius * cos(ToRad(angleInt)));
return result;
}
-(BOOL) beginTrackingWithTouch:(UITouch *)touch withEvent:(UIEvent *)event {
[super beginTrackingWithTouch:touch withEvent:event];
return YES;
}
-(BOOL) continueTrackingWithTouch:(UITouch *)touch withEvent:(UIEvent *)event {
[super continueTrackingWithTouch:touch withEvent:event];
CGPoint lastPoint = [touch locationInView:self];
//用于排除点在圆外面点与圆心半径80以内的点
if ((lastPoint.x>=0&&lastPoint.x<=275)&&(lastPoint.y>=0 && lastPoint.y<=275)) {
if ((lastPoint.x<=57.5 ||lastPoint.x>=217.5)||(lastPoint.y<=57.5 ||lastPoint.y>=217.5)) {
// [self moveHandle:lastPoint];
}
}
[self sendActionsForControlEvents:UIControlEventValueChanged];
return YES;
}
-(void)moveHandle:(CGPoint)point {
CGPoint centerPoint = CGPointMake(self.frame.size.width/2, self.frame.size.height/2);
int currentAngle = floor(AngleFromNorth(centerPoint, point, NO));
if (currentAngle>40 && currentAngle <140) {
}else{
if (currentAngle<=40) {
_angle = currentAngle+360;
}else{
_angle = currentAngle;
}
}
_currentValue =[self valueFromAngle];
[self setNeedsDisplay];
}
static inline float AngleFromNorth(CGPoint p1, CGPoint p2, BOOL flipped) {
CGPoint v = CGPointMake(p2.x-p1.x,p2.y-p1.y);
float vmag = sqrt(SQR(v.x) + SQR(v.y)), result = 0;
v.x /= vmag;
v.y /= vmag;
double radians = atan2(v.y,v.x);
result = ToDeg(radians);
return (result >=0 ? result : result + 360.0);
}
效果图: