ios - 带边框的 cornerRadius : Glitch around border

标签 ios objective-c calayer

我的应用程序主要是基于圆形和边框的。

我使用 UIView 的图层属性来设置圆角半径和边框。

但是我遇到了一个问题,角不清晰。

我得到以下结果:

UIButton

screenshot of a button with rounded corners and a border

UIImageView

screenshot of an image view with rounded corners and a border

您可以在白色或灰色边框周围观察到一条细边框线。

这是我的代码:

button.layer.borderWidth = 2.0;
button.layer.borderColor = [[UIColor whiteColor] CGColor];
button.layer.cornerRadius = 4;

button.clipsToBounds = YES;

我已经搜索过解决这个问题,但没有成功。

我试过 button.layer.masksToBounds = YES,但没有效果。

我错过了什么吗?还是有任何其他方法可以给我比 CALayer 更好的结果?

最佳答案

我尝试了很多解决方案,最后使用 UIBezierPath

我创建了 UIView 的类别并添加了制作圆形矩形和边框的方法。

这是该类别的方法:

- (void)giveBorderWithCornerRadious:(CGFloat)radius borderColor:(UIColor *)borderColor andBorderWidth:(CGFloat)borderWidth
{
    CGRect rect = self.bounds;
    
    //Make round
        // Create the path for to make circle
        UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:rect
                                                       byRoundingCorners:UIRectCornerAllCorners
                                                             cornerRadii:CGSizeMake(radius, radius)];

        // Create the shape layer and set its path
        CAShapeLayer *maskLayer = [CAShapeLayer layer];

        maskLayer.frame = rect;
        maskLayer.path  = maskPath.CGPath;
        
        // Set the newly created shape layer as the mask for the view's layer
        self.layer.mask = maskLayer;
    
    //Give Border
        //Create path for border
        UIBezierPath *borderPath = [UIBezierPath bezierPathWithRoundedRect:rect
                                                         byRoundingCorners:UIRectCornerAllCorners
                                                               cornerRadii:CGSizeMake(radius, radius)];

        // Create the shape layer and set its path
        CAShapeLayer *borderLayer = [CAShapeLayer layer];
        
        borderLayer.frame       = rect;
        borderLayer.path        = borderPath.CGPath;
        borderLayer.strokeColor = [UIColor whiteColor].CGColor;
        borderLayer.fillColor   = [UIColor clearColor].CGColor;
        borderLayer.lineWidth   = borderWidth;
        
        //Add this layer to give border.
        [[self layer] addSublayer:borderLayer];
}

我从这篇精彩的文章中得到了使用 UIBezierPath 的想法:Thinking like a Bézier path

我从这两个链接获得大部分代码:

注意:这是类别方法,因此 self 代表调用此方法的 View 。如 UIButton、UIImageView 等

关于ios - 带边框的 cornerRadius : Glitch around border,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25551053/

相关文章:

ios - 字段 `lyrics` 对于 swift 中当前播放歌曲的 MPMediaItem 是空的,ios 12+

objective-c - Cocoa 应用程序菜单栏不可点击

ios - 如何在单行中的两个单元格之间设置没有间隙的 Collection View 单元格

ios - 使用 AFNetworking setImageWithURL : 设置 UIImageView 圆角

ios - 未调用 Swift viewWillTransition

ios - 处理 Parse 中的某些错误

iphone - 为什么我们需要将Apple的In App Payment收据存储到服务器?

objective-c - 清空核心数据 NSSet(多个关系)

swift - 在 CALayer 中绘制 UIBezierPath 时上下文无效

ios - CAKeyFrameAnimation表现层似乎没有改变