画虚线

实际项目中需要画竖着的虚线,在网上没找到。。。就改造了一下画横着的虚线方法。

/**
 *  画虚线
 *
 *  @param frame   虚线的frame
 *  @param isTrans 是否要旋转(画竖线则为YES,横线则为NO)
 */
(void)shapeLineWithFrame:(CGRect)frame isTrans:(BOOL)isTrans{

    UIImageView *imageView = [[UIImageView alloc]initWithFrame:frame];

    imageView.backgroundColor = [UIColor clearColor];
    [self.contentView addSubview:imageView];

    if (isTrans) {
        CGRect rect = CGRectMake(CGRectGetMinX(imageView.frame)-(imageView.frame.size.height-imageView.frame.size.width)/2.0, CGRectGetMinY(imageView.frame)+(imageView.frame.size.height-imageView.frame.size.width)/2.0, imageView.frame.size.height, imageView.frame.size.width);
        imageView.frame = rect;
    }
    UIGraphicsBeginImageContext(imageView.frame.size);   //开始画线
    [imageView.image drawInRect:CGRectMake(                                                                                                                                                                                                                                                                                                                                                                  0, 0, CGRectGetWidth(imageView.frame), CGRectGetHeight(imageView.frame))];

    CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);  //设置线条终点形状

    CGFloat lengths[] = {3,3};
    CGContextRef line = UIGraphicsGetCurrentContext();
    CGContextSetStrokeColorWithColor(line, [UIColor lightGrayColor].CGColor);

    CGContextSetLineDash(line, 0, lengths, 2);  //画虚线
    CGContextMoveToPoint(line, 0, 0);    //开始画线
    CGContextAddLineToPoint(line, CGRectGetMaxX(imageView.frame), 0);
    CGContextStrokePath(line);

    imageView.image = UIGraphicsGetImageFromCurrentImageContext();
    if (isTrans) {
        CGAffineTransform transform = CGAffineTransformMakeRotation(M_PI_2);
        imageView.transform = transform;
    }
}

当参数isTransYES的时候,计算出竖线所对应的横线的frame(计算出以竖线的中心为原点旋转90°之后的frame),先画出横线,最后旋转90°(M_PI_2)即可;为NO时直接画虚线即可。

方法解释:

  • void CGContextSetLineDash (
    CGContextRef _Nullable c, //图形上下文 (可以理解为”画板“)
    CGFloat phase, //从多少单位(多远)开始画虚线
    const CGFloat * _Nullable
    lengths, //线和空格的长度数组
    size_t count //想要取的数组参数中元素的个数
    ); //设置怎么画

  • void CGContextMoveToPoint (
    CGContextRef _Nullable c, //图形上下文
    CGFloat x, //x坐标
    CGFloat y //y坐标
    ); //从指定的点开始画

  • void CGContextAddLineToPoint (
    CGContextRef _Nullable c, //图形上下文
    CGFloat x, //终点x坐标
    CGFloat y //终点y坐标
    ); // 设置终点

  • void CGContextStrokePath (
    CGContextRef _Nullable c
    ); // 在”画板“上画线

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值