使用uibezierpath在UIView上绘制边框

时间:2016-07-19 19:53:04

标签: ios objective-c uiview border

我需要你帮助使用uibezierpath或类似的东西在UIView上绘制这个边框。

enter image description here

我已经制定了这个解决方案:在另一个中嵌入一个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];

}

感谢。

1 个答案:

答案 0 :(得分:5)

您可以使用两个贝塞尔曲线路径在一个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];
}

enter image description here