美文网首页学无止境iOS Developer恩美第二个APP项目
View.layer.mask属性的应用(画圆角,画心)

View.layer.mask属性的应用(画圆角,画心)

作者: 這Er | 来源:发表于2017-02-16 14:04 被阅读130次

    前言

    看到什么app,脑子里都会不自觉的想这个东西是怎么实现的。哔哩哔哩作为我用来偶尔看看鬼畜,追追新番的一个应用,感觉它某些细节的设计确实不错。例如下图中的标注处的圆角

    哔哩哔哩的iOS客户端首页截图

    设置View的四个角都为圆角

    像图中处的4个角都为圆角,这都是一些基础的东西感觉就没必要写了,什么你还不知道?特别简单,只需要设置下面的属性就可以了,产生圆角引发的性能问题此处不做讨论,这样写一般应用是没有问题的

    view.layer.cornerRadius = 10;
    view.layer.masksToBounds = YES;
    

    设置View的两个角都为圆角

    像图中的两个圆角,当然就实现效果来说,方法有很多种,此处讲一个,使用CALayer的mask属性:

    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.bounds
                                                       byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight
                                                             cornerRadii:CGSizeMake(15, 15)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = self.bounds;
    maskLayer.path = maskPath.CGPath;
    self.layer.mask = maskLayer;
    

    设置View显示一个心形❤️

    其实和显示两个圆角的方法差不多,只不过就是绘制图形的路径不一样
    下图的图片上使用两根贝塞尔曲线绘制了一个心形❤️,曲线的算式,想要看的可以看下github的工程

    各个形状的展示

    总结

    mask属性是做什么的?
    看下苹果文档的描述:

    The layer’s alpha channel determines how much of the layer’s content and background shows through. Fully or partially opaque pixels allow the underlying content to show through but fully transparent pixels block that content.
    
    The default value of this property is nil nil. When configuring a mask, remember to set the size and position of the mask layer to ensure it is aligned properly with the layer it masks.
    

    翻译成中文就是:

    这个layer的alpha通道决定展示多少layer的内容和背景,完全或部分不透明的像素允许下面的内容展示出来,但是完全透明的像素会阻碍内容

    为什么用CAShapeLayer + UIBezierPath哪?

    UIBezierPath是系统对画图方法的封装,可以很方便的调用,获取路径path
    @property(nonatomic) CGPathRef CGPath;

    CAShapeLayer有path属性
    @property(nullable) CGPathRef path;
    可以很方便的将你画的path绘制到layer上

    这两个搭配简直就是珠连璧合、相得益彰、相辅相成、不好意思没词了。。。

    相关文章

      网友评论

        本文标题:View.layer.mask属性的应用(画圆角,画心)

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