iOS如何画虚线?

重写drawRect方法

准备:继承UIView的子类

1. .h文件

//

//  DashesLineView.h

//  inface

//

//  Created by huangzengsong on 15/5/11.

//  Copyright (c) 2015年 huangzs. All rights reserved.

//

 

#import <UIKit/UIKit.h>

 

@interface DashesLineView : UIView

@property(nonatomic)CGPoint startPoint;//虚线起点

@property(nonatomic)CGPoint endPoint;//虚线终点

@property(nonatomic,strong)UIColor* lineColor;//虚线颜色

@end

 

2. .m文件

//

//  DashesLineView.m

//  inface

//

//  Created by huangzengsong on 15/5/11.

//  Copyright (c) 2015年 huangzs. All rights reserved.

//

 

#import "DashesLineView.h"

 

@implementation DashesLineView

 

- (id)initWithFrame:(CGRect)frame

 

{

    

    self= [super initWithFrame:frame];

    

    if(self) {

        

        // Initialization code

        

    }

    

    return self;

    

}

 

// Only override drawRect: if you perform custom drawing.

 

// An empty implementation adversely affects performance during animation.

 

- (void)drawRect:(CGRect)rect

 

{

    

    CGContextRef context =UIGraphicsGetCurrentContext();

    

    CGContextBeginPath(context);

    

    CGContextSetLineWidth(context,1);//线宽度

    

    CGContextSetStrokeColorWithColor(context,self.lineColor.CGColor);

    

    CGFloat lengths[] = {1,2};//先画4个点再画2个点

    

    CGContextSetLineDash(context,0, lengths,2);//注意2(count)的值等于lengths数组的长度

    

    CGContextMoveToPoint(context,self.startPoint.x,self.startPoint.y);

    

    CGContextAddLineToPoint(context,self.endPoint.x,self.endPoint.y);

    

    CGContextStrokePath(context);

    

    CGContextClosePath(context);

    

}

 

 

 

/*

// Only override drawRect: if you perform custom drawing.

// An empty implementation adversely affects performance during animation.

- (void)drawRect:(CGRect)rect {

    // Drawing code

}

*/

 

@end

 

3.调用时

    self.DashLineView.startPoint=CGPointMake(0, 1);

    self.DashLineView.endPoint=CGPointMake(

[[UIScreen mainScreen] bounds].size.width

-40, 1);

    self.DashLineView.lineColor=

[UIColor colorWithRed:28.0/255.0 green:160.0/255.0 blue:229.0/255.0 alpha:1]

;

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。