iOS小技能:基础形状的绘制(画虚线、三角形、圆角矩形、 椭圆、扇形)

1,149 阅读3分钟

一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第23天,点击查看活动详情

引言

需求:绘制矩形和虚线

image.png

  • 绘制文字

![image.png](https://p9-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/d0a3ad9bfffc4c68809db99a735f0d06~tplv-k3u1fbpfcp-watermark.image?)
    /*写文字*/
    CGContextSetRGBFillColor (context,  1, 0, 0, 1.0);//设置填充颜色

    [@"图片:" drawInRect:CGRectMake(10, 340+180, 80, 20) withAttributes:self.stringAttributes];

/**
 文字样式
 */
- (NSMutableDictionary*)getstringAttributes4Text{
    
    
    UIFont  *font = [UIFont boldSystemFontOfSize:15.0];//设置
    

    NSMutableDictionary *stringAttributes = [NSMutableDictionary dictionary];
    [stringAttributes setObject:font forKey: NSFontAttributeName];

    return stringAttributes;
}

I 基础形状

1.1 矩形

案例: 画矩形图形,并旋转90度

在这里插入图片描述

- (UIView *)leftstartV{
    if (nil == _leftstartV) {

        UIView *tmpView = [[UIView alloc]init];

        _leftstartV = tmpView;

        tmpView.layer.borderColor = [UIColor colorWithRed:254/255.0 green:192/255.0 blue:2/255.0 alpha:1.0].CGColor;
        tmpView.layer.borderWidth = 1;




        [self addSubview:tmpView];
        
        CGFloat angle =   M_PI_4;

        
     
        [tmpView setTransform:CGAffineTransformMakeRotation(angle)];
        
     
//
//    ————————————————
//    版权声明:本文为CSDN博主「iOS逆向」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
//    原文链接:https://blog.csdn.net/z929118967/article/details/73822163
        __weak __typeof__(self) weakSelf = self;

        [tmpView mas_makeConstraints:^(MASConstraintMaker *make) {


            make.right.equalTo(weakSelf.titleLab.mas_left).offset(kAdjustRatio(-7));
            
        


            make.centerY.equalTo(weakSelf.titleLab);
            
            



            make.size.mas_equalTo(CGSizeMake(kAdjustRatio(11.3), kAdjustRatio(11.3)));
        



        }];


    }
    return _leftstartV;
}

1.2 画线

用法

- (void)layoutSubviews{
    
    [super layoutSubviews];
    
    
    [self bringSubviewToFront:self.linView];

    [self.linView layoutIfNeeded];
    [CRMLineTool drawLineOfDashByCAShapeLayer:self.linView lineLength:(kAdjustRatio(3)) lineSpacing:kAdjustRatio(3) lineColor:k_tableView_Line lineDirection:YES];

}

通过 CAShapeLayer 方式绘制虚线

/**
 *  通过 CAShapeLayer 方式绘制虚线
 *
 *  param lineView:       需要绘制成虚线的view
 *  param lineLength:     虚线的宽度
 *  param lineSpacing:    虚线的间距
 *  param lineColor:      虚线的颜色
 *  param lineDirection   虚线的方向  YES 为水平方向, NO 为垂直方向
 **/
+ (void)drawLineOfDashByCAShapeLayer:(UIView *)lineView lineLength:(int)lineLength lineSpacing:(int)lineSpacing lineColor:(UIColor *)lineColor lineDirection:(BOOL)isHorizonal {
    

    CAShapeLayer *shapeLayer = [CAShapeLayer layer];

    [shapeLayer setBounds:lineView.bounds];

    if (isHorizonal) {

        [shapeLayer setPosition:CGPointMake(CGRectGetWidth(lineView.frame) / 2, CGRectGetHeight(lineView.frame))];

    } else{
        [shapeLayer setPosition:CGPointMake(CGRectGetWidth(lineView.frame) / 2, CGRectGetHeight(lineView.frame)/2)];
    }

    [shapeLayer setFillColor:[UIColor clearColor].CGColor];
    //  设置虚线颜色为blackColor
    [shapeLayer setStrokeColor:lineColor.CGColor];
    //  设置虚线宽度
    if (isHorizonal) {
        [shapeLayer setLineWidth:CGRectGetHeight(lineView.frame)];
    } else {

        [shapeLayer setLineWidth:CGRectGetWidth(lineView.frame)];
    }
    [shapeLayer setLineJoin:kCALineJoinRound];
    //  设置线宽,线间距
    [shapeLayer setLineDashPattern:[NSArray arrayWithObjects:[NSNumber numberWithInt:lineLength], [NSNumber numberWithInt:lineSpacing], nil]];
    //  设置路径
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathMoveToPoint(path, NULL, 0, 0);

    if (isHorizonal) {
        CGPathAddLineToPoint(path, NULL,CGRectGetWidth(lineView.frame), 0);
    } else {
        CGPathAddLineToPoint(path, NULL, 0, CGRectGetHeight(lineView.frame));
    }

    [shapeLayer setPath:path];
    CGPathRelease(path);
    //  把绘制好的虚线添加上来
    [lineView.layer addSublayer:shapeLayer];
}


初始化视图


- (UIView *)linView{
    if (nil == _linView) {
        UIView *tmpView = [[UIView alloc]init];
        _linView = tmpView;
        
        tmpView.backgroundColor = UIColor.whiteColor;
        
//        [_linView setBackgroundColor:k_tableView_Line];
        
        [self addSubview:tmpView];
        __weak __typeof__(self) weakSelf = self;
        
        

        [tmpView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(LineH);
//            make.top.equalTo(weakSelf.rightLable.mas_bottom3).offset(kAdjustRatio(20));

            make.bottom.offset(kAdjustRatio(-1));
            

            make.left.equalTo(weakSelf).offset(kAdjustRatio(kSideMargin));

            make.right.equalTo(weakSelf).offset(kAdjustRatio(-kSideMargin));
            

        }];
    }
    return _linView;
}


1.3 画三角形

- (void)setup_Draw3Points:(CGContextRef )context{
    
    
    CGFloat PointsY =  230;
    

    [@"画三角形:" drawInRect:CGRectMake(10, PointsY, 80, 20) withAttributes:self.stringAttributes];

    //只要三个点就行跟画一条线方式一样,把三点连接起来
    CGPoint sPoints[3];//坐标点
    sPoints[0] =CGPointMake(100, PointsY);//坐标1
    sPoints[1] =CGPointMake(140, PointsY);//坐标2
    sPoints[2] =CGPointMake(140, 190);//坐标3
    CGContextAddLines(context, sPoints, 3);//添加线
    CGContextClosePath(context);//封起来
    CGContextDrawPath(context, kCGPathFillStroke); //根据坐标绘制路径

}

II、圆角矩形

#pragma mark - ******** 画圆角矩形

- (void)setup_Arc:(CGContextRef )context{
    
    
    CGFloat Curvey = 260+70;
    

    
    [@"画圆角矩形:" drawInRect:CGRectMake(10, Curvey, 100, 20) withAttributes:self.stringAttributes];

    float fw = 180;
    float fh = 280+30;
    
    CGContextMoveToPoint(context, fw, fh-20);  // 开始坐标右边开始
    CGContextAddArcToPoint(context, fw, fh, fw-20, fh, 10);  // 右下角角度
    CGContextAddArcToPoint(context, 120, fh, 120, fh-20, 10); // 左下角角度
    CGContextAddArcToPoint(context, 120, 250, fw-20, 250, 10); // 左上角
    CGContextAddArcToPoint(context, fw, 250, fw, fh-20, 10); // 右上角
    CGContextClosePath(context);
    CGContextDrawPath(context, kCGPathFillStroke); //根据坐标绘制路径

    
}

III、 扇形和椭圆

#pragma mark - ******** 扇形和椭圆

- (void)setup_DrawEllipse:(CGContextRef )context{

    
    CGFloat EllipseY =  160+5;

    [@"画扇形和椭圆:" drawInRect:CGRectMake(10, EllipseY, 110, 20) withAttributes:self.stringAttributes];

    //1、画扇形,也就画圆,只不过是设置角度的大小,形成一个扇形
    UIColor*  aColor = [UIColor colorWithRed:0 green:1 blue:1 alpha:1];
    CGContextSetFillColorWithColor(context, aColor.CGColor);//填充颜色
    
    //以10为半径围绕圆心画指定角度扇形
    CGContextMoveToPoint(context, 160, 180);
    
    CGContextAddArc(context, 160, 185, 30,  -60 * M_PI / 180, -120 * M_PI / 180, 1);

    CGContextClosePath(context);
    CGContextDrawPath(context, kCGPathFillStroke); //绘制路径
 
    
    //2、画椭圆
    CGContextAddEllipseInRect(context, CGRectMake(160, 180, 20, 8));
    CGContextDrawPath(context, kCGPathFillStroke);

}

see also

demo

github.com/zhangkn/iOS… 可关注公众号:【iOS逆向】,回复消息6 获取demo源码