iOS-電池圖標【結合貝塞爾曲線控制電量顯示】


 

基於UIView類:WKJBatteryView

WKJBatteryView.h

#import <UIKit/UIKit.h>

@interface WKJBatteryView : UIView /** value:0 - 100 */
- (void)setBatteryValue:(NSInteger)value; @end

WKJBatteryView.m

#import "WKJBatteryView.h"
@interface WKJBatteryView() ///電池寬度
@property (nonatomic,assign) CGFloat b_width; ///電池高度
@property (nonatomic,assign) CGFloat b_height; ///電池外線寬
@property (nonatomic,assign) CGFloat b_lineW; @property (nonatomic,strong) UIView *batteryView; @end
@implementation WKJBatteryView - (instancetype)initWithFrame:(CGRect)frame{ self = [super initWithFrame:frame]; if (self) { [self drawBattery]; } return self; } ///畫圖標
- (void)drawBattery{ ///x坐標
    CGFloat b_x = 1; ///y坐標
    CGFloat b_y = 1; _b_height = self.bounds.size.height - 2; _b_width = self.bounds.size.width - 5; _b_lineW = 1; //畫電池【左邊電池】
    UIBezierPath *pathLeft = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(b_x, b_y, _b_width, _b_height) cornerRadius:2]; CAShapeLayer *batteryLayer = [CAShapeLayer layer]; batteryLayer.lineWidth = _b_lineW; batteryLayer.strokeColor = [UIColor lightGrayColor].CGColor; batteryLayer.fillColor = [UIColor clearColor].CGColor; batteryLayer.path = [pathLeft CGPath]; [self.layer addSublayer:batteryLayer]; //畫電池【右邊電池箭頭】
    UIBezierPath *pathRight = [UIBezierPath bezierPath]; [pathRight moveToPoint:CGPointMake(b_x + _b_width+1, b_y + _b_height/3)]; [pathRight addLineToPoint:CGPointMake(b_x + _b_width+1, b_y + _b_height * 2/3)]; CAShapeLayer *layerRight = [CAShapeLayer layer]; layerRight.lineWidth = 2; layerRight.strokeColor = [UIColor lightGrayColor].CGColor; layerRight.fillColor = [UIColor clearColor].CGColor; layerRight.path = [pathRight CGPath]; [self.layer addSublayer:layerRight]; ///電池內填充
    _batteryView = [[UIView alloc]initWithFrame:CGRectMake(b_x + 1,b_y + _b_lineW, 0, _b_height - _b_lineW * 2)]; _batteryView.layer.cornerRadius = 2; _batteryView.backgroundColor = [UIColor colorWithRed:0.324 green:0.941 blue:0.413 alpha:1.000]; [self addSubview:_batteryView]; } ///控制電量顯示
- (void)setBatteryValue:(NSInteger)value{ if (value<10) { _batteryView.backgroundColor = [UIColor redColor]; }else{ _batteryView.backgroundColor = [UIColor colorWithRed:0.324 green:0.941 blue:0.413 alpha:1.000]; } CGRect rect = _batteryView.frame; rect.size.width = (value*(_b_width - _b_lineW * 2))/100; _batteryView.frame = rect; } @end
 
封裝好WKJBatteryView后,直接 initWithFrame 實例化引用,然后添加到試圖上就可以了,下面是效果:
 

 

落日熔金,暮雲合璧,人在何處。染柳煙濃,吹梅笛怨,春意知幾許。元宵佳節,融和天氣,次第豈無風雨。來相召、香車寶馬,謝他酒朋詩侶。中州盛日,閨門多暇,記得偏重三五。鋪翠冠兒,捻金雪柳,簇帶爭濟楚。如今憔悴,風鬟霜鬢,怕見夜間出去。不如向、簾兒底下,聽人笑語。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM