iOS开发——绘图电池按百分比显示

时间:2022-11-15 22:57:38

  1、在DrawLine.h文件中提供了一个改变电池电量数值的接口

//

//  DrawLine.h

//  Demo-draw2

//

//  Created by yyt on 16/5/11.

//  Copyright © 2016年 yyt. All rights reserved.

//

#import <UIKit/UIKit.h>

@interface DrawLine : UIView

@property(nonatomic,assign) NSInteger currentNum;

@end

  2、在DrawLine.m文件中

//

//  DrawLine.m

//  Demo-draw2

//

//  Created by yyt on 16/5/11.

//  Copyright © 2016年 yyt. All rights reserved.

//

#import "DrawLine.h"

@implementation DrawLine

- (void)drawRect:(CGRect)rect {

CGContextRef bgContextRef = UIGraphicsGetCurrentContext();

CGRect frame = CGRectMake(10, 10, 40, 20);

CGContextAddRect(bgContextRef, frame);

CGContextSetLineWidth(bgContextRef, 2);

[commonBgColor setStroke];

CGContextStrokePath(bgContextRef);

CGContextMoveToPoint(bgContextRef, 50, 20);

CGContextAddLineToPoint(bgContextRef, 54, 20);

CGContextSetLineWidth(bgContextRef, 6);

CGContextStrokePath(bgContextRef);

CGContextMoveToPoint(bgContextRef, 10, 20);

CGContextAddLineToPoint(bgContextRef, 10+_currentNum*40/100, 20);

CGContextSetLineWidth(bgContextRef, 20);

CGContextStrokePath(bgContextRef);

}

@end

  3、在需要用的地方ViewController.m文件中

  我这里是写了个死数据,真正做项目的话,就需要在电量值发生改变的时候,修改currentNum值,然后setNeedsDisplay一下。

//

//  ViewController.m

//  Demo-draw2

//

//  Created by yyt on 16/5/11.

//  Copyright © 2016年 yyt. All rights reserved.

//

#import "ViewController.h"

#import "DrawLine.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {

[super viewDidLoad];

self.view.backgroundColor = [UIColor lightGrayColor];

DrawLine *lineView = [[DrawLine alloc] initWithFrame:CGRectMake(100, 100, 200, 200)];

lineView.backgroundColor = [UIColor whiteColor];

  lineView.currentNum = 87;

[self.view addSubview:lineView];

}

@end