iOS 方形虚线的实现

项目中经常有虚线的需求,现整理一部分,不足之处再修改

方形虚线:

/**

** lineView:      需要绘制成方形虚线的view

** lineLength:    虚线的宽度

** lineSpacing:  虚线的间距

** lineColor:     虚线的颜色

**/


-(void)drawSquareDottedLine:(UIView*)squareView lineLength:(int)lineLength lineSpacing:(int)lineSpacing lineColor:(UIColor*)lineColor

{

CAShapeLayer *border = [CAShapeLayer layer];

border.strokeColor = lineColor.CGColor;

border.fillColor = nil;

border.path = [UIBezierPath bezierPathWithRect:squareView.bounds].CGPath;

border.frame = squareView.bounds;

border.lineWidth = 1.0f;

border.lineCap = @"square";

border.lineDashPattern = @[@(lineLength), @(lineSpacing)];

[squareView.layer addSublayer:border];

}

虚线:

/**

** lineView:      需要绘制成虚线的view

** lineLength:  虚线的宽度

** lineSpacing: 虚线的间距

** lineColor:     虚线的颜色

**/

- (void)drawDashLine:(UIView *)lineView lineLength:(int)lineLength lineSpacing:(int)lineSpacing lineColor:(UIColor *)lineColor

{

CAShapeLayer *shapeLayer = [CAShapeLayer layer];

[shapeLayer setBounds:lineView.bounds];

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

[shapeLayer setFillColor:[UIColor clearColor].CGColor];

//  设置虚线颜色为blackColor

[shapeLayer setStrokeColor:lineColor.CGColor];

//  设置虚线宽度

[shapeLayer setLineWidth:CGRectGetHeight(lineView.frame)];

[shapeLayer setLineJoin:kCALineJoinRound];

//  设置线宽,线间距

[shapeLayer setLineDashPattern:[NSArray arrayWithObjects:[NSNumber numberWithInt:lineLength], [NSNumber numberWithInt:lineSpacing], nil]];

//  设置路径

CGMutablePathRef path = CGPathCreateMutable();

CGPathMoveToPoint(path, NULL, 0, 0);

CGPathAddLineToPoint(path, NULL, CGRectGetWidth(lineView.frame), 0);

[shapeLayer setPath:path];

CGPathRelease(path);

//  把绘制好的虚线添加上来

[lineView.layer addSublayer:shapeLayer];

}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 172,983评论 25 708
  • 千年的轮回依旧,是谁唤醒了江南沉睡的烟雨?梦中的江南是否还在,梦中之景是否还存?烟雨又起,雨脚如麻,丝丝细雨总是让...
    贱猫咪阅读 1,059评论 0 3
  • 四、巧取江城 永城,又名永丰,建城之人原想借此名期盼此城能永世丰登。可惜天不遂人愿,此处土地贫瘠,又不在南北要道之...
    文宇之穹阅读 721评论 0 50