iOS基础扩展ios框架我的ios进阶

计算内存空间

2016-03-13  本文已影响397人  南方_H

在项目很多地方可能都会查询一些硬件的信息,比如说,计算手机所剩内存空间,我们将信息通过一个视图显示在界面上:

FOUNDATION_EXPORT NSString * const NSFileSystemSize;
FOUNDATION_EXPORT NSString * const NSFileSystemFreeSize;
FOUNDATION_EXPORT NSString * const NSFileSystemNodes;
FOUNDATION_EXPORT NSString * const NSFileSystemFreeNodes;
@interface HTStorageSpaceView()

@property (nonatomic, strong) UIImageView *progressImg;
@property (nonatomic, strong) UIImageView *trackImg;
/**
 *  空间所剩标签展示
 */
@property (nonatomic, strong) UILabel *progressLable;
@end

@implementation HTStorageSpaceView

- (instancetype)initWithFrame:(CGRect)frame{
    
    self = [super initWithFrame:frame];
    
    if (self) {
        
        _progressImg           = [[UIImageView alloc]init];
        _trackImg              = [[UIImageView alloc]init];
        
        _progressImg.image     = [self createImageWithColor:GREEN_SYSTEM_COLOR];
        _trackImg.image        = [self createImageWithColor:GRAY_LINE_COLOR];
        
        _progressLable         = [[UILabel alloc]init];
        _progressLable.font    = [UIFont systemFontOfSize:12];
        _progressLable.textColor =  WHITECOLOR;
        
        
        _progressLable.textAlignment = NSTextAlignmentCenter;
        
        [self loadSpaceWishFrame:frame];
        
        [self addSubview:_progressImg];
        [self addSubview:_trackImg];
        [self addSubview:_progressLable];
    }
    return self;
}
/**
 *  加载剩余空间
 */
- (void)loadSpaceWishFrame:(CGRect)frame{
    
    NSDictionary *fattributes = [[NSFileManager defaultManager] attributesOfFileSystemForPath:NSHomeDirectory() error:nil];
    
    //总空间
    float   space     =   [[fattributes objectForKey:NSFileSystemSize] floatValue];
    //所剩空间
    float   freespace =   [[fattributes objectForKey:NSFileSystemFreeSize] floatValue];
    
    
    float free_m  =  freespace / 1024 / 1024 / 1024;
    float space_m =  space / 1024 / 1024 / 1024;
    float proportion = free_m / space_m;
    
    
    _progressImg.frame      = CGRectMake(0, 0,(1 - proportion) * frame.size.width, frame.size.height);
    _trackImg.frame         = CGRectMake((1 - proportion) * frame.size.width , 0, WIDTH - (1 - proportion) * frame.size.width , frame.size.height);
    _progressLable.text     = [NSString stringWithFormat:@"总空间%.1fG/剩余%.1fG",space_m,free_m]; 
    _progressLable.frame    = CGRectMake(0, 0, WIDTH, frame.size.height -2);
    
}
-(UIImage *) createImageWithColor: (UIColor *) color
{
    CGRect rect=CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return theImage;
}

效果如下:


IMG_4729.jpg
上一篇 下一篇

猜你喜欢

热点阅读