美文网首页
iOS UIImageView 圆形

iOS UIImageView 圆形

作者: gerrywanggang | 来源:发表于2018-06-28 18:13 被阅读0次

    众所周知, UIImageView 在drawrect方法中是不走的,也就是继承UIImageView的子控件,无法在drawrect方法中重新绘制,因为该方法是失效的。

    - (void)drawRect:(CGRect)rect {

        // Drawing code

        CGFloatwidth =CGRectGetWidth(rect);

        CGFloatheight =CGRectGetHeight(rect);

        CGFloatradius = width>height?height/2.0:width/2.0;

        CGMutablePathRef path = CGPathCreateMutable();

        CGPathAddArc(path,NULL, width/2.0, height/2.0, radius,0,2*M_PI,YES);

        CAShapeLayer *maskLayer = [CAShapeLayer layer];

        maskLayer.frame= rect;

        maskLayer.path= path;

        self.layer.mask= maskLayer;

    }

    那么怎样才能让UIImageview绘制出圆形呢?需要让他走绘制的方法,如果不能走drawrect,那么采用他还会走什么方法呢?答案是layoutSubviews, 把方法写在layoutSubviews里面即可。

    #import "HZRoundImageView.h"

    @implementationHZRoundImageView

    - (instancetype)initWithFrame:(CGRect)frame {

        if(self= [superinitWithFrame:frame]) {

        }

        return self;

    }

    - (void)layoutSubviews {

        CGRectrect =self.bounds;

        // Drawing code

        CGFloatwidth =CGRectGetWidth(rect);

        CGFloatheight =CGRectGetHeight(rect);

        CGFloatradius = width>height?height/2.0:width/2.0;

        CGMutablePathRef path = CGPathCreateMutable();

        CGPathAddArc(path,NULL, width/2.0, height/2.0, radius,0,2*M_PI,YES);

        CAShapeLayer *maskLayer = [CAShapeLayer layer];

        maskLayer.frame= rect;

        maskLayer.path= path;

        self.layer.mask= maskLayer;

    }

    然后在其他地方调用, 无论是使用initWithFrame方法还是autolayout都可以变成圆形。

    调用一个例子如下:

    @implementation ViewController

    - (void)viewDidLoad {

        [super viewDidLoad];

        // Do any additional setup after loading the view, typically from a nib.

        [self initUI];

    }

    - (void)initUI {

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

        [self.view addSubview:imageView];

        [imageView setBackgroundColor:[UIColor greenColor]];

        [imageView setImage:[UIImageimageNamed:@"bbs_item0"]];

        imageView.layer.masksToBounds=YES;

        [imageView mas_makeConstraints:^(MASConstraintMaker*make) {

            make.center.equalTo(self.view);

            make.width.equalTo(self.view).multipliedBy(0.8);

            make.height.equalTo(self.view).multipliedBy(0.8);

        }];

    }

    效果如上图。

    相关文章

      网友评论

          本文标题:iOS UIImageView 圆形

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