2011-09-30 90 views
0

我正在尝试创建饼图。每个馅饼应该有不同的颜色,并有边框。所以我做了我自己的课PieChart.m:CGContextSetRGBStrokeColor不会绘制边框

#import "PieChart.h" 


@implementation PieChart 
@synthesize startDeg, endDeg, isSelected, colorNumber; 

- (id)initWithFrame:(CGRect)frame 
{ 
    self = [super initWithFrame:frame]; 
    if (self) { 
     // Initialization code 
    } 
    return self; 
} 


// Only override drawRect: if you perform custom drawing. 
// An empty implementation adversely affects performance during animation. 
- (void)drawRect:(CGRect)rect 
{ 
    // Drawing code 

    int centerX = 120; 
    int centerY = 160; 
    int radius = 94; 

    CGContextRef ctx = UIGraphicsGetCurrentContext(); 
    CGContextSetRGBStrokeColor(ctx, 255.0/255.0, 255.0/255.0, 255.0/255.0, 1.0); 
    CGContextSetLineWidth(ctx, 2.0); 

    CGContextSetRGBFillColor(ctx, [self getColorFor:1]/255.0, [self getColorFor:2]/255.0, [self getColorFor:3]/255.0, 1.0); 

    CGContextMoveToPoint(ctx, centerX, centerY); 
    CGContextAddArc(ctx, centerX, centerY, radius, (startDeg)*M_PI/180.0, (endDeg)*M_PI/180.0, 0); 

    CGContextClosePath(ctx); 
    CGContextFillPath(ctx); 
} 

- (void)dealloc 
{ 
    [super dealloc]; 
} 

-(float)getColorFor:(int)rgb { 
    if (colorNumber == 1) { 
     switch (rgb) { 
      case 1: 
       return 232.0; 
       break; 
      case 2: 
       return 96.0; 
       break; 
      case 3: 
       return 104.0; 
       break; 

      default: 
       return 255.0; 
       break; 
     } 
    } 
    if (colorNumber == 2) { 
     switch (rgb) { 
      case 1: 
       return 248.0; 
       break; 
      case 2: 
       return 198.0; 
       break; 
      case 3: 
       return 6.0; 
       break; 

      default: 
       return 255.0; 
       break; 
     } 
    } 

    return 255.0; 
} 

@end 

问题是,边界永远不会画。或者,如果我设法绘制边界,填充不会在那里!任何建议如何实现?

这是我如何使用这个类在我的ViewController:

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    PieChart *pie1 = [[PieChart alloc] initWithFrame:CGRectMake(10, 10, 300, 400)]; 
    pie1.startDeg = 0; 
    pie1.endDeg = 127; 
    pie1.colorNumber = 1; 
    pie1.backgroundColor = [UIColor clearColor]; 

    PieChart *pie2 = [[PieChart alloc] initWithFrame:CGRectMake(10, 10, 300, 400)]; 
    pie2.startDeg = 127; 
    pie2.endDeg = 360; 
    pie2.colorNumber = 2; 
    pie2.backgroundColor = [UIColor clearColor]; 

    [self.view addSubview:pie1]; 
    [self.view addSubview:pie2]; 
} 

回答

2

与您的代码的问题是,你只填写你的路径,而不是抚摸着它 - 那么自然边界正在绘制。您需要替换CGContextFillPath调用

CGContextDrawPath (ctx, kCGPathFillStroke); 
+0

感谢的人解决这个问题!这就像一个魅力;) – dizza213

0

抚摸或填充路径会清除当前路径。这就是为什么一个人可以工作而不是另一个人(无论你先试一试)。

您可以通过重新加入轻抚你的前路,或使用CGContextDrawPath