给图片设置任意个圆角

  有时候,我们做cell的时候回遇到这种需求

  

  要求,tableview中每一组的第一个cell和最后一个cell显示两个圆角

  一听到圆角,估计很多人会想到下面两句代码,但是,做不到上面这种效果.

  layer.cornerRadius = 10;

     layer.masksToBounds = YES;

  其实最简单的办法可以让美工(UI设计师)做两张这种背景图片,然后设置cell的cell.backgroundView 就完成了,这是最快的办法,但是如果UI不给的话,只能是:一言不合就裁剪图片了.

  说到裁剪图片,想到的是CAShapeLayer,别问我为什么,因为它有一个属性是path,然后想到用UIBezierPath中的一个方法

+ (instancetype)bezierPathWithRoundedRect:(CGRect)rect byRoundingCorners:(UIRectCorner)corners cornerRadii:(CGSize)cornerRadii;

 这个方法中的UIRectCorner是一个枚举,有如下值:

  UIRectCornerTopLeft     = 1 << 0,

    UIRectCornerTopRight    = 1 << 1,

    UIRectCornerBottomLeft  = 1 << 2,

    UIRectCornerBottomRight = 1 << 3,

    UIRectCornerAllCorners  = ~0UL

  这下就简单多了,上代码:

  

  在storyboard中就放了一个UIImageview,随意设置了一张图片.

  

//
//  ViewController.m
//  设置圆角
//
//  Created by hqw on 16/4/20.
//  Copyright © 2016年 墨鸦. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:self.imageView.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(10, 10)];
    CAShapeLayer *layer = [CAShapeLayer layer];
    layer.frame = self.imageView.bounds;
    layer.path = path.CGPath;
    self.imageView.layer.mask = layer;
}


@end

  运行效果如下:

  

  到时候只需设置对应的cell.layer就可以了满足要求了.

 

posted @ 2016-04-21 01:12  墨鸦  阅读(294)  评论(0)    收藏  举报