2013-06-24 3 views
6

Я новичок программист ios. В одном из моих проектов мне нужно нарисовать круг, в котором различная часть круга будет заполнена разными цветами. Я могу нарисовать circle.But я не могу определить другую часть круга и заполнить их другим цветом. Вот скриншот, чтобы прояснить, что я хочу сделать. circle with different colorРисование круга, заполненного различными частями с разным цветом

Помощь будет принята с благодарностью.

+0

Похоже на круговой диаграмме. Почему бы не использовать [Core plot] (http://www.raywenderlich.com/13269/how-to-draw-graphs-with-core-plot-part-1) для этого? – Amar

+0

Чтобы люди могли дать вам ответы, соответствующие вашей реализации, вы можете сообщить нам, если вы используете функции CoreGraphics (те функции, которые начинаются с 'CGContext') в вашем собственном' drawRect', или используя 'UIBezierPath' 'stroke', или используя' CAShapeLayer'. – Rob

+0

@Rob на самом деле я использую основные графические функции, такие как CGContext. – sujat

ответ

11

Вы можете использовать UIBezierPath, который имеет способ addArcWithCenter:radius:startAngle:endAngle:clockwise:, где вы можете указать радиус, центр и углы. Код может выглядеть следующим образом, который привлекает четверть круга в зеленый цвет:

CGPoint center = CGPointMake(CGRectGetWidth(self.bounds)/2.f, CGRectGetHeight(self.bounds)/2.f); 
CGFloat radius = center.x - 10.f; 

UIBezierPath *portionPath = [UIBezierPath bezierPath]; 
[portionPath moveToPoint:center]; 
[portionPath addArcWithCenter:center radius:radius startAngle:0.f endAngle:M_PI_2 clockwise:YES]; 
[portionPath closePath]; 

[[UIColor greenColor] setFill]; 
[portionPath fill]; 

UIBezierPath *portionPath1 = [UIBezierPath bezierPath]; 
[portionPath1 moveToPoint:center]; 
[portionPath1 addArcWithCenter:center radius:radius startAngle:M_PI_2 endAngle:M_PI clockwise:YES]; 
[portionPath1 closePath]; 

[[UIColor blueColor] setFill]; 
[portionPath1 fill]; 

Конечно, вы можете также рассмотреть возможность использования библиотеки как CorePlot.

+0

, он отлично работает на одну порцию. но как я могу продолжить его с другими порциями? Я сделал тот же процесс для других частей, меняющих начальный угол и угол конца. Но не работает желательно – sujat

+0

Просто играйте с углами и цветами. Центр и радиус всегда должны быть одинаковыми. Вы должны были бы вычислить угол каждой части, а затем пройти через все части, увеличивая начальные и конечные уровни. – Karl

+0

Я подумал, что слишком. Но что-то не так в моем уголке. Не могли бы вы просто показать мне еще один угол вычисления угла. Я попробовал это для следующей части [startAngle: M_PI_2 endAngle: M_PI] – sujat

0

Это простой вопрос о тригонометрии. Выясните угол, который вам нужен для части пирога (процентное время среза пирога 360 градусов), затем вы переходите к центру. Линия к краю круга под соответствующим углом дуги к следующей стороне среза пирога для нужного угла дуги, затем вернитесь к центру.

В качестве альтернативы, вы можете использовать CorePlot, чтобы сделать круговые диаграммы для вас.

2

мы имеем 6 класс

CircleViewController.h, CircleViewController.m, GraphView.h, GraphView.h, CirclePart.h, CirclePart.m

CirclePart.h

#import <Foundation/Foundation.h> 
#import <UIKit/UIKit.h> 

@interface CirclePart : NSObject 

@property (nonatomic) CGFloat startDegree; 
@property (nonatomic) CGFloat endDegree; 
@property (nonatomic) UIColor *partColor; 

-(id)initWithStartDegree:(CGFloat)startDegree endDegree:(CGFloat)endDegree partColor:(UIColor*)partColor; 

@end 

CirclePart.m

#import "CirclePart.h" 

@implementation CirclePart 

-(id)initWithStartDegree:(CGFloat)startDegree endDegree:(CGFloat)endDegree partColor:(UIColor*)partColor 
{ 
    self = [super init]; 
    if (self) { 
     self.startDegree = startDegree; 
     self.endDegree = endDegree; 
     self.partColor = partColor; 
    } 
    return self; 
} 

@end 

GraphView.h

#import <UIKit/UIKit.h> 
#import "CirclePart.h" 

@interface GraphView : UIView 

@property (nonatomic) CGPoint centrePoint; 
@property (nonatomic) CGFloat radius; 
@property (nonatomic) CGFloat lineWidth; 
@property (nonatomic, strong) NSArray *circleParts; 

-(id)initWithFrame:(CGRect)frame CentrePoint:(CGPoint)centrePoint radius:(CGFloat)radius lineWidth:(CGFloat)lineWidth circleParts:(NSArray*)circleParts; 

@end 

GraphView.m

#import "GraphView.h" 

@implementation GraphView 

-(id)initWithFrame:(CGRect)frame CentrePoint:(CGPoint)centrePoint radius:(CGFloat)radius lineWidth:(CGFloat)lineWidth circleParts:(NSArray*)circleParts 
{ 
    self = [super initWithFrame:frame]; 
    if (self) { 
     self.centrePoint = centrePoint; 
     self.radius = radius; 
     self.lineWidth = lineWidth; 
     self.circleParts = circleParts; 
    } 
    return self; 
} 

- (void)drawRect:(CGRect)rect { 

    [self drawCircle]; 
} 

- (void)drawCircle { 

    CGContextRef context = UIGraphicsGetCurrentContext(); 
    CGContextSetLineWidth(context, _lineWidth); 

    for(CirclePart *circlePart in _circleParts) 
    { 
     CGContextMoveToPoint(context, _centrePoint.x, _centrePoint.y); 

     CGContextAddArc(context, _centrePoint.x , _centrePoint.y, _radius, [self radians:circlePart.startDegree], [self radians:circlePart.endDegree], 0); 
     CGContextSetFillColorWithColor(context, circlePart.partColor.CGColor); 
     CGContextFillPath(context); 
    } 
} 

-(float) radians:(double) degrees { 
    return degrees * M_PI/180; 
} 


@end 

CircleViewController.h

#import <UIKit/UIKit.h> 

@interface CircleViewController : UIViewController 

@end 

CircleViewController.m

#import "CircleViewController.h" 
#import "GraphView.h" 
#import "CirclePart.h" 

@interface CircleViewController() 

@end 

@implementation CircleViewController 

- (void)viewDidLoad { 
    [super viewDidLoad]; 

    CirclePart *part1 = [[CirclePart alloc] initWithStartDegree:0 endDegree:120 partColor:[UIColor redColor]]; 
    CirclePart *part2 = [[CirclePart alloc] initWithStartDegree:120 endDegree:250 partColor:[UIColor blueColor]]; 
    CirclePart *part3 = [[CirclePart alloc] initWithStartDegree:250 endDegree:360 partColor:[UIColor grayColor]]; 

    NSArray *circleParts = [[NSArray alloc] initWithObjects:part1, part2, part3, nil]; 

    CGRect rect = CGRectMake(100, 100, 200, 200); 
    CGPoint circleCenter = CGPointMake(rect.size.width/2, rect.size.height/2); 

    GraphView *graphView = [[GraphView alloc] initWithFrame:rect CentrePoint:circleCenter radius:80 lineWidth:2 circleParts:circleParts]; 
    graphView.backgroundColor = [UIColor whiteColor]; 
    graphView.layer.borderColor = [UIColor redColor].CGColor; 
    graphView.layer.borderWidth = 1.0f; 

    [self.view addSubview:graphView]; 
} 

- (void)didReceiveMemoryWarning { 
    [super didReceiveMemoryWarning]; 
    // Dispose of any resources that can be recreated. 
} 

@end