IOS如何给VIEW设置2个圆角?set cornerRadius for only top-left and top-right corner of a UIVIEW

-----如果大家有更好的方法请告诉我,谢谢--------

有些设计中,需要实现top-left和top-right为圆角,而bottom-left and bottom-right依然是平角,这样就不能使用

_bg.layer.cornerRadius

了。

这里要用到一些基本的绘制功能UIBezierPath and CAShapeLayer

-----------

这里先看看最终效果图


注意上面的大白块,top-left and top-right是圆角,bottom-left and bottom-right是平角,然后有一个border color;

实现的具体步骤如下(给大白块定义为_bg):

一、定义一个贝赛尔曲线,作为路径绘制给_bg

UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:_bg.bounds
                                     byRoundingCorners:(UIRectCornerTopLeft|UIRectCornerTopRight)
                                           cornerRadii:CGSizeMake(10.0, 10.0)];
//    (UIRectCornerBottomLeft|UIRectCornerBottomRight)
    
CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
maskLayer.path = maskPath.CGPath;
_bg.layer.mask = maskLayer;
(标题里说绘制上面的2个角只是一种说法,其实想绘几个就绘几个。其实上面这一步就实现了标题的问题,参数请自己研究)


完成这一步,如果想给UIView添加borderColor and borderWidth,会发现,UIView直线处成功有了线条,但是曲线(圆角)并没有线条的出现,所以就有了接下的内容。


二、创建一个UIView,用来绘制展现border的,然后覆盖在_bg上面,实现borderColor的效果

UIView *strokeView = [[UIView alloc] initWithFrame:_bg.bounds];
strokeView.tag = 99;
_bg.userInteractionEnabled = NO;

注1:为什么要设置tag

注2:为什么要新建一个UIView


三、为storkeView绘制边线

CAShapeLayer *strokeLayer = [CAShapeLayer layer];
strokeLayer.path = maskPath.CGPath;
strokeLayer.fillColor = [UIColor clearColor].CGColor; //内容填充的颜色设置为clear
strokeLayer.strokeColor = [UIColor colorWithHexString:@"#e0e0e0"].CGColor; //边色
strokeLayer.lineWidth = 1; // 边宽
[strokeView.layer addSublayer:strokeLayer];
完成这一步,其实会发现,已经实现了在给_bg添加borderColor的效果;这里解释下注1和注;

注1:因为使用了AutoLayout,有时候不能确定_bg在不同设备上最终的bounds ,所以像绘制的内容如果放在viewWillLayoutSubviews方法(或者多次绘制)时,在layout之前如果不小心触发了绘制,那么绘制的bounds可能是按照xib上设计的尺寸;这里我建议就是设置一个tag,然后在每次绘制(触发)前调用

[[_bg viewWithTag:99] removeFromSuperview];
方法来清除掉borderColor,防止绘制多个strokeView在_bg上面

注2:其实直接在_bg上绘制strokeLayer是可以的,但是如果_bg里本身有内容的话,绘制因为是整个UIView绘制(不是只绘一条线),所以会把子元素给抹掉,所以还是新建一个UIView比较好


-------那么接下来,仔细看效果图其实会发现,最下面的边其实是没有borderColor的,那如何抹掉呢?-------

四、在strokeView上创建一根白色的线,覆盖下面的边线,实现抹掉效果……

CALayer *bottomBorder = [CALayer layer];
bottomBorder.frame = CGRectMake(0.0f, strokeView.bounds.size.height-1.0f, strokeView.frame.size.width, 1.0f);
bottomBorder.backgroundColor = [UIColor whiteColor].CGColor;
[strokeView.layer addSublayer:bottomBorder];
这里创建了一个图层,Rect和strokeView下面的边线的size\origin是一样的,因为白色背景,所以图层用白色,实现抹掉~


哦,最后记得把strokeView添加到_bg里

[_bg addSubview:strokeView];

----如果_bg有子元素是需要触发事件的,可以

[[_bg2 viewWithTag:99].superview sendSubviewToBack:[_bg2 viewWithTag:99]];


-----如果大家有更好的方法请告诉我,谢谢--------






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值