OC版本
// 创建一个UIColor对象
UIColor *color = [UIColor blueColor];
// 将UIColor转换为UIImage
UIGraphicsBeginImageContext(CGSizeMake(1, 1)); // 设置图片大小
[color setFill];
UIRectFill(CGRectMake(0, 0, 1, 1));
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[readBtn setBackgroundImage:image forState:UIControlStateHighlighted];
Swift版本
方法一 直接使用setBackgroundImage方法
let button = UIButton(type: .system)
button.frame = CGRect(x: 100, y: 100, width: 200, height: 50)
button.setTitle("Button", for: .normal)
// 创建一个宽高为1x1的纯色图片作为背景
let color = UIColor.red
let image = UIImage(color: color, size: CGSize(width: 1, height: 1))
button.setBackgroundImage(image, for: .normal)
方法二 使用UIImage.resizeableImage方法
let button = UIButton(type: .system)
button.frame = CGRect(x: 100, y: 100, width: 200, height: 50)
button.setTitle("Button", for: .normal)
let color = UIColor.red
let image = UIImage.resizeableImage(with: color, size: CGSize(width: 1, height: 1))
button.setBackgroundImage(image, for: .normal)
self.view.addSubview(button)
extension UIImage {
static func resizeableImage(with color: UIColor, size: CGSize) -> UIImage {
let rect = CGRect(origin: .zero, size: size)
UIGraphicsBeginImageContextWithOptions(rect.size, false, 0)
color.setFill()
UIRectFill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image ?? UIImage()
}
}
© 版权声明
文章版权归作者所有,未经允许请勿转载。
相关文章
暂无评论...