iOS指定圆角的位置


使用CAShapeLayerUIBezierPath设置圆角

UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];

    imageView.image = [UIImage imageNamed:@"ingq"];

    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:imageView.bounds byRoundingCorners:UIRectCornerAllCorners cornerRadii:imageView.bounds.size];

    CAShapeLayer *maskLayer = [[CAShapeLayer alloc]init];

    //设置大小
    maskLayer.frame = imageView.bounds;

    //设置图形样子
    maskLayer.path = maskPath.CGPath;

    imageView.layer.mask = maskLayer;

    [self.view addSubview:imageView];

指定需要成为圆角的角,可使用的方法:

+ (UIBezierPath *)bezierPathWithRoundedRect:(CGRect)rect
                          byRoundingCorners:(UIRectCorner)corners
                                cornerRadii:(CGSize)cornerRadii

该方法中corners参数指定了要成为圆角的角, 枚举类型如下:

typedef NS_OPTIONS(NSUInteger, UIRectCorner) {
    UIRectCornerTopLeft     = 1 << 0,
    UIRectCornerTopRight    = 1 << 1,
    UIRectCornerBottomLeft  = 1 << 2,
    UIRectCornerBottomRight = 1 << 3,
    UIRectCornerAllCorners  = ~0UL
};
//设置视图位置和大小
    UIView *myView = [[UIView alloc] initWithFrame:CGRectMake(120, 300, 100, 50)];

    //设置背景颜色
    myView.backgroundColor = [UIColor redColor];

    //添加
    [self.view addSubview:myView];

    //绘制圆角 要设置的圆角 使用“|”来组合
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:myView.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerBottomRight cornerRadii:CGSizeMake(20, 20)];

    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];

    //设置大小
    maskLayer.frame = myView.bounds;

    //设置图形样子
    maskLayer.path = maskPath.CGPath;

    myView.layer.mask = maskLayer;

    UILabel *label = [[UILabel alloc]init];

    //添加文字
    label.text = @"ingq";

    //文字颜色
    label.textColor = [UIColor whiteColor];

    [myView addSubview: label];

    //自动布局
    [label mas_makeConstraints:^(MASConstraintMaker *make) {

        make.center.equalTo(myView);
    }];

附件: