0
点赞
收藏
分享

微信扫一扫

iOS绘图------虚线的画法

本人有若干成套学习视频, 可试看! 可试看! 可试看, 重要的事情说三遍 包含Java, 数据结构与算法, iOS, 安卓, python, flutter等等, 如有需要, 联系微信tsaievan.

在项目中, 有两个地方用到了画虚线

  • 虚线标注某个点
    UIBezierPath *dashPath = [UIBezierPath bezierPath];
    [dashPath moveToPoint: CGPointMake(startPointX, startPonitY)];
    [dashPath addLineToPoint: CGPointMake(endPointX, endPointY)];
    dashPath.lineWidth = 1;
    CGFloat dashLineConfig[] = {2.0, 1.0};
    [dashPath setLineDash: dashLineConfig count: 2 phase: 2];
    UIColor *dashColor = [UIColor colorWithRed:0.31 green:0.30 blue:0.67 alpha:1];
    [dashColor setStroke];
    [dashPath stroke];
  • 虚线画按钮边框
///< 画button外面的蓝色虚线框
- (void)drawRect:(CGRect)rect {
    [super drawRect:rect];
    CAShapeLayer *border = [CAShapeLayer layer];
    border.strokeColor = JYBColor_Blue.CGColor;
    border.fillColor = nil;
    border.path = [UIBezierPath bezierPathWithRoundedRect:self.bounds cornerRadius:20].CGPath;
    border.frame = self.bounds;
    border.lineWidth = 0.5;
    border.lineCap = @"square";
    border.lineDashPattern = @[@2, @2];
    [self.layer addSublayer:border];
}

两种方法不同, 第一个是用贝塞尔曲线来画, 第二个是用CAShapeLayer来画.
其实还可以用CoreGraphic框架来画. 但其实CG框架和贝塞尔曲线是一个套路, OC中的UIBezierPath其实就是对C语言的CG框架的封装.

所以这里只需要介绍贝塞尔曲线的画法就可以了

- (void)setLineDash:(nullable const CGFloat *)pattern count:(NSInteger)count phase:(CGFloat)phase;

画虚线主要就是这个方法了

  • 第一个参数pattern:

就是一个C的数组, 以点为单位, 表明了一种模式:
{第一条线段的长度, 第一个间隔的长度, 第二条线段的长度...} 以此类推

比如:
{10,10}表示先绘制10个点,再跳过10个点,如此反复,如图:

{10, 20, 10},则表示先绘制10个点,跳过20个点,绘制10个点,跳过10个点,再绘制20个点,如此反复,如图:

  • 第二个参数count:

表示这个C数组的长度

  • 第三个参数phase:

phase参数表示在第一个虚线绘制的时候跳过多少个点, 比如文档中说明的当phase6时, 如果pattern5-2-3-2的话, 那么就会从第1个gap中间开始画这条虚线.

但理解了这个方法之后, 画线段就跟画直线一样简单了

另外, CAShapeLayerlineDashPattern属性其实也就跟上述方法中的pattern参数一样了. 大家举一反三就好了.

PS. 本人有若干成套学习视频, 包含Java, 数据结构与算法, iOS, 安卓, python, flutter等等, 如有需要, 联系微信tsaievan.

举报

相关推荐

0 条评论