IOS绘制虚线的方法总结
程序员文章站
2023-12-14 22:15:34
一、重写drawrect方法。
- (void)drawrect:(cgrect)rect
{
[super drawrect:rect];
cgcont...
一、重写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];
关于这种方式已经有人整理出了一个非常好用的类方法,具体见下面这段代码,注意:下面非完整代码,如有需要,请自己百度搜索。
/** ** lineview: 需要绘制成虚线的view ** linelength: 虚线的宽度 ** linespacing: 虚线的间距 ** linecolor: 虚线的颜色 **/ + (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];
总结
以上内容部分来自于网络,本着分享的学习精神,如有涉及侵权问题,请及时告知。以上就是这篇文章的全部内容,欢迎大家一起探讨学习,有问题请留言,小编将会尽快对你的问题进行回复。