iOS UIView 单边剪裁

UIView 的clipToBounds属性 和 CALayer的maskToBounds属性,都可以实现视图的四周剪裁,即超出视图范围不显示

但是如果只想超出某一边的视图不显示,另外几边的视图超出部分依旧显示,这种需求怎么处理呢?

有一个比较简单,但是并不灵活的方式的

UIView *view = [[UIView alloc] initWithFrame:CGRectMake(50, 100, 200, 200)];
    view.clipsToBounds = NO;
    view.backgroundColor = [UIColor redColor];
    
    CAShapeLayer *layer = [CAShapeLayer layer];
    layer.path = [UIBezierPath bezierPathWithRect:CGRectMake(0, -50, 300, 300)].CGPath;
    view.layer.borderWidth = 1;
    view.layer.borderColor = [UIColor blackColor].CGColor;
    view.layer.mask = layer;
    
    UIView *sub = [[UIView alloc] initWithFrame:CGRectMake(-20, -20, 240, 240)];
    sub.backgroundColor = [[UIColor blueColor] colorWithAlphaComponent:0.3];
    [view addSubview:sub];
    [self.view addSubview:view];

这种方式,可以使得view左边被剪裁,超出左边的部分不显示,其他几边超出的部分依旧会显示
只是需要严格计算超出的部分的大小,才能达到比较理想的效果

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容