视图遮罩的实现

2018-07-24  本文已影响0人  Oceanj

ios遮罩就是将原始图片或者视图通过遮罩的方式修改原有的显示,比如最简单的将方形图片显示成圆角图片,很多人会通过layer.cornerRadius实现:

UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
imageView.image = [UIImage imageNamed:@"head_icon"];
imageView.layer.cornerRadius = 50.f;

这种方式效率不高,用遮罩方式实现更好一些,遮罩的实现原理就是修改layer.mask的值,layer.mask也是一个layer,设置之后它将显示这个设置的layer,如下代码:

UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
imageView.image = [UIImage imageNamed:@"head_icon"];
UIBezierPath *bezierPath = [UIBezierPath bezierPathWithRoundedRect:imageView.bounds cornerRadius:50];
CAShapeLayer *layer = [CAShapeLayer layer];
    layer.path = bezierPath.CGPath;
imageView.layer.mask = layer;

以上实现了一个简单的遮罩效果,下面介绍一个显示当前电池电量的效果,先说明下电池显示时电池的外壳时固定不变的,而电池外壳内部的电量则需要根据当前电量百分比显示,需要做遮罩处理的就是电池外壳内部的图片,效果如下:

图片标题 图片标题 图片标题
-(void)layoutView:(BOOL)isDay {
    
    UIImageView *daybatteryOutFrame = [[UIImageView alloc]initWithFrame:self.frame];
    daybatteryOutFrame.image = [UIImage imageNamed:isDay?@"day_电量_outerframe":@"night_电量_outerframe"];
    [self addSubview:daybatteryOutFrame];
    
    CGRect inerLevelRect = [UIScreen mainScreen].scale >=3? CGRectMake(1, 1, 21.5, 7.8):CGRectMake(1.5, 1, 20, 7.5);
    UIImageView *daybatteryinerLevel = [[UIImageView alloc]initWithFrame:inerLevelRect];
    daybatteryinerLevel.image = [UIImage imageNamed:isDay?@"day_电量_100":@"night_电量_100"];
    [daybatteryOutFrame addSubview:daybatteryinerLevel];
    self.daybatteryinerLevel = daybatteryinerLevel;
}

-(void)setBatteryLevel:(CGFloat)level
{
    if (level < 0) {
        level = 0;
    }
    if (level > 1) {
        level = 1;
    }
    UIBezierPath *bezierPath = [UIBezierPath bezierPathWithRect:CGRectMake(0, 0, CGRectGetWidth(self.daybatteryinerLevel.frame) * level, CGRectGetHeight(self.daybatteryinerLevel.frame))];
    CAShapeLayer *levelLayer = [CAShapeLayer layer];
    levelLayer.path = bezierPath.CGPath;
    self.daybatteryinerLevel.layer.mask = levelLayer;
}
上一篇下一篇

猜你喜欢

热点阅读