栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 移动开发 > iOS

IOS绘制虚线的方法总结

iOS 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

IOS绘制虚线的方法总结

一、重写drawRect方法。

- (void)drawRect:(CGRect)rect
{
 [super drawRect:rect];
CGContextRef currentContext = UIGraphicsGetCurrentContext();
//设置虚线颜色
 CGContextSetStrokeColorWithColor(currentContext, [UIColor BlackColor].CGColor);
 //设置虚线宽度
 CGContextSetLineWidth(currentContext, 1);
 //设置虚线绘制起点
 CGContextMoveToPoint(currentContext, 0, 0);
 //设置虚线绘制终点
 CGContextAddLineToPoint(currentContext, self.frame.origin.x + self.frame.size.width, 0);
 //设置虚线排列的宽度间隔:下面的arr中的数字表示先绘制3个点再绘制1个点
 CGFloat arr[] = {3,1};
 //下面最后一个参数“2”代表排列的个数。
 CGContextSetLineDash(currentContext, 0, arr, 2);
 CGContextDrawPath(currentContext, kCGPathStroke);
 
}

二、采用CAShapeLayer方式绘制虚线

CAShapeLayer *shapeLayer = [CAShapeLayer layer];
[shapeLayer setBounds:self.bounds];
[shapeLayer setPosition:CGPointMake(self.frame.size.width / 2.0, self.frame.size.height)];
[shapeLayer setFillColor:[UIColor clearColor].CGColor];
//设置虚线颜色
shapeLayer setStrokeColor:[UIColor BlackColor].CGColor];
//设置虚线宽度
[shapeLayer setLineWidth:self.frame.size.height];
[shapeLayer setLineJoin:kCALineJoinRound];
//设置虚线的线宽及间距
 [shapeLayer setLineDashPattern:[NSArray arrayWithObjects:[NSNumber numberWithInt:3], [NSNumber numberWithInt:1], nil]];
 //创建虚线绘制路径
 CGMutablePathRef path = CGPathCreateMutable();
 //设置虚线绘制路径起点
 CGPathMoveToPoint(path, NULL, 0, 0);
 //设置虚线绘制路径终点
 CGPathAddLineToPoint(path, NULL, self.frame.size.width, 0);
 //设置虚线绘制路径
 [shapeLayer setPath:path];
 CGPathRelease(path);
 //添加虚线
 [self.layer addSublayer:shapeLayer];

关于这种方式已经有人整理出了一个非常好用的类方法,具体见下面这段代码,注意:下面非完整代码,如有需要,请自己百度搜索。


 
+ (void)drawDashLine:(UIView *)lineView lineLength:(int)lineLength lineSpacing:(int)lineSpacing lineColor:(UIColor *)lineColor
{
 CAShapeLayer *shapeLayer = [CAShapeLayer layer];
 .....
 [shapeLayer setStrokeColor:lineColor.CGColor];
 ......
 [shapeLayer setLineDashPattern:[NSArray arrayWithObjects:[NSNumber numberWithInt:lineLength], [NSNumber numberWithInt:lineSpacing], nil]];
  ......
 [lineView.layer addSublayer:shapeLayer];
 
}

三、经济实惠型:采用贴图的方式绘制虚线(需要设计师切图配合)

UIImageView *imgDashLineView =[[UIImageView alloc] initWithframe:CGRectMake(15, 200, self.view.frame.size.width - 30, 1)];

[imgDashLineView setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"xuxian.png"]]];

[self.view addSubview:imgDashLineView];

总结

以上内容部分来自于网络,本着分享的学习精神,如有涉及侵权问题,请及时告知。以上就是这篇文章的全部内容,欢迎大家一起探讨学习,有问题请留言,小编将会尽快对你的问题进行回复。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/167178.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号