BackgroundButton.m 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. //
  2. // BackgroundButton.m
  3. // XenonSDK
  4. //
  5. // Created by SAGESSE on 2019/5/29.
  6. // Copyright © 2019 SAGESSE. All rights reserved.
  7. //
  8. #import "BackgroundButton.h"
  9. UIImage* makeImage(UIColor* newValue) {
  10. if (newValue == nil) {
  11. return nil;
  12. }
  13. CGRect rect = CGRectMake(0, 0, 4, 4);
  14. UIGraphicsBeginImageContext(rect.size);
  15. CGContextRef context = UIGraphicsGetCurrentContext();
  16. CGContextSetFillColorWithColor(context, newValue.CGColor);
  17. CGContextFillRect(context, rect);
  18. UIImage* image = UIGraphicsGetImageFromCurrentImageContext();
  19. UIGraphicsEndImageContext();
  20. return image;
  21. }
  22. @implementation BackgroundButton
  23. - (void)setBackgroundColor:(id)backgroundColor {
  24. [super setBackgroundColor:UIColor.clearColor];
  25. // update background image.
  26. dispatch_async(dispatch_get_main_queue(), ^{
  27. id n = makeImage([backgroundColor colorWithAlphaComponent:1.0]);
  28. id h = makeImage([backgroundColor colorWithAlphaComponent:0.8]);
  29. [self setBackgroundImage:n forState: UIControlStateNormal];
  30. [self setBackgroundImage:n forState: UIControlStateNormal | UIControlStateSelected];
  31. [self setBackgroundImage:h forState: UIControlStateHighlighted];
  32. [self setBackgroundImage:h forState: UIControlStateHighlighted | UIControlStateSelected];
  33. });
  34. }
  35. @end