如何在不设置图像的情况下更改 UIButton 上 ImageView 的背景颜色? (例如,我在按钮文本旁边有一个红色方 block )。
当我简单地设置 mybutton.imageView.backgroundColor = UIColor.red
并将 ImageView 的约束设置为 28x28px
时。我没有看到红色方 block 。
谢谢。
澄清一下:我只想为 UIButton 的 ImageView 设置背景颜色 - 我不想为整个按钮着色!
最佳答案
您将问题标记为 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)
}
}
然后,添加“按钮文本旁边的红色方 block ”:
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
,否则图像将被“着色”。
关于ios - UIButton:设置 ImageView 的背景(不设置图像),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47153925/