教你把UIView切成任意形状 通过ShapeLayer

有时候layer.cornerRadius并不能满足需求,自己实现drawRect又太麻烦,怎么办?

多的不说,直接上代码:

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
- (void)dwMakeBottomRoundCornerWithRadius:(CGFloat)radius
{
    CGSizesize = self.frame.size;
    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    [shapeLayersetFillColor:[[UIColorwhiteColor]CGColor]];
     
    CGMutablePathRefpath = CGPathCreateMutable();
    CGPathMoveToPoint(path,NULL, size.width - radius, size.height);
    CGPathAddArc(path,NULL, size.width-radius, size.height-radius, radius, M_PI/2,0.0,YES);
    CGPathAddLineToPoint(path,NULL, size.width, 0.0);
    CGPathAddLineToPoint(path,NULL,0.0,0.0);
    CGPathAddLineToPoint(path,NULL,0.0, size.height - radius);
    CGPathAddArc(path,NULL, radius, size.height - radius, radius, M_PI, M_PI/2,YES);
    CGPathCloseSubpath(path);
    [shapeLayersetPath:path];
    CFRelease(path);
    self.layer.mask = shapeLayer;//layer的mask,顾名思义,是种位掩蔽,在shapeLayer的填充区域中,alpha值不为零的部分,self会被绘制;alpha值为零的部分,self不会被绘制
}
 
- (id)initWithFrame:(CGRect)frame
{
    if(self= [superinitWithFrame:frame])
    {
        [selfdwMakeBottomRoundCornerWithRadius:3.0];
    }
    returnself;
}

这样就能切出一个只有下半部圆角的View

这种方法,只要稍作修改就能实现很多效果,比如一个多边形的按钮,把一张图片切成邮票。

UIView:

layer.mask:

最终绘制:

阅读更多
个人分类: ios
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

教你把UIView切成任意形状 通过ShapeLayer

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭