虚线的实现

论坛 期权论坛 脚本     
匿名技术用户   2021-1-4 02:51   80   0


转载:http://blog.csdn.net/zh198964/article/details/47727053


因为项目需要画虚线,起初想用图片重复叠加实现。搜罗了一圈还是封装一个UIView

代码如下

.h文件
[objc] view plain copy
  1. #import <UIKit/UIKit.h>
  2. @interface DashesLineView : UIView
  3. @property(nonatomic)CGPoint startPoint;//虚线起点
  4. @property(nonatomic)CGPoint endPoint;//虚线终点
  5. @property(nonatomic,strong)UIColor* lineColor;//虚线颜色
  6. @end

.m文件

[objc] view plain copy
  1. #import "DashesLineView.h"
  2. #define kInterval 10 // 全局间距
  3. @implementation DashesLineView
  4. - (id)initWithFrame:(CGRect)frame
  5. {
  6. self= [super initWithFrame:frame];
  7. if(self) {
  8. _lineColor = [UIColor redColor];
  9. _startPoint = CGPointMake(0, 1);
  10. _endPoint = CGPointMake(screen_width , 1);
  11. }
  12. return self;
  13. }
  14. - (void)drawRect:(CGRect)rect {
  15. CGContextRef context = UIGraphicsGetCurrentContext();
  16. CGContextBeginPath(context);
  17. CGContextSetLineWidth(context,0.5);//线宽度
  18. CGContextSetStrokeColorWithColor(context,self.lineColor.CGColor);
  19. CGFloat lengths[] = {4,2};//先画4个点再画2个点
  20. CGContextSetLineDash(context,0, lengths,2);//注意2(count)的值等于lengths数组的长度
  21. CGContextMoveToPoint(context,self.startPoint.x,self.startPoint.y);
  22. CGContextAddLineToPoint(context,self.endPoint.x,self.endPoint.y);
  23. CGContextStrokePath(context);
  24. CGContextClosePath(context);
  25. }
  26. @end
分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:7942463
帖子:1588486
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP