最近公司项目在某一个模块当中需要用到一个“圆弧”菜单,起初在网上找了很多Demo,都没有想要的效果,最后就自己摸索写了一个,其中有一个简单的从左到右连续出现的动画,效果如图:(代码在末尾)
圆弧菜单.png
1.绘制圆弧
LineWidth :圆弧宽度
OutRadius:圆弧半径
底层圆弧(浅色):
- (void)drawRect:(CGRect)rect {
//一个不透明类型的Quartz 2D绘画环境,相当于一个画布,你可以在上面任意绘画
CGContextRef context = UIGraphicsGetCurrentContext();
//void CGContextAddArc(CGContextRef c,CGFloat x, CGFloat y,CGFloat radius,CGFloat startAngle,CGFloat endAngle, int clockwise)
//x,y为圆点坐标,radius半径,startAngle为开始的弧度,endAngle为 结束的弧度,clockwise 0为顺时针,1为逆时针。
/*--------绘制底层圆弧--------*/
//画线笔颜色
CGContextSetStrokeColorWithColor(context, [UIColor colorWithRed:224/255.0 green:246/255.0 blue:243/255.0 alpha:1].CGColor);
//线的宽度
CGContextSetLineWidth(context, LineWidth);
//添加一个圆(弧)
CGContextAddArc(context, self.bounds.size.width/2, self.bounds.size.height, OutRadius, -M_PI, 0, 0);
//绘制路径
CGContextDrawPath(context, kCGPathStroke);
}
外层圆弧(深色):
说明一下,我在用CGContextSetLineCap方法设置圆弧的端点为圆角时,圆弧的首尾两端都会同时设置,由于没有找到只设置一边的方法,所以我在初始化view的时候遮住了首端的圆角,这样就看着只有尾端才有圆角效果。
/*--------绘制外层圆弧--------*/
CGContextSetStrokeColorWithColor(context, [UIColor colorWithRed:0/255.0 green:201/255.0 blue:171/255.0 alpha:1.0].CGColor);
//设置圆弧的端点形状 (圆角)
CGContextSetLineCap(context, kCGLineCapRound);
CGContextSetLineWidth(context, LineWidth);
CGContextAddArc(context, self.bounds.size.width/2, self.bounds.size.height, OutRadius, -M_PI, -M_2_PI, 0);
CGContextDrawPath(context, kCGPathStroke);
2.确定图标和菜单的位置
主要方法:
#pragma mark 计算圆圈上点在IOS系统中的坐标
/*
center 中心点坐标,angle 角度 ,radius 半径
由角度(x)转换弧度:(M_PI * (x) / 180.0)
由弧度(x)转换角度:(x*180.0)/(M_PI)
*/
-(CGPoint) calcCircleCoordinateWithCenter:(CGPoint) center andWithAngle : (CGFloat) angle andWithRadius: (CGFloat) radiusNumber{
CGFloat x2 = radiusNumber*cosf(angle*M_PI/180);
CGFloat y2 = radiusNumber*sinf(angle*M_PI/180);
return CGPointMake(center.x-x2, center.y-y2);
}
以小图标的位置为例,首先根据上面的方法计算出坐标,再将坐标作为图标的中心点,这样就搞定了。
//角度
#define Angle 180/8
CGPoint point = [self calcCircleCoordinateWithCenter:CGPointMake(self.bounds.size.width/2, self.bounds.size.height) andWithAngle:Angle*(i+1) andWithRadius: OutRadius];
iconBtn.center = point;
完整代码如下:
#pragma mark -- 圆弧内小图标数组
/*
array:表示装有图标的数组,从外部传值获得
*/
-(void)addIconSubView:(NSArray *)array{
for (int i = 0; i < array.count; i++) {
UIButton *iconBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 22, 22)];
[iconBtn setImage:[UIImage imageNamed:array[i]] forState:UIControlStateNormal];
iconBtn.tag=100+i;
CGPoint point = [self calcCircleCoordinateWithCenter:CGPointMake(self.bounds.size.width/2, self.bounds.size.height) andWithAngle:Angle*(i+1) andWithRadius: OutRadius];
iconBtn.center = point;
iconBtn.alpha = 0;
[self addSubview:iconBtn];
//动画,连续出现
[UIView animateWithDuration:0.5 delay:i*0.1 options:UIViewAnimationOptionCurveLinear animations:^{
iconBtn.alpha = 1;
} completion:^(BOOL finished) {
}];
}
}
菜单跟图标一样,完整的Demo可以通过以下链接下载:
https://github.com/BeginnerF/CLArcMenu