iOS开发_绘制圆角矩形虚线环

- (void)drawRect:(CGRect)rect {
    
    // 获取上下文(/画笔/绘图环境)
    CGContextRef context = UIGraphicsGetCurrentContext();
    // 小段长度
    CGFloat line_dash = self.height / 20;
    
    // 虚线的样式:长5 空隙15 长10 空隙30 长2 空隙20...
    //CGFloat lengths[] = {5, 15, 10, 30, 2, 20};
    CGFloat lengths[] = {line_dash, 2 * line_dash};
    /**
     * phase 开始点 跳过多少个点数(0代表从头画)
     * lengths 虚线的样式
     * count 长度
    */
    // CGContextSetLineDash(<#CGContextRef c#>, <#CGFloat phase#>, <#const CGFloat *lengths#>, <#size_t count#>)
    CGContextSetLineDash(context, 1, lengths, sizeof(lengths) / sizeof(lengths[0]));
    // 在自身尺寸内缩进一点进行绘制
    CGFloat inset_offset = 2 * line_dash;
    
    CGRect frame = [self bounds:inset_offset];
    
    CGFloat org_x = frame.origin.x;
    CGFloat org_y = frame.origin.y;
    CGFloat size_w = frame.size.width;
    CGFloat size_h = frame.size.height;
    
    // 圆角半径
    CGFloat radius = 2 * line_dash;
    // 线条的宽度
    CGContextSetLineWidth(context, line_dash / 5.f);
    // 设置线条颜色
    [[UIColor whiteColor] set];
    
    // 开始坐标右边开始
    CGContextMoveToPoint(context, org_x + size_w, org_y + size_h - radius);
    // 右下角角度
    CGContextAddArcToPoint(context, org_x + size_w, org_y + size_h, org_x + size_w - radius, org_y + size_h, radius);
    // 左下角角度
    CGContextAddArcToPoint(context, org_x, org_y + size_h, org_x, org_y + size_h - radius, radius);
    // 左上角
    CGContextAddArcToPoint(context, org_x, org_y, org_x + radius, org_y, radius);
    // 右上角
    CGContextAddArcToPoint(context, org_x + size_w, org_y, org_x + size_w, org_y + radius, radius);
    // 圆角矩形闭环
    CGContextClosePath(context);
    
    // 画线
    CGContextStrokePath(context);
}

- (CGRect)bounds:(CGFloat)inset_offset {
    CGFloat org_x = inset_offset;
    CGFloat org_y = inset_offset;
    CGFloat size_w = self.width - 2 * inset_offset;
    CGFloat size_h = self.height - 2 * inset_offset;
    CGRect frame = CGRectMake(org_x, org_y, size_w, size_h);
    return frame;
}
posted @ 2024-05-27 14:22  CH520  阅读(11)  评论(0编辑  收藏  举报