ios 在UIView上画图,线条

1.画线条(实线,虚线)

- (void)drawRect:(CGRect)rect

{

    CGContextRef context = UIGraphicsGetCurrentContext();

    [self drawXLine:context rect:rect];

    [self drawLegend:context rect:rect];

}

-(CGContextRef)drawXLine:(CGContextRef)context rect:(CGRect)rect
{
    CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);
    
    //float partren[] = {2,3};
    //CGContextSetLineDash(context, 0,partren , 2); //画虚线
    
    CGContextMoveToPoint(context, 10, 0);
    CGContextAddLineToPoint(context, 0, 100);
    CGContextStrokePath(context);
    return context;
}

2.画图例说明

//画图例说明
-(void)drawLegend:(CGContextRef)context rect:(CGRect)_rect
{
    CGSize          myShadowOffset = CGSizeMake (2,  2);//矩形和阴影的位置
    CGContextSaveGState(context);
    CGContextSetFillColorWithColor(context, [UIColor colorWithRed:0.9 green:0.9 blue:0.9 alpha:1].CGColor);
    CGContextSetShadow (context, myShadowOffset, 2);   //背景的阴影
    CGContextFillRect(context, CGRectMake(self.frame.size.width/2-100, [UIScreen mainScreen].bounds.size.height-80, 200, 25.0));
    
    NSArray *groupTitle = [NSArray arrayWithObjects:@"提出问题数量",@"方案采纳数量", nil];
    int legendCount = [groupTitle count];
    int stepWidth = 15;
    
    for (int i = 0; i < legendCount; i++) {
        if (i == 0){
            //设定第一个图例的颜色
            CGContextSetFillColorWithColor(context, [UIColor colorWithRed:64.0/255.0 green:104.0/255.0 blue:168.0/255.0 alpha:1.0].CGColor);
        }
        else {
            //设定第二个图例的颜色
            CGContextSetFillColorWithColor(context, [UIColor colorWithRed:240.0/255.0 green:152.0/255.0 blue:56.0/255.0 alpha:1.0].CGColor);
        }
        CGContextSetShadow (context, myShadowOffset, 1);
        CGContextFillRect(context, CGRectMake(stepWidth + 50, [UIScreen mainScreen].bounds.size.height-72, 10, 10));  //小方块的大小以及位置
        
        UILabel *label2 = [[UILabel alloc] initWithFrame:CGRectMake(stepWidth+65, [UIScreen mainScreen].bounds.size.height-76, _rect.size.width, 18)];   //声明UIlbel并指定其位置和长宽
        label2.backgroundColor = [UIColor clearColor];                   //设置label的背景色,这里设置为透明色。
        label2.font = [UIFont fontWithName:@"Helvetica-Bold" size:12];   //设置label的字体和字体大小。
        //label2.transform = CGAffineTransformMakeRotation(0.1);           //设置label的旋转角度
        label2.text = [groupTitle objectAtIndex:i];                      //设置label所显示的文本
        label2.textColor = [UIColor blackColor];                         //设置文本的颜色
        label2.textAlignment =NSTextAlignmentLeft;                       //设置文本在label中显示的位置,这里为居中。
        [self addSubview:label2];
        stepWidth += 100;
    }
    CGContextRestoreGState(context);
}

---恢复内容结束---

原文地址:https://www.cnblogs.com/lihaibo-Leao/p/3260032.html