How to make a UIView with optional rounded corners and border?

前端 未结 3 614
余生分开走
余生分开走 2020-12-17 08:26

I am applying corner radius to a UIView i.e. UIRectCornerTopLeft and UIRectCornerTopRight. When I apply this, the border is gone at t

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-17 08:52

    Found this piece of code. Have not actually tried it, but seems like it is what you need.

    - (void)drawDashedBorderAroundView:(UIView *)v {
    
        //border definitions
        CGFloat cornerRadius = 10;
        CGFloat borderWidth = 2;
        NSInteger dashPattern1 = 8;
        NSInteger dashPattern2 = 8;
        UIColor *lineColor = [UIColor orangeColor];
    
        //drawing
        CGRect frame = v.bounds;
    
        CAShapeLayer *_shapeLayer = [CAShapeLayer layer];
    
        //creating a path
        CGMutablePathRef path = CGPathCreateMutable();
    
        //drawing a border around a view
        CGPathMoveToPoint(path, NULL, 0, frame.size.height - cornerRadius);
        CGPathAddLineToPoint(path, NULL, 0, cornerRadius);
        CGPathAddArc(path, NULL, cornerRadius, cornerRadius, cornerRadius, M_PI, -M_PI_2, NO);
        CGPathAddLineToPoint(path, NULL, frame.size.width - cornerRadius, 0);
        CGPathAddArc(path, NULL, frame.size.width - cornerRadius, cornerRadius, cornerRadius, -M_PI_2, 0, NO);
        CGPathAddLineToPoint(path, NULL, frame.size.width, frame.size.height - cornerRadius);
        CGPathAddArc(path, NULL, frame.size.width - cornerRadius, frame.size.height - cornerRadius, cornerRadius, 0, M_PI_2, NO);
        CGPathAddLineToPoint(path, NULL, cornerRadius, frame.size.height);
        CGPathAddArc(path, NULL, cornerRadius, frame.size.height - cornerRadius, cornerRadius, M_PI_2, M_PI, NO);
    
        //path is set as the _shapeLayer object's path
        _shapeLayer.path = path;
        CGPathRelease(path);
    
        _shapeLayer.backgroundColor = [[UIColor clearColor] CGColor];
        _shapeLayer.frame = frame;
        _shapeLayer.masksToBounds = NO;
        [_shapeLayer setValue:[NSNumber numberWithBool:NO] forKey:@"isCircle"];
        _shapeLayer.fillColor = [[UIColor clearColor] CGColor];
        _shapeLayer.strokeColor = [lineColor CGColor];
        _shapeLayer.lineWidth = borderWidth;
        _shapeLayer.lineDashPattern = [NSArray arrayWithObjects:[NSNumber numberWithInt:dashPattern1], [NSNumber numberWithInt:dashPattern2], nil];
        _shapeLayer.lineCap = kCALineCapRound;
    
        //_shapeLayer is added as a sublayer of the view, the border is visible
        [v.layer addSublayer:_shapeLayer];
        v.layer.cornerRadius = cornerRadius;
    }
    

    This piece of code adds a dashed line, but you can modify that by _shapeLayer.lineDashPattern.

提交回复
热议问题