使用 uibezierpath 在 UIView 上绘制边框

draw border on UIView using uibezierpath

我需要你帮助使用 uibezierpath 或类似工具在 UIView 上绘制此边框。

我已经制定了这个解决方案:在另一个 UIView 中嵌套一个 UIView,但我认为有更好的解决方案:

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];

    self.theView.layer.cornerRadius = self.theView.bounds.size.width/2;
    self.theView.layer.masksToBounds = YES;

    UIView *borderView = [[UIView alloc] initWithFrame:CGRectMake(4, 4, CGRectGetWidth(self.theView.frame) - 8, CGRectGetHeight(self.theView.frame) - 8)];
    borderView.backgroundColor = [UIColor grayColor];
    borderView.layer.cornerRadius = self.theView.bounds.size.width/2;
    borderView.layer.masksToBounds = YES;

    self.theView.layer.borderWidth = 2;
    self.theView.layer.borderColor = [UIColor redColor].CGColor;
    self.theView.backgroundColor = [UIColor clearColor];
    [self.theView addSubview:borderView];

}

谢谢。

您可以使用两条贝塞尔曲线路径将其绘制在一个 UIView 中。 UIView 的子类并将其包含在 UIView drawRect 方法中,

-(void)drawRect:(CGRect)frame
{
    UIBezierPath* ovalPath = [UIBezierPath bezierPathWithOvalInRect: CGRectMake(CGRectGetMinX(frame) + 2, CGRectGetMinY(frame) + 2.5, CGRectGetWidth(frame) - 5, CGRectGetHeight(frame) - 5)];
    [UIColor.redColor setStroke];
    ovalPath.lineWidth = 1;
    [ovalPath stroke];

   UIBezierPath* oval2Path = [UIBezierPath bezierPathWithOvalInRect: CGRectMake(CGRectGetMinX(frame) + 10, CGRectGetMinY(frame) + 10, CGRectGetWidth(frame) - 20, CGRectGetHeight(frame) - 20)];
    [UIColor.lightGrayColor setFill];
    [oval2Path fill];
}