IOS绘制虚线的方法总结
一、重写drawRect方法。
-(void)drawRect:(CGRect)rect
{
[superdrawRect:rect];
CGContextRefcurrentContext=UIGraphicsGetCurrentContext();
//设置虚线颜色
CGContextSetStrokeColorWithColor(currentContext,[UIColorBlackColor].CGColor);
//设置虚线宽度
CGContextSetLineWidth(currentContext,1);
//设置虚线绘制起点
CGContextMoveToPoint(currentContext,0,0);
//设置虚线绘制终点
CGContextAddLineToPoint(currentContext,self.frame.origin.x+self.frame.size.width,0);
//设置虚线排列的宽度间隔:下面的arr中的数字表示先绘制3个点再绘制1个点
CGFloatarr[]={3,1};
//下面最后一个参数“2”代表排列的个数。
CGContextSetLineDash(currentContext,0,arr,2);
CGContextDrawPath(currentContext,kCGPathStroke);
}
二、采用CAShapeLayer方式绘制虚线
CAShapeLayer*shapeLayer=[CAShapeLayerlayer]; [shapeLayersetBounds:self.bounds]; [shapeLayersetPosition:CGPointMake(self.frame.size.width/2.0,self.frame.size.height)]; [shapeLayersetFillColor:[UIColorclearColor].CGColor]; //设置虚线颜色 shapeLayersetStrokeColor:[UIColorBlackColor].CGColor]; //设置虚线宽度 [shapeLayersetLineWidth:self.frame.size.height]; [shapeLayersetLineJoin:kCALineJoinRound]; //设置虚线的线宽及间距 [shapeLayersetLineDashPattern:[NSArrayarrayWithObjects:[NSNumbernumberWithInt:3],[NSNumbernumberWithInt:1],nil]]; //创建虚线绘制路径 CGMutablePathRefpath=CGPathCreateMutable(); //设置虚线绘制路径起点 CGPathMoveToPoint(path,NULL,0,0); //设置虚线绘制路径终点 CGPathAddLineToPoint(path,NULL,self.frame.size.width,0); //设置虚线绘制路径 [shapeLayersetPath:path]; CGPathRelease(path); //添加虚线 [self.layeraddSublayer:shapeLayer];
关于这种方式已经有人整理出了一个非常好用的类方法,具体见下面这段代码,注意:下面非完整代码,如有需要,请自己百度搜索。
/**
**lineView:需要绘制成虚线的view
**lineLength:虚线的宽度
**lineSpacing:虚线的间距
**lineColor:虚线的颜色
**/
+(void)drawDashLine:(UIView*)lineViewlineLength:(int)lineLengthlineSpacing:(int)lineSpacinglineColor:(UIColor*)lineColor
{
CAShapeLayer*shapeLayer=[CAShapeLayerlayer];
.....
[shapeLayersetStrokeColor:lineColor.CGColor];
......
[shapeLayersetLineDashPattern:[NSArrayarrayWithObjects:[NSNumbernumberWithInt:lineLength],[NSNumbernumberWithInt:lineSpacing],nil]];
......
[lineView.layeraddSublayer:shapeLayer];
}
三、经济实惠型:采用贴图的方式绘制虚线(需要设计师切图配合)
UIImageView*imgDashLineView=[[UIImageViewalloc]initWithFrame:CGRectMake(15,200,self.view.frame.size.width-30,1)]; [imgDashLineViewsetBackgroundColor:[UIColorcolorWithPatternImage:[UIImageimageNamed:@"xuxian.png"]]]; [self.viewaddSubview:imgDashLineView];
总结
以上内容部分来自于网络,本着分享的学习精神,如有涉及侵权问题,请及时告知。以上就是这篇文章的全部内容,欢迎大家一起探讨学习,有问题请留言,小编将会尽快对你的问题进行回复。