ZXVideoPlayerBatteryView.m 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. //
  2. // ZXVideoPlayerBatteryView.m
  3. // ZXVideoPlayer
  4. //
  5. // Created by Shawn on 16/4/23.
  6. // Copyright © 2016年 Shawn. All rights reserved.
  7. //
  8. #import "ZXVideoPlayerBatteryView.h"
  9. @implementation ZXVideoPlayerBatteryView
  10. - (void)dealloc
  11. {
  12. [[NSNotificationCenter defaultCenter] removeObserver:self];
  13. }
  14. - (instancetype)initWithFrame:(CGRect)frame
  15. {
  16. self = [super initWithFrame:frame];
  17. if (self) {
  18. self.backgroundColor = [UIColor clearColor];
  19. [self setInitialBatteryLevel];
  20. [self addBatteryObserver];
  21. }
  22. return self;
  23. }
  24. - (void)drawRect:(CGRect)rect
  25. {
  26. CGFloat borderWidth = 1.0; // 边框线宽
  27. CGFloat margin = 1.0; // 电量填充rect距边框的距离
  28. CGFloat blockWidth = 2.0;
  29. CGFloat blockHeight = 6.0;
  30. [[UIColor whiteColor] set];
  31. // 电池矩形框(self内边缘绘制边框)
  32. UIBezierPath *borderPath = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(borderWidth / 2, borderWidth / 2, CGRectGetWidth(self.bounds) - borderWidth - blockWidth, CGRectGetHeight(self.bounds) - borderWidth) cornerRadius:3];
  33. borderPath.lineWidth = borderWidth;
  34. [borderPath stroke];
  35. // 电池正极 (只有 topRight && bottomRight 两个角有圆角)
  36. UIBezierPath *blockPath = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(CGRectGetMaxX(borderPath.bounds) + borderWidth / 2, CGRectGetMidY(borderPath.bounds) - blockHeight / 2, blockWidth, blockHeight) byRoundingCorners:UIRectCornerTopRight | UIRectCornerBottomRight cornerRadii:CGSizeMake(blockWidth / 2, blockHeight / 2)];
  37. blockPath.lineWidth = 0.01;
  38. [blockPath fill];
  39. [blockPath stroke];
  40. // 填充电量 (距离边框保留magin单位宽度)
  41. CGContextFillRect(UIGraphicsGetCurrentContext(), CGRectMake(borderWidth + margin, borderWidth + margin, ((CGRectGetWidth(borderPath.bounds) - borderWidth - margin) - margin) * self.batteryLevel, CGRectGetHeight(self.bounds) - (borderWidth + margin) * 2));
  42. }
  43. - (void)setInitialBatteryLevel
  44. {
  45. [UIDevice currentDevice].batteryMonitoringEnabled = YES;
  46. self.batteryLevel = [UIDevice currentDevice].batteryLevel;
  47. }
  48. - (void)addBatteryObserver
  49. {
  50. // or use [[UIDevice currentDevice] addObserver:self forKeyPath:@"batteryLevel" options:NSKeyValueObservingOptionNew context:NULL];
  51. // 以上方法调用次数相对较多,所以修改为仅当值改变时重绘
  52. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onBatteryLevelChanged:) name:UIDeviceBatteryLevelDidChangeNotification object:nil];
  53. }
  54. - (void)onBatteryLevelChanged:(NSNotification *)noti
  55. {
  56. self.batteryLevel = ((UIDevice *)noti.object).batteryLevel;
  57. [self setNeedsDisplay]; // redrawn battery view
  58. }
  59. @end