封裝一個畫虛線的類
.h文件
#import <UIKit/UIKit.h>
@interface PHDashedLineView : UIView
@property(nonatomic,assign)CGPoint startPoint;//虛線起點
@property(nonatomic,assign)CGPoint endPoint;//虛線終點
@property(nonatomic,strong)UIColor* lineColor;//虛線顏色
@property(nonatomic,assign)CGFloat solidWidth; //虛線中橫線的寬度
@property(nonatomic,assign)CGFloat spaceWidth; //虛線中空白地方的寬度
@end
.m文件
#import "PHDashedLineView.h"
@implementation PHDashedLineView
- (void)drawRect:(CGRect)rect{
CGContextRef context = UIGraphicsGetCurrentContext(); //設置上下文
CGContextSetStrokeColorWithColor(context, _lineColor.CGColor);//線條顏色
CGContextSetLineWidth(context, 1.0);//線條寬度
CGContextMoveToPoint(context, _startPoint.x, _startPoint.y); //開始畫線, x,y 為開始點的坐標
CGContextAddLineToPoint(context, _endPoint.x, _endPoint.y);//畫直線, x,y 為線條結束點的坐標
CGFloat lengths[] = {_solidWidth,_spaceWidth};
CGContextSetLineDash(context, 0, lengths, 2);
CGContextStrokePath(context); //開始畫線
}
@end
使用
PHDashedLineView *view = [[PHDashedLineView alloc] initWithFrame:CGRectMake(0, PCView_H(self) - 1, SCREEN_WIDTH, 1)];
view.backgroundColor = [UIColor clearColor];
view.lineColor = COLORRGB187;
view.solidWidth = 1;
view.spaceWidth = 5;
view.startPoint = CGPointMake(0, 0);
view.endPoint = CGPointMake(self.frame.size.width, 0);
_dashedView = view;
[self addSubview:view];
上面例子中最后結果是畫了一條水平的直線,可以通過開始和結束的坐標畫出不同傾斜度的直線出來,如果在這行代碼<code>view.endPoint = CGPointMake(self.frame.size.width, 0);</code>后面加上<code>view.endPoint = CGPointMake(self.frame.size.width, 120);</code>就會畫出一條折線出來
更多好玩的,大家可以慢慢琢磨
網上還看到一種寫法,使用<code>CAShapeLayer</code>來繪制,下面附上代碼:
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(100, 100, 132, 150)];
view.backgroundColor = [UIColor cyanColor];
[self.view addSubview:view];
CAShapeLayer *shapeLayer = [CAShapeLayer layer];
[shapeLayer setFrame:view.bounds];
[shapeLayer setPosition:CGPointMake(0, 0)];
[shapeLayer setFillColor:[[UIColor clearColor] CGColor]];
// 設置虛線的顏色
[shapeLayer setStrokeColor:[[UIColor blackColor] CGColor]];
// 設置虛線的高度
[shapeLayer setLineWidth:1.0f];
[shapeLayer setLineJoin:kCALineJoinRound];
// 3=線的寬度 1=每條線的間距
[shapeLayer setLineDashPattern:
[NSArray arrayWithObjects:[NSNumber numberWithInt:3],
[NSNumber numberWithInt:1],nil]];
// Setup the path
CGMutablePathRef path = CGPathCreateMutable();
//給出起始和終點path
CGFloat coordinateX = view.frame.size.width / 2;
CGFloat coordinateY = view.frame.size.height / 2 * 3;
CGPathMoveToPoint(path, NULL, coordinateX, coordinateY);
CGPathAddLineToPoint(path, NULL, coordinateX + view.frame.size.width,coordinateY);
CGPathAddLineToPoint(path, NULL, coordinateX + view.frame.size.width,coordinateY - view.frame.size.height);
[shapeLayer setPath:path];
[[view layer] addSublayer:shapeLayer];
CGPathRelease(path);
請戳:原文鏈接