[自定义组件之一]利用calyer的遮罩处理圆形图片显示

#import <UIKit/UIKit.h>

@interface CircleImgageView : UIImageView

@end
#import "CircleImgageView.h"
@interface CircleImgageView ()
@property (nonatomic,strong) CALayer* ShowLayer;
@end

@implementation CircleImgageView
-(instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        self.ShowLayer = [CALayer layer];
        [self.layer addSublayer:self.ShowLayer];
        float imgDiameter = MIN(self.frame.size.width, self.frame.size.height);
        float x = (self.frame.size.width - imgDiameter) / 2;
        float y = (self.frame.size.height - imgDiameter) / 2;
        float w = imgDiameter;
        float h = imgDiameter;
        self.ShowLayer.frame = CGRectMake(x, y, w, h);
        self.ShowLayer.backgroundColor = [[UIColor blackColor] CGColor];
        self.ShowLayer.cornerRadius = imgDiameter / 2;
        self.layer.mask = self.ShowLayer;
        self.layer.masksToBounds = YES;
        
    }
    return self;
}
@end
<pre name="code" class="objc">CircleImgageView* c = [[CircleImgageView alloc] initWithFrame:CGRectMake(10, 20, 175, 175)];
    c.image = [UIImage imageNamed:@"J罗.jpg"];
    [self.view addSubview:c];
 
 
 总结: 
 

   1,利用了calayer的mask属性实现。

   2,addsublayer,设置mask 这两个有顺序区别,总之组件会响应最后一次的刷新状态。

   3,可以利用png图片,带alpha的那种,有渐变效果。


你可能感兴趣的:(ios,图片,自定义组件)