2023年7月14日发(作者:)
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, .x + , 0); //设置虚线排列的宽度间隔:下⾯的arr中的数字表⽰先绘制3个点再绘制1个点 CGFloat arr[] = {3,1}; //下⾯最后⼀个参数“2”代表排列的个数。 CGContextSetLineDash(currentContext, 0, arr, 2); CGContextDrawPath(currentContext, kCGPathStroke);
}⼆、采⽤CAShapeLayer⽅式绘制虚线CAShapeLayer *shapeLayer = [CAShapeLayer layer];[shapeLayer setBounds:];[shapeLayer setPosition:CGPointMake( / 2.0, )];[shapeLayer setFillColor:[UIColor clearColor].CGColor];//设置虚线颜⾊shapeLayer setStrokeColor:[UIColor BlackColor].CGColor];//设置虚线宽度[shapeLayer setLineWidth:];[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, , 0); //设置虚线绘制路径 [shapeLayer setPath:path]; CGPathRelease(path); //添加虚线 [ addSublayer:shapeLayer];关于这种⽅式已经有⼈整理出了⼀个⾮常好⽤的类⽅法,具体见下⾯这段代码,注意:下⾯⾮完整代码,如有需要,请⾃⼰百度搜索。/** ** lineView: 需要绘制成虚线的view ** lineLength: 虚线的宽度 ** lineSpacing: 虚线的间距 ** lineColor: 虚线的颜⾊ **/
+ (void)drawDashLine:(UIView *)lineView lineLength:(int)lineLength lineSpacing:(int)lineSpacing lineColor:(UIColor *)lineColor{ CAShapeLayer *shapeLayer = [CAShapeLayer layer]; ..... [shapeLayer setStrokeColor:r]; ...... [shapeLayer setLineDashPattern:[NSArray arrayWithObjects:[NSNumber numberWithInt:lineLength], [NSNumber numberWithInt:lineSpacing], nil]]; ...... [ addSublayer:shapeLayer];
}三、经济实惠型:采⽤贴图的⽅式绘制虚线(需要设计师切图配合)UIImageView *imgDashLineView =[[UIImageView alloc] initWithFrame:CGRectMake(15, 200, - 30, 1)];[imgDashLineView setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@""]]];[ addSubview:imgDashLineView];总结以上内容部分来⾃于⽹络,本着分享的学习精神,如有涉及侵权问题,请及时告知。以上就是这篇⽂章的全部内容,欢迎⼤家⼀起探讨学习,有问题请留⾔,⼩编将会尽快对你的问题进⾏回复。
发布者:admin,转转请注明出处:http://www.yc00.com/news/1689264480a226422.html
评论列表(0条)