您将您的问题标记为Swift 和Objective-C,所以...
在 Swift 中,您可以使用此扩展程序创建具有特定颜色的“空白”图像:
public extension UIImage {
public convenience init?(color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) {
let rect = CGRect(origin: .zero, size: size)
UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)
color.setFill()
UIRectFill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
guard let cgImage = image?.cgImage else { return nil }
self.init(cgImage: cgImage)
}
}
然后,在按钮文本旁边添加一个“红色方块”:
let btnImage = UIImage(color: .red, size: CGSize(width: 28, height: 28))
btn.setImage(btnImage, for: .normal)
如果你需要在 Obj-C 中这样做,它的过程是相同的:
- (UIImage *)imageWithColor:(UIColor *)color andSize:(CGSize)sz {
CGRect rect = CGRectMake(0.0f, 0.0f, sz.width, sz.height);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [color CGColor]);
CGContextFillRect(context, rect);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
和
UIImage *btnImage = [self imageWithColor:[UIColor redColor] andSize:CGSizeMake(28.0, 28.0)];
[_btn setImage:btnImage forState:UIControlStateNormal];
注意:确保您的UIButton 类型设置为Custom,否则图像将被“着色”。