现在的位置: 首页 > 综合 > 正文

ios画圆弧

2014年03月12日 ⁄ 综合 ⁄ 共 2338字 ⁄ 字号 评论关闭

首先看一下效果:

我定义了一个timer类,通过调用它来实现这样的效果。下面来看代码:

//  timer.h

#import <UIKit/UIKit.h>

@interface timer : UIView

- (id)initWithFrame:(CGRect)frame arcWidth:(double)width current:(double)current total:(double)total;

@end

//  TimeProportion.m


#import "TimeProportion.h"
#define PI 3.14159265358979323846


@implementation TimeProportion
static float arcWidth; //圆弧的宽度
static double pieCapacity;  //角度增量值

static inline float radians(double degrees) {
    return degrees * PI / 180;
}


- (id)initWithFrame:(CGRect)frame arcWidth:(double)width current:(double)current total:(double)total
{
    self = [super initWithFrame:frame];
    if (self) {
        arcWidth=width;
        pieCapacity=360*current/total;
        NSLog(@"pieCapacity->>%f",pieCapacity);
    }
    return self;
}

- (void)drawRect:(CGRect)rect {
    CGContextRef context = UIGraphicsGetCurrentContext();//获得当前view的图形上下文(context)
    //设置填充颜色
    CGContextSetRGBFillColor(context, 0, 0, 0, 1);
    //设置画笔颜色
//    CGContextSetRGBStrokeColor(context, 0, 0, 0, 1);
    //设置画笔线条粗细
//    CGContextSetLineWidth(context, 0);
    
    //扇形参数
    double radius; //半径
    if(self.frame.size.width>self.frame.size.height){
        radius=self.frame.size.height/2-self.frame.size.height/10;
    }else{
        radius=self.frame.size.width/2-self.frame.size.width/10;
    }
    int startX=self.frame.size.width/2;//圆心x坐标
    int startY=self.frame.size.height/2;//圆心y坐标
    double pieStart=270;//起始的角度
    int clockwise=1;//0=逆时针,1=顺时针
    
    //顺时针画扇形
    CGContextMoveToPoint(context, startX, startY);
    CGContextAddArc(context, startX, startY, radius, radians(pieStart), radians(pieStart+pieCapacity), clockwise);
    CGContextClosePath(context);
//    CGContextDrawPath(context, kCGPathEOFillStroke);
    CGContextFillPath(context);
    
    clockwise=0;//0=逆时针,1=顺时针
    CGContextSetRGBStrokeColor(context, 255, 153, 0, 1);
    CGContextSetRGBFillColor(context, 255, 153, 0, 1);
    //逆时针画扇形
    CGContextMoveToPoint(context, startX, startY);
    CGContextAddArc(context, startX, startY, radius, radians(pieStart), radians(pieStart+pieCapacity), clockwise);
    CGContextClosePath(context);
//    CGContextDrawPath(context, kCGPathEOFillStroke);
    CGContextFillPath(context);
    
    //    画圆
    CGContextBeginPath(context);
    CGContextSetRGBFillColor(context, 1.0, 1.0, 1.0, 1.0);
    CGRect circle = CGRectInset(self.bounds, arcWidth, arcWidth);
    CGContextAddEllipseInRect(context, circle);
    CGContextFillPath(context);
    
}

@end

调用时候的代码:

    首先引入这个类: #import"timer.h"

    然后再调用这个类:

    CGRect frame = CGRectMake(60, 120, 200, 200);
    
    timer *timerView = [[timer alloc] initWithFrame:frame arcWidth:20 current:1 total:4];
    timerView.backgroundColor=[UIColor whiteColor];//设置背景色:白色
    [self.view addSubview: timerView];

抱歉!评论已关闭.