iOS绘制虚线框

3,521 阅读1分钟

1.逻辑

  • 将4条虚线连接起来,绘制一个虚线框
  • 这里使用的是CGContextRef

2.要点

虚线,起点到终点画线,如下

//设置虚线绘制起点     
CGContextMoveToPoint(currentContext, 0, 0);     
//设置虚线绘制终点
CGContextAddLineToPoint(currentContext, rect.origin.x + rect.size.width, 0);

然后将上下左右4个点连接起来,如效果图:

3.主要代码(画线方法在UIView里实现)

#import "XWShaperLyaerView.h"

@implementation XWShaperLyaerView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor clearColor]; //设置透明是看上去像个虚线框
    }
    return self;
}

//提供一个实例方法
- (void)reloadViewLayer {
    [self setNeedsDisplay];
}

/**
    逻辑:将4条虚线连接起来绘制一个虚线框
 */
- (void)drawRect:(CGRect)rect{
     [super drawRect:rect];
     CGContextRef currentContext = UIGraphicsGetCurrentContext();
     //设置虚线颜色
     CGContextSetStrokeColorWithColor(currentContext, [UIColor redColor].CGColor);
     //设置虚线宽度
     CGContextSetLineWidth(currentContext, 3);

    //上
     //设置虚线绘制起点
     CGContextMoveToPoint(currentContext, 0, 0);
     //设置虚线绘制终点
     CGContextAddLineToPoint(currentContext, rect.origin.x + rect.size.width, 0);

    //右
    CGContextMoveToPoint(currentContext, rect.origin.x + rect.size.width, 0);
    CGContextAddLineToPoint(currentContext, rect.origin.x + rect.size.width, rect.origin.y + rect.size.height);

    //左
    CGContextMoveToPoint(currentContext, 0, 0);
    CGContextAddLineToPoint(currentContext, 0, rect.size.height);

    //下
    CGContextMoveToPoint(currentContext, 0, rect.size.height);
    CGContextAddLineToPoint(currentContext, rect.origin.x + rect.size.width, rect.origin.y + rect.size.height);

     //设置虚线排列的宽度间隔:下面的arr中的数字表示先绘制3个点再绘制3个点
     CGFloat arr[] = {3,3};
     //下面最后一个参数“2”代表排列的个数。
     CGContextSetLineDash(currentContext, 0, arr, 2);
     CGContextDrawPath(currentContext, kCGPathStroke);
}

@end

4.使用方式

如下:在屏幕上滑动添加封装好的UIView,可以做出随着滑动变化的虚线框

- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    CGPoint point = [self getTouchSet:touches];
    if (self.shapType == XWDrawingShapeScreenshots) { //截图
        // 移除遮盖
        [self.coverView removeFromSuperview];
        CGFloat x = self.startPoint.x;
        CGFloat y = self.startPoint.y;
        CGFloat width = point.x - self.startPoint.x;
        CGFloat height = point.y - self.startPoint.y;
        if (width < 0) {
            width = -width;
            x = x - width;
        }
        if (height < 0) {
            height = -height;
            y = y - height;
        }
        CGRect rect = CGRectMake(x, y, width, height);
        XWShaperLyaerView *coverView = [[XWShaperLyaerView alloc] init];
        self.coverView = coverView;
        // 添加一个view
        self.coverView.frame = rect;
        [self addSubview:self.coverView]; // 解决下次进行裁剪的时候没有coverview的覆盖
        [self.coverView reloadViewLayer];
    }
}