iOS开发:UIColor转成纯色图片(UIImage)

本文介绍如何将UIColor转换为UIImage,提供了Objective-C和Swift两种版本的实现代码。Objective-C版本使用了UIKIT_EXTERN宏定义,而Swift版本则通过扩展UIColor类来实现。文中详细展示了如何创建一个指定大小的图像上下文,设置填充颜色,并获取最终的图像。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Objective-c 版本

UIKIT_EXTERN UIImage * __nullable UIColorAsImage(UIColor * __nonnull color, CGSize size) {
    
    CGRect rect = CGRectMake(0, 0, size.width, size.height);
    
    UIGraphicsBeginImageContextWithOptions(rect.size, NO, [UIScreen mainScreen].scale);
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context,color.CGColor);
    CGContextFillRect(context, rect);
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
}

使用

// 复制上面代码放在任意头文件中,并引用该头文件,在需要的地方调用如下
UIImage *image = UIColorAsImage([UIColor redColor], CGSizeMake(200, 100));

Swift 版本

extension UIColor {
    
    func asImage(_ size: CGSize) -> UIImage? {
        
        var resultImage: UIImage? = nil
        let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
        UIGraphicsBeginImageContextWithOptions(rect.size, false, UIScreen.main.scale)
        
        guard let context = UIGraphicsGetCurrentContext() else {
            
            return resultImage
        }
        
        context.setFillColor(self.cgColor)
        context.fill(rect)
        resultImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        return resultImage
    }
}

使用

let colorImage = UIColor.black.asImage(CGSize(width: 100, height: 100));
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Harvey66

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值