Dashed line border around UIView

后端 未结 23 2404
粉色の甜心
粉色の甜心 2020-12-02 04:16

How do I add dashed line border around UIView.

Something Like this

\"\"

23条回答
  •  醉酒成梦
    2020-12-02 04:29

    Building upon what Prasad G has suggested I created a method inside a UIImage Extras class with the following:

    - (CAShapeLayer *) addDashedBorderWithColor: (CGColorRef) color {
        CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    
        CGSize frameSize = self.size;
    
        CGRect shapeRect = CGRectMake(0.0f, 0.0f, frameSize.width, frameSize.height);
        [shapeLayer setBounds:shapeRect];
        [shapeLayer setPosition:CGPointMake( frameSize.width/2,frameSize.height/2)];
    
        [shapeLayer setFillColor:[[UIColor clearColor] CGColor]];
        [shapeLayer setStrokeColor:color];
        [shapeLayer setLineWidth:5.0f];
        [shapeLayer setLineJoin:kCALineJoinRound];
        [shapeLayer setLineDashPattern:
         [NSArray arrayWithObjects:[NSNumber numberWithInt:10],
          [NSNumber numberWithInt:5],
          nil]];
        UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:shapeRect cornerRadius:15.0];
        [shapeLayer setPath:path.CGPath];
    
        return shapeLayer;
    }
    

    It's important to point out that if you define your shape's position as (0,0), the bottom corner of the border will be placed in the center of the image, that's why I set it to: (frameSize.width/2,frameSize.height/2)

    I then use my method to get the dashed border using the UIImage of my UIImageView and add the CAShapeLayer as a sublayer of the UIImageView layer:

    [myImageView.layer addSublayer:[myImageView.image addDashedBorderWithColor:[[UIColor whiteColor] CGColor]]];
    

提交回复
热议问题