美文网首页
半圆角矩形

半圆角矩形

作者: 上帝死了众神在堕落 | 来源:发表于2017-10-14 17:22 被阅读0次

有时候我们做项目的时候,会遇到个不同的视图,比如半圆角矩形

image.png

这样的视图我们改如何做呢?最为简单的方法就是先做一个圆角矩形,让视图的位置超出最右边,这样部分的圆角就在视图上不显示了,看上去效果就是半圆角矩形。

另外就是自定义UIButton,重新剪辑button。代码如下:

-(instancetype)initWithFrame:(CGRect)frame atType:(BUTTON_TYPE)type
{
    self = [super initWithFrame:frame];
    
    if(self){
        UIRectCorner corners;
        
        corners =  type ? UIRectCornerBottomRight | UIRectCornerTopRight :  UIRectCornerBottomLeft | UIRectCornerTopLeft;
        
        CGFloat radii = frame.size.height/2.0;
        
        UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.bounds byRoundingCorners:corners cornerRadii:CGSizeMake(radii, radii)];
        
        CAShapeLayer *maskLayer = [CAShapeLayer layer];
        
        maskLayer.frame = self.bounds;
        
        maskLayer.path = maskPath.CGPath;
        
        self.layer.mask = maskLayer;
    }
    return self;
}

最后说一下,半圆角矩形不可以设置边框,设置了边框后,圆角的边框也会被剪辑。那么如何做一个圆角边框矩形呢,我们可以给半圆角矩形画边框。画边框的代码如下:

- (void)drawRect:(CGRect)rect {
    // Drawing code
    
    CGFloat width = rect.size.width;
    CGFloat height = rect.size.height;
    //获取上下文 上下文的输出目标就是self[view]
    CGContextRef context = UIGraphicsGetCurrentContext();
    // 设置线颜色
    CGContextSetRGBStrokeColor(context, 191/255.0, 191/255.0, 191/255.0, 1);
    // 设置线宽
    CGContextSetLineWidth(context, lineWidth);
    //设置一起点
    CGContextMoveToPoint(context, width-lineWidth, lineWidth);
    CGContextAddLineToPoint(context, height/2+lineWidth, lineWidth);
    CGContextAddArc(context, height/2+lineWidth, height/2, height/2-lineWidth, -M_PI_2, M_PI_2, 1);
    CGContextAddLineToPoint(context, width-lineWidth, height-lineWidth);
    //只是画一条,【空心】
    CGContextStrokePath(context);
}

圆角矩形我们经常遇到,而且很容易就能够实现,半圆角矩形也很简单,你们一定都能够看懂的。

相关文章

网友评论

      本文标题:半圆角矩形

      本文链接:https://www.haomeiwen.com/subject/zjqfuxtx.html