view的边框线(border)默认显示在最上面的坑

绘制一个圆角矩形,然后在上面盖上一个图片,


想实现如下效果:


理想效果

编写代码如下:

self.layer.borderWidth = 1;

self.layer.borderColor = borderColor.CGColor;

 self.layer.backgroundColor = backColor.CGColor;

self.layer.cornerRadius=5;

UIImageView *imgview1=[[UIImageView alloc]initWithImage:_IMAGE(@"[email protected]", nil)];

    [selfaddSubview:imgview1];

    [imgview1mas_makeConstraints:^(MASConstraintMaker *make) {

        make.top.mas_equalTo(88);

        make.left.mas_equalTo(0);

        make.right.mas_equalTo(0);

        make.height.mas_equalTo(20);

    }];

结果出来的效果是这样的:


错误效果

发现border居然没有遮盖住,刚开始还以为是坐标没对好,将left改成-1看看,还是不行,还以为是图片问题,直接添加一个view,发现在border始终在上面:

测试效果

点击查看borderWidth的属性:

/* The width of the layer's border, inset from the layer bounds. The

 * border is composited above the layer's content and sublayers and

 * includes the effects of the `cornerRadius' property. Defaults to

 * zero. Animatable. */

发现上面注明了:border is composited above the layer's content and sublayers....

怪不得!

那要怎么绘制border,又能实现被遮盖,从而显示成凹进去的效果,其实只需要改变border的绘制方式即可,封了一个绘制圆角及边框线的方法如下:

-(void)roundCornerWithCornerRadii:(CGSize)cornerRadii andCorners:(UIRectCorner)corners andBordWidth:(CGFloat)bdWidth andBordColor:(UIColor*)bdColor{

    UIBezierPath *maskPath=[UIBezierPath bezierPathWithRoundedRect:self.bounds byRoundingCorners:corners cornerRadii: cornerRadii];

    CAShapeLayer *maskLayer = [CAShapeLayer layer];

    maskLayer.path= maskPath.CGPath;

    self.layer.mask= maskLayer;

    //如果有边框,此时边框不能用self.layer.border来设置会有出入,而应该:

    if(bdWidth && bdColor) {

        //重复执行roundCornerWithCornerRadii,如果有border的话,会导致boder重叠错位,故添加boder前先清除之前的添加的

        for(CAShapeLayer*borderLayerin[self.layersublayers]) {

            if([borderLayerisKindOfClass:[CAShapeLayerclass]]) {

                [borderLayerremoveFromSuperlayer];

                break;

            }

        }

        CAShapeLayer *borderLayer=[CAShapeLayer layer];

        borderLayer.path= maskPath.CGPath;

        borderLayer.fillColor= [UIColor clearColor].CGColor;

        borderLayer.strokeColor= [bdColorCGColor];

        borderLayer.lineWidth= bdWidth;

        borderLayer.frame=self.bounds;

        [self.layeraddSublayer:borderLayer];

    }

}

最终效果如下:

正确效果

注:通过UIBezierPath绘制圆角和边框线,好处多多,还能优化UI性能哦!

你可能感兴趣的:(view的边框线(border)默认显示在最上面的坑)